three.webgpu.nodes.js 1.1 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619
  1. /**
  2. * @license
  3. * Copyright 2010-2024 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. import { Color, Vector2, Vector3, Vector4, Matrix3, Matrix4, EventDispatcher, MathUtils, ColorManagement, SRGBTransfer, NoToneMapping, StaticDrawUsage, InterleavedBuffer, DynamicDrawUsage, InterleavedBufferAttribute, NoColorSpace, UnsignedIntType, IntType, WebGLCoordinateSystem, BackSide, CubeReflectionMapping, CubeRefractionMapping, WebGPUCoordinateSystem, TangentSpaceNormalMap, ObjectSpaceNormalMap, InstancedInterleavedBuffer, InstancedBufferAttribute, DataArrayTexture, FloatType, FramebufferTexture, LinearMipmapLinearFilter, DepthTexture, Material, NormalBlending, PointsMaterial, 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, ShadowMaterial, Uint32BufferAttribute, Uint16BufferAttribute, DoubleSide, 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, 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, ArrayCamera, ArrowHelper, AttachedBindMode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BasicDepthPacking, BatchedMesh, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxHelper, BufferGeometryLoader, Cache, Camera, 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, 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, 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. class NodeMaterialObserver {
  61. constructor( builder ) {
  62. this.renderObjects = new WeakMap();
  63. this.hasNode = this.containsNode( builder );
  64. this.hasAnimation = builder.object.isSkinnedMesh === true;
  65. this.refreshUniforms = refreshUniforms;
  66. this.renderId = 0;
  67. }
  68. firstInitialization( renderObject ) {
  69. const hasInitialized = this.renderObjects.has( renderObject );
  70. if ( hasInitialized === false ) {
  71. this.getRenderObjectData( renderObject );
  72. return true;
  73. }
  74. return false;
  75. }
  76. getRenderObjectData( renderObject ) {
  77. let data = this.renderObjects.get( renderObject );
  78. if ( data === undefined ) {
  79. const { geometry, material, object } = renderObject;
  80. data = {
  81. material: this.getMaterialData( material ),
  82. geometry: {
  83. attributes: this.getAttributesData( geometry.attributes ),
  84. indexVersion: geometry.index ? geometry.index.version : null,
  85. drawRange: { start: geometry.drawRange.start, count: geometry.drawRange.count }
  86. },
  87. worldMatrix: object.matrixWorld.clone()
  88. };
  89. if ( object.center ) {
  90. data.center = object.center.clone();
  91. }
  92. if ( object.morphTargetInfluences ) {
  93. data.morphTargetInfluences = object.morphTargetInfluences.slice();
  94. }
  95. if ( renderObject.bundle !== null ) {
  96. data.version = renderObject.bundle.version;
  97. }
  98. if ( data.material.transmission > 0 ) {
  99. const { width, height } = renderObject.context;
  100. data.bufferWidth = width;
  101. data.bufferHeight = height;
  102. }
  103. this.renderObjects.set( renderObject, data );
  104. }
  105. return data;
  106. }
  107. getAttributesData( attributes ) {
  108. const attributesData = {};
  109. for ( const name in attributes ) {
  110. const attribute = attributes[ name ];
  111. attributesData[ name ] = {
  112. version: attribute.version
  113. };
  114. }
  115. return attributesData;
  116. }
  117. containsNode( builder ) {
  118. const material = builder.material;
  119. for ( const property in material ) {
  120. if ( material[ property ] && material[ property ].isNode )
  121. return true;
  122. }
  123. if ( builder.renderer.nodes.modelViewMatrix !== null || builder.renderer.nodes.modelNormalViewMatrix !== null )
  124. return true;
  125. return false;
  126. }
  127. getMaterialData( material ) {
  128. const data = {};
  129. for ( const property of this.refreshUniforms ) {
  130. const value = material[ property ];
  131. if ( value === null || value === undefined ) continue;
  132. if ( typeof value === 'object' && value.clone !== undefined ) {
  133. if ( value.isTexture === true ) {
  134. data[ property ] = { id: value.id, version: value.version };
  135. } else {
  136. data[ property ] = value.clone();
  137. }
  138. } else {
  139. data[ property ] = value;
  140. }
  141. }
  142. return data;
  143. }
  144. equals( renderObject ) {
  145. const { object, material, geometry } = renderObject;
  146. const renderObjectData = this.getRenderObjectData( renderObject );
  147. // world matrix
  148. if ( renderObjectData.worldMatrix.equals( object.matrixWorld ) !== true ) {
  149. renderObjectData.worldMatrix.copy( object.matrixWorld );
  150. return false;
  151. }
  152. // material
  153. const materialData = renderObjectData.material;
  154. for ( const property in materialData ) {
  155. const value = materialData[ property ];
  156. const mtlValue = material[ property ];
  157. if ( value.equals !== undefined ) {
  158. if ( value.equals( mtlValue ) === false ) {
  159. value.copy( mtlValue );
  160. return false;
  161. }
  162. } else if ( mtlValue.isTexture === true ) {
  163. if ( value.id !== mtlValue.id || value.version !== mtlValue.version ) {
  164. value.id = mtlValue.id;
  165. value.version = mtlValue.version;
  166. return false;
  167. }
  168. } else if ( value !== mtlValue ) {
  169. materialData[ property ] = mtlValue;
  170. return false;
  171. }
  172. }
  173. if ( materialData.transmission > 0 ) {
  174. const { width, height } = renderObject.context;
  175. if ( renderObjectData.bufferWidth !== width || renderObjectData.bufferHeight !== height ) {
  176. renderObjectData.bufferWidth = width;
  177. renderObjectData.bufferHeight = height;
  178. return false;
  179. }
  180. }
  181. // geometry
  182. const storedGeometryData = renderObjectData.geometry;
  183. const attributes = geometry.attributes;
  184. const storedAttributes = storedGeometryData.attributes;
  185. const storedAttributeNames = Object.keys( storedAttributes );
  186. const currentAttributeNames = Object.keys( attributes );
  187. if ( storedAttributeNames.length !== currentAttributeNames.length ) {
  188. renderObjectData.geometry.attributes = this.getAttributesData( attributes );
  189. return false;
  190. }
  191. // compare each attribute
  192. for ( const name of storedAttributeNames ) {
  193. const storedAttributeData = storedAttributes[ name ];
  194. const attribute = attributes[ name ];
  195. if ( attribute === undefined ) {
  196. // attribute was removed
  197. delete storedAttributes[ name ];
  198. return false;
  199. }
  200. if ( storedAttributeData.version !== attribute.version ) {
  201. storedAttributeData.version = attribute.version;
  202. return false;
  203. }
  204. }
  205. // check index
  206. const index = geometry.index;
  207. const storedIndexVersion = storedGeometryData.indexVersion;
  208. const currentIndexVersion = index ? index.version : null;
  209. if ( storedIndexVersion !== currentIndexVersion ) {
  210. storedGeometryData.indexVersion = currentIndexVersion;
  211. return false;
  212. }
  213. // check drawRange
  214. if ( storedGeometryData.drawRange.start !== geometry.drawRange.start || storedGeometryData.drawRange.count !== geometry.drawRange.count ) {
  215. storedGeometryData.drawRange.start = geometry.drawRange.start;
  216. storedGeometryData.drawRange.count = geometry.drawRange.count;
  217. return false;
  218. }
  219. // morph targets
  220. if ( renderObjectData.morphTargetInfluences ) {
  221. let morphChanged = false;
  222. for ( let i = 0; i < renderObjectData.morphTargetInfluences.length; i ++ ) {
  223. if ( renderObjectData.morphTargetInfluences[ i ] !== object.morphTargetInfluences[ i ] ) {
  224. morphChanged = true;
  225. }
  226. }
  227. if ( morphChanged ) return true;
  228. }
  229. // center
  230. if ( renderObjectData.center ) {
  231. if ( renderObjectData.center.equals( object.center ) === false ) {
  232. renderObjectData.center.copy( object.center );
  233. return true;
  234. }
  235. }
  236. // bundle
  237. if ( renderObject.bundle !== null ) {
  238. renderObjectData.version = renderObject.bundle.version;
  239. }
  240. return true;
  241. }
  242. needsRefresh( renderObject, nodeFrame ) {
  243. if ( this.hasNode || this.hasAnimation || this.firstInitialization( renderObject ) )
  244. return true;
  245. const { renderId } = nodeFrame;
  246. if ( this.renderId !== renderId ) {
  247. this.renderId = renderId;
  248. return true;
  249. }
  250. const isStatic = renderObject.object.static === true;
  251. const isBundle = renderObject.bundle !== null && renderObject.bundle.static === true && this.getRenderObjectData( renderObject ).version === renderObject.bundle.version;
  252. if ( isStatic || isBundle )
  253. return false;
  254. const notEqual = this.equals( renderObject ) !== true;
  255. return notEqual;
  256. }
  257. }
  258. /** @module NodeUtils **/
  259. // cyrb53 (c) 2018 bryc (github.com/bryc). License: Public domain. Attribution appreciated.
  260. // A fast and simple 64-bit (or 53-bit) string hash function with decent collision resistance.
  261. // Largely inspired by MurmurHash2/3, but with a focus on speed/simplicity.
  262. // See https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript/52171480#52171480
  263. // https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js
  264. function cyrb53( value, seed = 0 ) {
  265. let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
  266. if ( value instanceof Array ) {
  267. for ( let i = 0, val; i < value.length; i ++ ) {
  268. val = value[ i ];
  269. h1 = Math.imul( h1 ^ val, 2654435761 );
  270. h2 = Math.imul( h2 ^ val, 1597334677 );
  271. }
  272. } else {
  273. for ( let i = 0, ch; i < value.length; i ++ ) {
  274. ch = value.charCodeAt( i );
  275. h1 = Math.imul( h1 ^ ch, 2654435761 );
  276. h2 = Math.imul( h2 ^ ch, 1597334677 );
  277. }
  278. }
  279. h1 = Math.imul( h1 ^ ( h1 >>> 16 ), 2246822507 );
  280. h1 ^= Math.imul( h2 ^ ( h2 >>> 13 ), 3266489909 );
  281. h2 = Math.imul( h2 ^ ( h2 >>> 16 ), 2246822507 );
  282. h2 ^= Math.imul( h1 ^ ( h1 >>> 13 ), 3266489909 );
  283. return 4294967296 * ( 2097151 & h2 ) + ( h1 >>> 0 );
  284. }
  285. /**
  286. * Computes a hash for the given string.
  287. *
  288. * @method
  289. * @param {String} str - The string to be hashed.
  290. * @return {Number} The hash.
  291. */
  292. const hashString = ( str ) => cyrb53( str );
  293. /**
  294. * Computes a hash for the given array.
  295. *
  296. * @method
  297. * @param {Array<Number>} array - The array to be hashed.
  298. * @return {Number} The hash.
  299. */
  300. const hashArray = ( array ) => cyrb53( array );
  301. /**
  302. * Computes a hash for the given list of parameters.
  303. *
  304. * @method
  305. * @param {...Number} params - A list of parameters.
  306. * @return {Number} The hash.
  307. */
  308. const hash$1 = ( ...params ) => cyrb53( params );
  309. /**
  310. * Computes a cache key for the given node.
  311. *
  312. * @method
  313. * @param {Object} object - The object to be hashed.
  314. * @param {Boolean} [force=false] - Whether to force a cache key computation or not.
  315. * @return {Number} The hash.
  316. */
  317. function getCacheKey$1( object, force = false ) {
  318. const values = [];
  319. if ( object.isNode === true ) {
  320. values.push( object.id );
  321. object = object.getSelf();
  322. }
  323. for ( const { property, childNode } of getNodeChildren( object ) ) {
  324. values.push( values, cyrb53( property.slice( 0, - 4 ) ), childNode.getCacheKey( force ) );
  325. }
  326. return cyrb53( values );
  327. }
  328. /**
  329. * This generator function can be used to iterate over the node children
  330. * of the given object.
  331. *
  332. * @generator
  333. * @param {Object} node - The object to be hashed.
  334. * @param {Boolean} [toJSON=false] - Whether to return JSON or not.
  335. * @yields {Object} A result node holding the property, index (if available) and the child node.
  336. */
  337. function* getNodeChildren( node, toJSON = false ) {
  338. for ( const property in node ) {
  339. // Ignore private properties.
  340. if ( property.startsWith( '_' ) === true ) continue;
  341. const object = node[ property ];
  342. if ( Array.isArray( object ) === true ) {
  343. for ( let i = 0; i < object.length; i ++ ) {
  344. const child = object[ i ];
  345. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  346. yield { property, index: i, childNode: child };
  347. }
  348. }
  349. } else if ( object && object.isNode === true ) {
  350. yield { property, childNode: object };
  351. } else if ( typeof object === 'object' ) {
  352. for ( const subProperty in object ) {
  353. const child = object[ subProperty ];
  354. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  355. yield { property, index: subProperty, childNode: child };
  356. }
  357. }
  358. }
  359. }
  360. }
  361. const typeFromLength = /*@__PURE__*/ new Map( [
  362. [ 1, 'float' ],
  363. [ 2, 'vec2' ],
  364. [ 3, 'vec3' ],
  365. [ 4, 'vec4' ],
  366. [ 9, 'mat3' ],
  367. [ 16, 'mat4' ]
  368. ] );
  369. /**
  370. * Returns the data type for the given the length.
  371. *
  372. * @method
  373. * @param {Number} length - The length.
  374. * @return {String} The data type.
  375. */
  376. function getTypeFromLength( length ) {
  377. return typeFromLength.get( length );
  378. }
  379. /**
  380. * Returns the length for the given data type.
  381. *
  382. * @method
  383. * @param {String} type - The data type.
  384. * @return {Number} The length.
  385. */
  386. function getLengthFromType( type ) {
  387. if ( /float|int|uint/.test( type ) ) return 1;
  388. if ( /vec2/.test( type ) ) return 2;
  389. if ( /vec3/.test( type ) ) return 3;
  390. if ( /vec4/.test( type ) ) return 4;
  391. if ( /mat3/.test( type ) ) return 9;
  392. if ( /mat4/.test( type ) ) return 16;
  393. console.error( 'THREE.TSL: Unsupported type:', type );
  394. }
  395. /**
  396. * Returns the data type for the given value.
  397. *
  398. * @method
  399. * @param {Any} value - The value.
  400. * @return {String?} The data type.
  401. */
  402. function getValueType( value ) {
  403. if ( value === undefined || value === null ) return null;
  404. const typeOf = typeof value;
  405. if ( value.isNode === true ) {
  406. return 'node';
  407. } else if ( typeOf === 'number' ) {
  408. return 'float';
  409. } else if ( typeOf === 'boolean' ) {
  410. return 'bool';
  411. } else if ( typeOf === 'string' ) {
  412. return 'string';
  413. } else if ( typeOf === 'function' ) {
  414. return 'shader';
  415. } else if ( value.isVector2 === true ) {
  416. return 'vec2';
  417. } else if ( value.isVector3 === true ) {
  418. return 'vec3';
  419. } else if ( value.isVector4 === true ) {
  420. return 'vec4';
  421. } else if ( value.isMatrix3 === true ) {
  422. return 'mat3';
  423. } else if ( value.isMatrix4 === true ) {
  424. return 'mat4';
  425. } else if ( value.isColor === true ) {
  426. return 'color';
  427. } else if ( value instanceof ArrayBuffer ) {
  428. return 'ArrayBuffer';
  429. }
  430. return null;
  431. }
  432. /**
  433. * Returns the value/object for the given data type and parameters.
  434. *
  435. * @method
  436. * @param {String} type - The given type.
  437. * @param {...Any} params - A parameter list.
  438. * @return {Any} The value/object.
  439. */
  440. function getValueFromType( type, ...params ) {
  441. const last4 = type ? type.slice( - 4 ) : undefined;
  442. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  443. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  444. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  445. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  446. }
  447. if ( type === 'color' ) {
  448. return new Color( ...params );
  449. } else if ( last4 === 'vec2' ) {
  450. return new Vector2( ...params );
  451. } else if ( last4 === 'vec3' ) {
  452. return new Vector3( ...params );
  453. } else if ( last4 === 'vec4' ) {
  454. return new Vector4( ...params );
  455. } else if ( last4 === 'mat3' ) {
  456. return new Matrix3( ...params );
  457. } else if ( last4 === 'mat4' ) {
  458. return new Matrix4( ...params );
  459. } else if ( type === 'bool' ) {
  460. return params[ 0 ] || false;
  461. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  462. return params[ 0 ] || 0;
  463. } else if ( type === 'string' ) {
  464. return params[ 0 ] || '';
  465. } else if ( type === 'ArrayBuffer' ) {
  466. return base64ToArrayBuffer( params[ 0 ] );
  467. }
  468. return null;
  469. }
  470. /**
  471. * Converts the given array buffer to a Base64 string.
  472. *
  473. * @method
  474. * @param {ArrayBuffer} arrayBuffer - The array buffer.
  475. * @return {String} The Base64 string.
  476. */
  477. function arrayBufferToBase64( arrayBuffer ) {
  478. let chars = '';
  479. const array = new Uint8Array( arrayBuffer );
  480. for ( let i = 0; i < array.length; i ++ ) {
  481. chars += String.fromCharCode( array[ i ] );
  482. }
  483. return btoa( chars );
  484. }
  485. /**
  486. * Converts the given Base64 string to an array buffer.
  487. *
  488. * @method
  489. * @param {String} base64 - The Base64 string.
  490. * @return {ArrayBuffer} The array buffer.
  491. */
  492. function base64ToArrayBuffer( base64 ) {
  493. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  494. }
  495. var NodeUtils = /*#__PURE__*/Object.freeze({
  496. __proto__: null,
  497. arrayBufferToBase64: arrayBufferToBase64,
  498. base64ToArrayBuffer: base64ToArrayBuffer,
  499. getCacheKey: getCacheKey$1,
  500. getLengthFromType: getLengthFromType,
  501. getNodeChildren: getNodeChildren,
  502. getTypeFromLength: getTypeFromLength,
  503. getValueFromType: getValueFromType,
  504. getValueType: getValueType,
  505. hash: hash$1,
  506. hashArray: hashArray,
  507. hashString: hashString
  508. });
  509. /**
  510. * Possible shader stages.
  511. *
  512. * @property {string} VERTEX The vertex shader stage.
  513. * @property {string} FRAGMENT The fragment shader stage.
  514. */
  515. const NodeShaderStage = {
  516. VERTEX: 'vertex',
  517. FRAGMENT: 'fragment'
  518. };
  519. /**
  520. * Update types of a node.
  521. *
  522. * @property {string} NONE The update method is not executed.
  523. * @property {string} FRAME The update method is executed per frame.
  524. * @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.
  525. * @property {string} OBJECT The update method is executed per {@link Object3D} that uses the node for rendering.
  526. */
  527. const NodeUpdateType = {
  528. NONE: 'none',
  529. FRAME: 'frame',
  530. RENDER: 'render',
  531. OBJECT: 'object'
  532. };
  533. /**
  534. * Data types of a node.
  535. *
  536. * @property {string} BOOLEAN Boolean type.
  537. * @property {string} INTEGER Integer type.
  538. * @property {string} FLOAT Float type.
  539. * @property {string} VECTOR2 Two-dimensional vector type.
  540. * @property {string} VECTOR3 Three-dimensional vector type.
  541. * @property {string} VECTOR4 Four-dimensional vector type.
  542. * @property {string} MATRIX2 2x2 matrix type.
  543. * @property {string} MATRIX3 3x3 matrix type.
  544. * @property {string} MATRIX4 4x4 matrix type.
  545. */
  546. const NodeType = {
  547. BOOLEAN: 'bool',
  548. INTEGER: 'int',
  549. FLOAT: 'float',
  550. VECTOR2: 'vec2',
  551. VECTOR3: 'vec3',
  552. VECTOR4: 'vec4',
  553. MATRIX2: 'mat2',
  554. MATRIX3: 'mat3',
  555. MATRIX4: 'mat4'
  556. };
  557. /**
  558. * Access types of a node. These are relevant for compute and storage usage.
  559. *
  560. * @property {string} READ_ONLY Read-only access
  561. * @property {string} WRITE_ONLY Write-only access.
  562. * @property {string} READ_WRITE Read and write access.
  563. */
  564. const NodeAccess = {
  565. READ_ONLY: 'readOnly',
  566. WRITE_ONLY: 'writeOnly',
  567. READ_WRITE: 'readWrite',
  568. };
  569. const defaultShaderStages = [ 'fragment', 'vertex' ];
  570. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  571. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  572. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  573. let _nodeId = 0;
  574. /**
  575. * Base class for all nodes.
  576. *
  577. * @augments EventDispatcher
  578. */
  579. class Node extends EventDispatcher {
  580. static get type() {
  581. return 'Node';
  582. }
  583. /**
  584. * Constructs a new node.
  585. *
  586. * @param {String?} nodeType - The node type.
  587. */
  588. constructor( nodeType = null ) {
  589. super();
  590. /**
  591. * The node type. This represents the result type of the node (e.g. `float` or `vec3`).
  592. *
  593. * @type {String?}
  594. * @default null
  595. */
  596. this.nodeType = nodeType;
  597. /**
  598. * The update type of the node's {@link Node#update} method. Possible values are listed in {@link NodeUpdateType}.
  599. *
  600. * @type {String}
  601. * @default 'none'
  602. */
  603. this.updateType = NodeUpdateType.NONE;
  604. /**
  605. * The update type of the node's {@link Node#updateBefore} method. Possible values are listed in {@link NodeUpdateType}.
  606. *
  607. * @type {String}
  608. * @default 'none'
  609. */
  610. this.updateBeforeType = NodeUpdateType.NONE;
  611. /**
  612. * The update type of the node's {@link Node#updateAfter} method. Possible values are listed in {@link NodeUpdateType}.
  613. *
  614. * @type {String}
  615. * @default 'none'
  616. */
  617. this.updateAfterType = NodeUpdateType.NONE;
  618. /**
  619. * The UUID of the node.
  620. *
  621. * @type {String}
  622. * @readonly
  623. */
  624. this.uuid = MathUtils.generateUUID();
  625. /**
  626. * The version of the node. The version automatically is increased when {@link Node#needsUpdate} is set to `true`.
  627. *
  628. * @type {Number}
  629. * @readonly
  630. * @default 0
  631. */
  632. this.version = 0;
  633. /**
  634. * Whether this node is global or not. This property is relevant for the internal
  635. * node caching system. All nodes which should be declared just once should
  636. * set this flag to `true` (a typical example is {@link AttributeNode}).
  637. *
  638. * @type {Boolean}
  639. * @default false
  640. */
  641. this.global = false;
  642. /**
  643. * This flag can be used for type testing.
  644. *
  645. * @type {Boolean}
  646. * @readonly
  647. * @default true
  648. */
  649. this.isNode = true;
  650. // private
  651. /**
  652. * The cache key of this node.
  653. *
  654. * @private
  655. * @type {Number?}
  656. * @default null
  657. */
  658. this._cacheKey = null;
  659. /**
  660. * The cache key 's version.
  661. *
  662. * @private
  663. * @type {Number}
  664. * @default 0
  665. */
  666. this._cacheKeyVersion = 0;
  667. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  668. }
  669. /**
  670. * Set this property to `true` when the node should be regenerated.
  671. *
  672. * @type {Boolean}
  673. * @default false
  674. */
  675. set needsUpdate( value ) {
  676. if ( value === true ) {
  677. this.version ++;
  678. }
  679. }
  680. /**
  681. * The type of the class. The value is usually the constructor name.
  682. *
  683. * @type {String}
  684. * @readonly
  685. */
  686. get type() {
  687. return this.constructor.type;
  688. }
  689. /**
  690. * Convenient method for defining {@link Node#update}.
  691. *
  692. * @param {Function} callback - The update method.
  693. * @param {String} updateType - The update type.
  694. * @return {Node} A reference to this node.
  695. */
  696. onUpdate( callback, updateType ) {
  697. this.updateType = updateType;
  698. this.update = callback.bind( this.getSelf() );
  699. return this;
  700. }
  701. /**
  702. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  703. * this method automatically sets the update type to `FRAME`.
  704. *
  705. * @param {Function} callback - The update method.
  706. * @return {Node} A reference to this node.
  707. */
  708. onFrameUpdate( callback ) {
  709. return this.onUpdate( callback, NodeUpdateType.FRAME );
  710. }
  711. /**
  712. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  713. * this method automatically sets the update type to `RENDER`.
  714. *
  715. * @param {Function} callback - The update method.
  716. * @return {Node} A reference to this node.
  717. */
  718. onRenderUpdate( callback ) {
  719. return this.onUpdate( callback, NodeUpdateType.RENDER );
  720. }
  721. /**
  722. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  723. * this method automatically sets the update type to `OBJECT`.
  724. *
  725. * @param {Function} callback - The update method.
  726. * @return {Node} A reference to this node.
  727. */
  728. onObjectUpdate( callback ) {
  729. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  730. }
  731. /**
  732. * Convenient method for defining {@link Node#updateReference}.
  733. *
  734. * @param {Function} callback - The update method.
  735. * @return {Node} A reference to this node.
  736. */
  737. onReference( callback ) {
  738. this.updateReference = callback.bind( this.getSelf() );
  739. return this;
  740. }
  741. /**
  742. * The `this` reference might point to a Proxy so this method can be used
  743. * to get the reference to the actual node instance.
  744. *
  745. * @return {Node} A reference to the node.
  746. */
  747. getSelf() {
  748. // Returns non-node object.
  749. return this.self || this;
  750. }
  751. /**
  752. * Nodes might refer to other objects like materials. This method allows to dynamically update the reference
  753. * to such objects based on a given state (e.g. the current node frame or builder).
  754. *
  755. * @param {Any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  756. * @return {Any} The updated reference.
  757. */
  758. updateReference( /*state*/ ) {
  759. return this;
  760. }
  761. /**
  762. * By default this method returns the value of the {@link Node#global} flag. This method
  763. * can be overwritten in derived classes if an analytical way is required to determine the
  764. * global status.
  765. *
  766. * @param {NodeBuilder} builder - The current node builder.
  767. * @return {Boolean} Whether this node is global or not.
  768. */
  769. isGlobal( /*builder*/ ) {
  770. return this.global;
  771. }
  772. /**
  773. * Generator function that can be used to iterate over the child nodes.
  774. *
  775. * @generator
  776. * @yields {Node} A child node.
  777. */
  778. * getChildren() {
  779. for ( const { childNode } of getNodeChildren( this ) ) {
  780. yield childNode;
  781. }
  782. }
  783. /**
  784. * Calling this method dispatches the `dispose` event. This event can be used
  785. * to register event listeners for clean up tasks.
  786. */
  787. dispose() {
  788. this.dispatchEvent( { type: 'dispose' } );
  789. }
  790. /**
  791. * Callback for {@link Node#traverse}.
  792. *
  793. * @callback traverseCallback
  794. * @param {Node} node - The current node.
  795. */
  796. /**
  797. * Can be used to traverse through the node's hierarchy.
  798. *
  799. * @param {traverseCallback} callback - A callback that is executed per node.
  800. */
  801. traverse( callback ) {
  802. callback( this );
  803. for ( const childNode of this.getChildren() ) {
  804. childNode.traverse( callback );
  805. }
  806. }
  807. /**
  808. * Returns the cache key for this node.
  809. *
  810. * @param {Boolean} [force=false] - When set to `true`, a recomputation of the cache key is forced.
  811. * @return {Number} The cache key of the node.
  812. */
  813. getCacheKey( force = false ) {
  814. force = force || this.version !== this._cacheKeyVersion;
  815. if ( force === true || this._cacheKey === null ) {
  816. this._cacheKey = hash$1( getCacheKey$1( this, force ), this.customCacheKey() );
  817. this._cacheKeyVersion = this.version;
  818. }
  819. return this._cacheKey;
  820. }
  821. /**
  822. * Generate a custom cache key for this node.
  823. *
  824. * @return {Number} The cache key of the node.
  825. * @default 0
  826. */
  827. customCacheKey() {
  828. return 0;
  829. }
  830. /**
  831. * Returns the references to this node which is by default `this`.
  832. *
  833. * @return {Node} A reference to this node.
  834. */
  835. getScope() {
  836. return this;
  837. }
  838. /**
  839. * Returns the hash of the node which is used to identify the node. By default it's
  840. * the {@link Node#uuid} however derived node classes might have to overwrite this method
  841. * depending on their implementation.
  842. *
  843. * @param {NodeBuilder} builder - The current node builder.
  844. * @return {String} The hash.
  845. */
  846. getHash( /*builder*/ ) {
  847. return this.uuid;
  848. }
  849. /**
  850. * Returns the update type of {@link Node#update}.
  851. *
  852. * @return {NodeUpdateType} The update type.
  853. */
  854. getUpdateType() {
  855. return this.updateType;
  856. }
  857. /**
  858. * Returns the update type of {@link Node#updateBefore}.
  859. *
  860. * @return {NodeUpdateType} The update type.
  861. */
  862. getUpdateBeforeType() {
  863. return this.updateBeforeType;
  864. }
  865. /**
  866. * Returns the update type of {@link Node#updateAfter}.
  867. *
  868. * @return {NodeUpdateType} The update type.
  869. */
  870. getUpdateAfterType() {
  871. return this.updateAfterType;
  872. }
  873. /**
  874. * Certain types are composed of multiple elements. For example a `vec3`
  875. * is composed of three `float` values. This method returns the type of
  876. * these elements.
  877. *
  878. * @param {NodeBuilder} builder - The current node builder.
  879. * @return {String} The type of the node.
  880. */
  881. getElementType( builder ) {
  882. const type = this.getNodeType( builder );
  883. const elementType = builder.getElementType( type );
  884. return elementType;
  885. }
  886. /**
  887. * Returns the node's type.
  888. *
  889. * @param {NodeBuilder} builder - The current node builder.
  890. * @return {String} The type of the node.
  891. */
  892. getNodeType( builder ) {
  893. const nodeProperties = builder.getNodeProperties( this );
  894. if ( nodeProperties.outputNode ) {
  895. return nodeProperties.outputNode.getNodeType( builder );
  896. }
  897. return this.nodeType;
  898. }
  899. /**
  900. * This method is used during the build process of a node and ensures
  901. * equal nodes are not built multiple times but just once. For example if
  902. * `attribute( 'uv' )` is used multiple times by the user, the build
  903. * process makes sure to process just the first node.
  904. *
  905. * @param {NodeBuilder} builder - The current node builder.
  906. * @return {Node} The shared node if possible. Otherwise `this` is returned.
  907. */
  908. getShared( builder ) {
  909. const hash = this.getHash( builder );
  910. const nodeFromHash = builder.getNodeFromHash( hash );
  911. return nodeFromHash || this;
  912. }
  913. /**
  914. * Represents the setup stage which is the first step of the build process, see {@link Node#build} method.
  915. * This method is often overwritten in derived modules to prepare the node which is used as the output/result.
  916. * The output node must be returned in the `return` statement.
  917. *
  918. * @param {NodeBuilder} builder - The current node builder.
  919. * @return {Node?} The output node.
  920. */
  921. setup( builder ) {
  922. const nodeProperties = builder.getNodeProperties( this );
  923. let index = 0;
  924. for ( const childNode of this.getChildren() ) {
  925. nodeProperties[ 'node' + index ++ ] = childNode;
  926. }
  927. // return a outputNode if exists
  928. return null;
  929. }
  930. /**
  931. * Represents the analyze stage which is the second step of the build process, see {@link Node#build} method.
  932. * This stage analyzes the node hierarchy and ensures descendent nodes are built.
  933. *
  934. * @param {NodeBuilder} builder - The current node builder.
  935. */
  936. analyze( builder ) {
  937. const usageCount = builder.increaseUsage( this );
  938. if ( usageCount === 1 ) {
  939. // node flow children
  940. const nodeProperties = builder.getNodeProperties( this );
  941. for ( const childNode of Object.values( nodeProperties ) ) {
  942. if ( childNode && childNode.isNode === true ) {
  943. childNode.build( builder );
  944. }
  945. }
  946. }
  947. }
  948. /**
  949. * Represents the generate stage which is the third step of the build process, see {@link Node#build} method.
  950. * This state builds the output node and returns the resulting shader string.
  951. *
  952. * @param {NodeBuilder} builder - The current node builder.
  953. * @param {String?} output - Can be used to define the output type.
  954. * @return {String?} The generated shader string.
  955. */
  956. generate( builder, output ) {
  957. const { outputNode } = builder.getNodeProperties( this );
  958. if ( outputNode && outputNode.isNode === true ) {
  959. return outputNode.build( builder, output );
  960. }
  961. }
  962. /**
  963. * The method can be implemented to update the node's internal state before it is used to render an object.
  964. * The {@link Node#updateBeforeType} property defines how often the update is executed.
  965. *
  966. * @param {NodeFrame} frame - A reference to the current node frame.
  967. * @return {Boolean?} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  968. */
  969. updateBefore( /*frame*/ ) {
  970. console.warn( 'Abstract function.' );
  971. }
  972. /**
  973. * The method can be implemented to update the node's internal state after it was used to render an object.
  974. * The {@link Node#updateAfterType} property defines how often the update is executed.
  975. *
  976. * @param {NodeFrame} frame - A reference to the current node frame.
  977. * @return {Boolean?} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  978. */
  979. updateAfter( /*frame*/ ) {
  980. console.warn( 'Abstract function.' );
  981. }
  982. /**
  983. * The method can be implemented to update the node's internal state when it is used to render an object.
  984. * The {@link Node#updateType} property defines how often the update is executed.
  985. *
  986. * @param {NodeFrame} frame - A reference to the current node frame.
  987. * @return {Boolean?} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  988. */
  989. update( /*frame*/ ) {
  990. console.warn( 'Abstract function.' );
  991. }
  992. /**
  993. * This method performs the build of a node. The behavior of this method as well as its return value depend
  994. * on the current build stage (setup, analyze or generate).
  995. *
  996. * @param {NodeBuilder} builder - The current node builder.
  997. * @param {String?} output - Can be used to define the output type.
  998. * @return {String?} When this method is executed in the setup or analyze stage, `null` is returned. In the generate stage, the generated shader string.
  999. */
  1000. build( builder, output = null ) {
  1001. const refNode = this.getShared( builder );
  1002. if ( this !== refNode ) {
  1003. return refNode.build( builder, output );
  1004. }
  1005. builder.addNode( this );
  1006. builder.addChain( this );
  1007. /* Build stages expected results:
  1008. - "setup" -> Node
  1009. - "analyze" -> null
  1010. - "generate" -> String
  1011. */
  1012. let result = null;
  1013. const buildStage = builder.getBuildStage();
  1014. if ( buildStage === 'setup' ) {
  1015. this.updateReference( builder );
  1016. const properties = builder.getNodeProperties( this );
  1017. if ( properties.initialized !== true ) {
  1018. const stackNodesBeforeSetup = builder.stack.nodes.length;
  1019. properties.initialized = true;
  1020. properties.outputNode = this.setup( builder );
  1021. if ( properties.outputNode !== null && builder.stack.nodes.length !== stackNodesBeforeSetup ) ;
  1022. for ( const childNode of Object.values( properties ) ) {
  1023. if ( childNode && childNode.isNode === true ) {
  1024. childNode.build( builder );
  1025. }
  1026. }
  1027. }
  1028. } else if ( buildStage === 'analyze' ) {
  1029. this.analyze( builder );
  1030. } else if ( buildStage === 'generate' ) {
  1031. const isGenerateOnce = this.generate.length === 1;
  1032. if ( isGenerateOnce ) {
  1033. const type = this.getNodeType( builder );
  1034. const nodeData = builder.getDataFromNode( this );
  1035. result = nodeData.snippet;
  1036. if ( result === undefined ) {
  1037. result = this.generate( builder ) || '';
  1038. nodeData.snippet = result;
  1039. } else if ( nodeData.flowCodes !== undefined && builder.context.nodeBlock !== undefined ) {
  1040. builder.addFlowCodeHierarchy( this, builder.context.nodeBlock );
  1041. }
  1042. result = builder.format( result, type, output );
  1043. } else {
  1044. result = this.generate( builder, output ) || '';
  1045. }
  1046. }
  1047. builder.removeChain( this );
  1048. builder.addSequentialNode( this );
  1049. return result;
  1050. }
  1051. /**
  1052. * Returns the child nodes as a JSON object.
  1053. *
  1054. * @return {Object} The serialized child objects as JSON.
  1055. */
  1056. getSerializeChildren() {
  1057. return getNodeChildren( this );
  1058. }
  1059. /**
  1060. * Serializes the node to JSON.
  1061. *
  1062. * @param {Object} json - The output JSON object.
  1063. */
  1064. serialize( json ) {
  1065. const nodeChildren = this.getSerializeChildren();
  1066. const inputNodes = {};
  1067. for ( const { property, index, childNode } of nodeChildren ) {
  1068. if ( index !== undefined ) {
  1069. if ( inputNodes[ property ] === undefined ) {
  1070. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  1071. }
  1072. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  1073. } else {
  1074. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  1075. }
  1076. }
  1077. if ( Object.keys( inputNodes ).length > 0 ) {
  1078. json.inputNodes = inputNodes;
  1079. }
  1080. }
  1081. /**
  1082. * Deserializes the node from the given JSON.
  1083. *
  1084. * @param {Object} json - The JSON object.
  1085. */
  1086. deserialize( json ) {
  1087. if ( json.inputNodes !== undefined ) {
  1088. const nodes = json.meta.nodes;
  1089. for ( const property in json.inputNodes ) {
  1090. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  1091. const inputArray = [];
  1092. for ( const uuid of json.inputNodes[ property ] ) {
  1093. inputArray.push( nodes[ uuid ] );
  1094. }
  1095. this[ property ] = inputArray;
  1096. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  1097. const inputObject = {};
  1098. for ( const subProperty in json.inputNodes[ property ] ) {
  1099. const uuid = json.inputNodes[ property ][ subProperty ];
  1100. inputObject[ subProperty ] = nodes[ uuid ];
  1101. }
  1102. this[ property ] = inputObject;
  1103. } else {
  1104. const uuid = json.inputNodes[ property ];
  1105. this[ property ] = nodes[ uuid ];
  1106. }
  1107. }
  1108. }
  1109. }
  1110. /**
  1111. * Serializes the node into the three.js JSON Object/Scene format.
  1112. *
  1113. * @param {Object?} meta - An optional JSON object that already holds serialized data from other scene objects.
  1114. * @return {Object} The serialized node.
  1115. */
  1116. toJSON( meta ) {
  1117. const { uuid, type } = this;
  1118. const isRoot = ( meta === undefined || typeof meta === 'string' );
  1119. if ( isRoot ) {
  1120. meta = {
  1121. textures: {},
  1122. images: {},
  1123. nodes: {}
  1124. };
  1125. }
  1126. // serialize
  1127. let data = meta.nodes[ uuid ];
  1128. if ( data === undefined ) {
  1129. data = {
  1130. uuid,
  1131. type,
  1132. meta,
  1133. metadata: {
  1134. version: 4.6,
  1135. type: 'Node',
  1136. generator: 'Node.toJSON'
  1137. }
  1138. };
  1139. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  1140. this.serialize( data );
  1141. delete data.meta;
  1142. }
  1143. // TODO: Copied from Object3D.toJSON
  1144. function extractFromCache( cache ) {
  1145. const values = [];
  1146. for ( const key in cache ) {
  1147. const data = cache[ key ];
  1148. delete data.metadata;
  1149. values.push( data );
  1150. }
  1151. return values;
  1152. }
  1153. if ( isRoot ) {
  1154. const textures = extractFromCache( meta.textures );
  1155. const images = extractFromCache( meta.images );
  1156. const nodes = extractFromCache( meta.nodes );
  1157. if ( textures.length > 0 ) data.textures = textures;
  1158. if ( images.length > 0 ) data.images = images;
  1159. if ( nodes.length > 0 ) data.nodes = nodes;
  1160. }
  1161. return data;
  1162. }
  1163. }
  1164. /**
  1165. * Base class for representing element access on an array-like
  1166. * node data structures.
  1167. *
  1168. * @augments Node
  1169. */
  1170. class ArrayElementNode extends Node { // @TODO: If extending from TempNode it breaks webgpu_compute
  1171. static get type() {
  1172. return 'ArrayElementNode';
  1173. }
  1174. /**
  1175. * Constructs array element node.
  1176. *
  1177. * @param {Node} node - The array-like node.
  1178. * @param {Node} indexNode - The index node that defines the element access.
  1179. */
  1180. constructor( node, indexNode ) {
  1181. super();
  1182. /**
  1183. * The array-like node.
  1184. *
  1185. * @type {Node}
  1186. */
  1187. this.node = node;
  1188. /**
  1189. * The index node that defines the element access.
  1190. *
  1191. * @type {Node}
  1192. */
  1193. this.indexNode = indexNode;
  1194. /**
  1195. * This flag can be used for type testing.
  1196. *
  1197. * @type {Boolean}
  1198. * @readonly
  1199. * @default true
  1200. */
  1201. this.isArrayElementNode = true;
  1202. }
  1203. /**
  1204. * This method is overwritten since the node type is inferred from the array-like node.
  1205. *
  1206. * @param {NodeBuilder} builder - The current node builder.
  1207. * @return {String} The node type.
  1208. */
  1209. getNodeType( builder ) {
  1210. return this.node.getElementType( builder );
  1211. }
  1212. generate( builder ) {
  1213. const nodeSnippet = this.node.build( builder );
  1214. const indexSnippet = this.indexNode.build( builder, 'uint' );
  1215. return `${nodeSnippet}[ ${indexSnippet} ]`;
  1216. }
  1217. }
  1218. /**
  1219. * This module is part of the TSL core and usually not used in app level code.
  1220. * It represents a convert operation during the shader generation process
  1221. * meaning it converts the data type of a node to a target data type.
  1222. *
  1223. * @augments Node
  1224. */
  1225. class ConvertNode extends Node {
  1226. static get type() {
  1227. return 'ConvertNode';
  1228. }
  1229. /**
  1230. * Constructs a new convert node.
  1231. *
  1232. * @param {Node} node - The node which type should be converted.
  1233. * @param {String} convertTo - The target node type. Multiple types can be defined by separating them with a `|` sign.
  1234. */
  1235. constructor( node, convertTo ) {
  1236. super();
  1237. /**
  1238. * The node which type should be converted.
  1239. *
  1240. * @type {Node}
  1241. */
  1242. this.node = node;
  1243. /**
  1244. * The target node type. Multiple types can be defined by separating them with a `|` sign.
  1245. *
  1246. * @type {String}
  1247. */
  1248. this.convertTo = convertTo;
  1249. }
  1250. /**
  1251. * This method is overwritten since the implementation tries to infer the best
  1252. * matching type from the {@link ConvertNode#convertTo} property.
  1253. *
  1254. * @param {NodeBuilder} builder - The current node builder.
  1255. * @return {String} The node type.
  1256. */
  1257. getNodeType( builder ) {
  1258. const requestType = this.node.getNodeType( builder );
  1259. let convertTo = null;
  1260. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  1261. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  1262. convertTo = overloadingType;
  1263. }
  1264. }
  1265. return convertTo;
  1266. }
  1267. serialize( data ) {
  1268. super.serialize( data );
  1269. data.convertTo = this.convertTo;
  1270. }
  1271. deserialize( data ) {
  1272. super.deserialize( data );
  1273. this.convertTo = data.convertTo;
  1274. }
  1275. generate( builder, output ) {
  1276. const node = this.node;
  1277. const type = this.getNodeType( builder );
  1278. const snippet = node.build( builder, type );
  1279. return builder.format( snippet, type, output );
  1280. }
  1281. }
  1282. /**
  1283. * This module uses cache management to create temporary variables
  1284. * if the node is used more than once to prevent duplicate calculations.
  1285. *
  1286. * The class acts as a base class for many other nodes types.
  1287. *
  1288. * @augments Node
  1289. */
  1290. class TempNode extends Node {
  1291. static get type() {
  1292. return 'TempNode';
  1293. }
  1294. /**
  1295. * Constructs a temp node.
  1296. *
  1297. * @param {String} nodeType - The node type.
  1298. */
  1299. constructor( type ) {
  1300. super( type );
  1301. /**
  1302. * This flag can be used for type testing.
  1303. *
  1304. * @type {Boolean}
  1305. * @readonly
  1306. * @default true
  1307. */
  1308. this.isTempNode = true;
  1309. }
  1310. /**
  1311. * Whether this node is used more than once in context of other nodes.
  1312. *
  1313. * @return {Boolean} A flag that indicates if there is more than one dependency to other nodes.
  1314. */
  1315. hasDependencies( builder ) {
  1316. return builder.getDataFromNode( this ).usageCount > 1;
  1317. }
  1318. build( builder, output ) {
  1319. const buildStage = builder.getBuildStage();
  1320. if ( buildStage === 'generate' ) {
  1321. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  1322. const nodeData = builder.getDataFromNode( this );
  1323. if ( nodeData.propertyName !== undefined ) {
  1324. return builder.format( nodeData.propertyName, type, output );
  1325. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  1326. const snippet = super.build( builder, type );
  1327. const nodeVar = builder.getVarFromNode( this, null, type );
  1328. const propertyName = builder.getPropertyName( nodeVar );
  1329. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  1330. nodeData.snippet = snippet;
  1331. nodeData.propertyName = propertyName;
  1332. return builder.format( nodeData.propertyName, type, output );
  1333. }
  1334. }
  1335. return super.build( builder, output );
  1336. }
  1337. }
  1338. /**
  1339. * This module is part of the TSL core and usually not used in app level code.
  1340. * It represents a join operation during the shader generation process.
  1341. * For example in can compose/join two single floats into a `vec2` type.
  1342. *
  1343. * @augments TempNode
  1344. */
  1345. class JoinNode extends TempNode {
  1346. static get type() {
  1347. return 'JoinNode';
  1348. }
  1349. /**
  1350. * Constructs a new join node.
  1351. *
  1352. * @param {Array<Node>} nodes - An array of nodes that should be joined.
  1353. * @param {String?} [nodeType=null] - The node type.
  1354. */
  1355. constructor( nodes = [], nodeType = null ) {
  1356. super( nodeType );
  1357. /**
  1358. * An array of nodes that should be joined.
  1359. *
  1360. * @type {Array<Node>}
  1361. */
  1362. this.nodes = nodes;
  1363. }
  1364. /**
  1365. * This method is overwritten since the node type must be inferred from the
  1366. * joined data length if not explicitly defined.
  1367. *
  1368. * @param {NodeBuilder} builder - The current node builder.
  1369. * @return {String} The node type.
  1370. */
  1371. getNodeType( builder ) {
  1372. if ( this.nodeType !== null ) {
  1373. return builder.getVectorType( this.nodeType );
  1374. }
  1375. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  1376. }
  1377. generate( builder, output ) {
  1378. const type = this.getNodeType( builder );
  1379. const nodes = this.nodes;
  1380. const primitiveType = builder.getComponentType( type );
  1381. const snippetValues = [];
  1382. for ( const input of nodes ) {
  1383. let inputSnippet = input.build( builder );
  1384. const inputPrimitiveType = builder.getComponentType( input.getNodeType( builder ) );
  1385. if ( inputPrimitiveType !== primitiveType ) {
  1386. inputSnippet = builder.format( inputSnippet, inputPrimitiveType, primitiveType );
  1387. }
  1388. snippetValues.push( inputSnippet );
  1389. }
  1390. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  1391. return builder.format( snippet, type, output );
  1392. }
  1393. }
  1394. const _stringVectorComponents = vectorComponents.join( '' );
  1395. /**
  1396. * This module is part of the TSL core and usually not used in app level code.
  1397. * `SplitNode` represents a property access operation which means it is
  1398. * used to implement any `.xyzw`, `.rgba` and `stpq` usage on node objects.
  1399. * For example:
  1400. * ```js
  1401. * const redValue = color.r;
  1402. * ```
  1403. *
  1404. * @augments Node
  1405. */
  1406. class SplitNode extends Node {
  1407. static get type() {
  1408. return 'SplitNode';
  1409. }
  1410. /**
  1411. * Constructs a new split node.
  1412. *
  1413. * @param {Node} node - The node that should be accessed.
  1414. * @param {String} [components='x'] - The components that should be accessed.
  1415. */
  1416. constructor( node, components = 'x' ) {
  1417. super();
  1418. /**
  1419. * The node that should be accessed.
  1420. *
  1421. * @type {Node}
  1422. */
  1423. this.node = node;
  1424. /**
  1425. * The components that should be accessed.
  1426. *
  1427. * @type {Node}
  1428. */
  1429. this.components = components;
  1430. /**
  1431. * This flag can be used for type testing.
  1432. *
  1433. * @type {Boolean}
  1434. * @readonly
  1435. * @default true
  1436. */
  1437. this.isSplitNode = true;
  1438. }
  1439. /**
  1440. * Returns the vector length which is computed based on the requested components.
  1441. *
  1442. * @return {Number} The vector length.
  1443. */
  1444. getVectorLength() {
  1445. let vectorLength = this.components.length;
  1446. for ( const c of this.components ) {
  1447. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  1448. }
  1449. return vectorLength;
  1450. }
  1451. /**
  1452. * Returns the component type of the node's type.
  1453. *
  1454. * @param {NodeBuilder} builder - The current node builder.
  1455. * @return {String} The component type.
  1456. */
  1457. getComponentType( builder ) {
  1458. return builder.getComponentType( this.node.getNodeType( builder ) );
  1459. }
  1460. /**
  1461. * This method is overwritten since the node type is inferred from requested components.
  1462. *
  1463. * @param {NodeBuilder} builder - The current node builder.
  1464. * @return {String} The node type.
  1465. */
  1466. getNodeType( builder ) {
  1467. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  1468. }
  1469. generate( builder, output ) {
  1470. const node = this.node;
  1471. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  1472. let snippet = null;
  1473. if ( nodeTypeLength > 1 ) {
  1474. let type = null;
  1475. const componentsLength = this.getVectorLength();
  1476. if ( componentsLength >= nodeTypeLength ) {
  1477. // needed expand the input node
  1478. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  1479. }
  1480. const nodeSnippet = node.build( builder, type );
  1481. if ( this.components.length === nodeTypeLength && this.components === _stringVectorComponents.slice( 0, this.components.length ) ) {
  1482. // unnecessary swizzle
  1483. snippet = builder.format( nodeSnippet, type, output );
  1484. } else {
  1485. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  1486. }
  1487. } else {
  1488. // ignore .components if .node returns float/integer
  1489. snippet = node.build( builder, output );
  1490. }
  1491. return snippet;
  1492. }
  1493. serialize( data ) {
  1494. super.serialize( data );
  1495. data.components = this.components;
  1496. }
  1497. deserialize( data ) {
  1498. super.deserialize( data );
  1499. this.components = data.components;
  1500. }
  1501. }
  1502. /**
  1503. * This module is part of the TSL core and usually not used in app level code.
  1504. * `SetNode` represents a set operation which means it is used to implement any
  1505. * `setXYZW()`, `setRGBA()` and `setSTPQ()` method invocations on node objects.
  1506. * For example:
  1507. * ```js
  1508. * materialLine.colorNode = color( 0, 0, 0 ).setR( float( 1 ) );
  1509. * ```
  1510. *
  1511. * @augments TempNode
  1512. */
  1513. class SetNode extends TempNode {
  1514. static get type() {
  1515. return 'SetNode';
  1516. }
  1517. /**
  1518. * Constructs a new set node.
  1519. *
  1520. * @param {Node} sourceNode - The node that should be updated.
  1521. * @param {String} components - The components that should be updated.
  1522. * @param {Node} targetNode - The value node.
  1523. */
  1524. constructor( sourceNode, components, targetNode ) {
  1525. super();
  1526. /**
  1527. * The node that should be updated.
  1528. *
  1529. * @type {Node}
  1530. */
  1531. this.sourceNode = sourceNode;
  1532. /**
  1533. * The components that should be updated.
  1534. *
  1535. * @type {String}
  1536. */
  1537. this.components = components;
  1538. /**
  1539. * The value node.
  1540. *
  1541. * @type {Node}
  1542. */
  1543. this.targetNode = targetNode;
  1544. }
  1545. /**
  1546. * This method is overwritten since the node type is inferred from {@link SetNode#sourceNode}.
  1547. *
  1548. * @param {NodeBuilder} builder - The current node builder.
  1549. * @return {String} The node type.
  1550. */
  1551. getNodeType( builder ) {
  1552. return this.sourceNode.getNodeType( builder );
  1553. }
  1554. generate( builder ) {
  1555. const { sourceNode, components, targetNode } = this;
  1556. const sourceType = this.getNodeType( builder );
  1557. const componentType = builder.getComponentType( targetNode.getNodeType( builder ) );
  1558. const targetType = builder.getTypeFromLength( components.length, componentType );
  1559. const targetSnippet = targetNode.build( builder, targetType );
  1560. const sourceSnippet = sourceNode.build( builder, sourceType );
  1561. const length = builder.getTypeLength( sourceType );
  1562. const snippetValues = [];
  1563. for ( let i = 0; i < length; i ++ ) {
  1564. const component = vectorComponents[ i ];
  1565. if ( component === components[ 0 ] ) {
  1566. snippetValues.push( targetSnippet );
  1567. i += components.length - 1;
  1568. } else {
  1569. snippetValues.push( sourceSnippet + '.' + component );
  1570. }
  1571. }
  1572. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1573. }
  1574. }
  1575. /**
  1576. * This module is part of the TSL core and usually not used in app level code.
  1577. * It represents a flip operation during the shader generation process
  1578. * meaning it flips normalized values with the following formula:
  1579. * ```
  1580. * x = 1 - x;
  1581. * ```
  1582. * `FlipNode` is internally used to implement any `flipXYZW()`, `flipRGBA()` and
  1583. * `flipSTPQ()` method invocations on node objects. For example:
  1584. * ```js
  1585. * uvNode = uvNode.flipY();
  1586. * ```
  1587. *
  1588. * @augments TempNode
  1589. */
  1590. class FlipNode extends TempNode {
  1591. static get type() {
  1592. return 'FlipNode';
  1593. }
  1594. /**
  1595. * Constructs a new flip node.
  1596. *
  1597. * @param {Node} sourceNode - The node which component(s) should be flipped.
  1598. * @param {String} components - The components that should be flipped e.g. `'x'` or `'xy'`.
  1599. */
  1600. constructor( sourceNode, components ) {
  1601. super();
  1602. /**
  1603. * The node which component(s) should be flipped.
  1604. *
  1605. * @type {Node}
  1606. */
  1607. this.sourceNode = sourceNode;
  1608. /**
  1609. * The components that should be flipped e.g. `'x'` or `'xy'`.
  1610. *
  1611. * @type {String}
  1612. */
  1613. this.components = components;
  1614. }
  1615. /**
  1616. * This method is overwritten since the node type is inferred from the source node.
  1617. *
  1618. * @param {NodeBuilder} builder - The current node builder.
  1619. * @return {String} The node type.
  1620. */
  1621. getNodeType( builder ) {
  1622. return this.sourceNode.getNodeType( builder );
  1623. }
  1624. generate( builder ) {
  1625. const { components, sourceNode } = this;
  1626. const sourceType = this.getNodeType( builder );
  1627. const sourceSnippet = sourceNode.build( builder );
  1628. const sourceCache = builder.getVarFromNode( this );
  1629. const sourceProperty = builder.getPropertyName( sourceCache );
  1630. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  1631. const length = builder.getTypeLength( sourceType );
  1632. const snippetValues = [];
  1633. let componentIndex = 0;
  1634. for ( let i = 0; i < length; i ++ ) {
  1635. const component = vectorComponents[ i ];
  1636. if ( component === components[ componentIndex ] ) {
  1637. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  1638. componentIndex ++;
  1639. } else {
  1640. snippetValues.push( sourceProperty + '.' + component );
  1641. }
  1642. }
  1643. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1644. }
  1645. }
  1646. /**
  1647. * Base class for representing data input nodes.
  1648. *
  1649. * @augments Node
  1650. */
  1651. class InputNode extends Node {
  1652. static get type() {
  1653. return 'InputNode';
  1654. }
  1655. /**
  1656. * Constructs a new input node.
  1657. *
  1658. * @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).
  1659. * @param {String?} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  1660. */
  1661. constructor( value, nodeType = null ) {
  1662. super( nodeType );
  1663. /**
  1664. * This flag can be used for type testing.
  1665. *
  1666. * @type {Boolean}
  1667. * @readonly
  1668. * @default true
  1669. */
  1670. this.isInputNode = true;
  1671. /**
  1672. * The value of this node. This can be a any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  1673. *
  1674. * @type {Any}
  1675. */
  1676. this.value = value;
  1677. /**
  1678. * The precision of the value in the shader.
  1679. *
  1680. * @type {('low'|'medium'|'high')?}
  1681. * @default null
  1682. */
  1683. this.precision = null;
  1684. }
  1685. getNodeType( /*builder*/ ) {
  1686. if ( this.nodeType === null ) {
  1687. return getValueType( this.value );
  1688. }
  1689. return this.nodeType;
  1690. }
  1691. /**
  1692. * Returns the input type of the node which is by default the node type. Derived modules
  1693. * might overwrite this method and use a fixed type or compute one analytically.
  1694. *
  1695. * A typical example for different input and node types are textures. The input type of a
  1696. * normal RGBA texture is `texture` whereas its node type is `vec4`.
  1697. *
  1698. * @param {NodeBuilder} builder - The current node builder.
  1699. * @return {String} The input type.
  1700. */
  1701. getInputType( builder ) {
  1702. return this.getNodeType( builder );
  1703. }
  1704. /**
  1705. * Sets the precision to the given value. The method can be
  1706. * overwritten in derived classes if the final precision must be computed
  1707. * analytically.
  1708. *
  1709. * @param {('low'|'medium'|'high')} precision - The precision of the input value in the shader.
  1710. * @return {InputNode} A reference to this node.
  1711. */
  1712. setPrecision( precision ) {
  1713. this.precision = precision;
  1714. return this;
  1715. }
  1716. serialize( data ) {
  1717. super.serialize( data );
  1718. data.value = this.value;
  1719. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  1720. data.valueType = getValueType( this.value );
  1721. data.nodeType = this.nodeType;
  1722. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  1723. data.precision = this.precision;
  1724. }
  1725. deserialize( data ) {
  1726. super.deserialize( data );
  1727. this.nodeType = data.nodeType;
  1728. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  1729. this.precision = data.precision || null;
  1730. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  1731. }
  1732. generate( /*builder, output*/ ) {
  1733. console.warn( 'Abstract function.' );
  1734. }
  1735. }
  1736. /**
  1737. * Class for representing a constant value in the shader.
  1738. *
  1739. * @augments InputNode
  1740. */
  1741. class ConstNode extends InputNode {
  1742. static get type() {
  1743. return 'ConstNode';
  1744. }
  1745. /**
  1746. * Constructs a new input node.
  1747. *
  1748. * @param {Any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color).
  1749. * @param {String?} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  1750. */
  1751. constructor( value, nodeType = null ) {
  1752. super( value, nodeType );
  1753. /**
  1754. * This flag can be used for type testing.
  1755. *
  1756. * @type {Boolean}
  1757. * @readonly
  1758. * @default true
  1759. */
  1760. this.isConstNode = true;
  1761. }
  1762. /**
  1763. * Generates the shader string of the value with the current node builder.
  1764. *
  1765. * @param {NodeBuilder} builder - The current node builder.
  1766. * @return {String} The generated value as a shader string.
  1767. */
  1768. generateConst( builder ) {
  1769. return builder.generateConst( this.getNodeType( builder ), this.value );
  1770. }
  1771. generate( builder, output ) {
  1772. const type = this.getNodeType( builder );
  1773. return builder.format( this.generateConst( builder ), type, output );
  1774. }
  1775. }
  1776. //
  1777. let currentStack = null;
  1778. const NodeElements = new Map();
  1779. function addMethodChaining( name, nodeElement ) {
  1780. if ( NodeElements.has( name ) ) {
  1781. console.warn( `Redefinition of method chaining ${ name }` );
  1782. return;
  1783. }
  1784. if ( typeof nodeElement !== 'function' ) throw new Error( `Node element ${ name } is not a function` );
  1785. NodeElements.set( name, nodeElement );
  1786. }
  1787. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  1788. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  1789. const shaderNodeHandler = {
  1790. setup( NodeClosure, params ) {
  1791. const inputs = params.shift();
  1792. return NodeClosure( nodeObjects( inputs ), ...params );
  1793. },
  1794. get( node, prop, nodeObj ) {
  1795. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  1796. if ( node.isStackNode !== true && prop === 'assign' ) {
  1797. return ( ...params ) => {
  1798. currentStack.assign( nodeObj, ...params );
  1799. return nodeObj;
  1800. };
  1801. } else if ( NodeElements.has( prop ) ) {
  1802. const nodeElement = NodeElements.get( prop );
  1803. return node.isStackNode ? ( ...params ) => nodeObj.add( nodeElement( ...params ) ) : ( ...params ) => nodeElement( nodeObj, ...params );
  1804. } else if ( prop === 'self' ) {
  1805. return node;
  1806. } else if ( prop.endsWith( 'Assign' ) && NodeElements.has( prop.slice( 0, prop.length - 'Assign'.length ) ) ) {
  1807. const nodeElement = NodeElements.get( prop.slice( 0, prop.length - 'Assign'.length ) );
  1808. return node.isStackNode ? ( ...params ) => nodeObj.assign( params[ 0 ], nodeElement( ...params ) ) : ( ...params ) => nodeObj.assign( nodeElement( nodeObj, ...params ) );
  1809. } else if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true ) {
  1810. // accessing properties ( swizzle )
  1811. prop = parseSwizzle( prop );
  1812. return nodeObject( new SplitNode( nodeObj, prop ) );
  1813. } else if ( /^set[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  1814. // set properties ( swizzle ) and sort to xyzw sequence
  1815. prop = parseSwizzleAndSort( prop.slice( 3 ).toLowerCase() );
  1816. return ( value ) => nodeObject( new SetNode( node, prop, value ) );
  1817. } else if ( /^flip[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  1818. // set properties ( swizzle ) and sort to xyzw sequence
  1819. prop = parseSwizzleAndSort( prop.slice( 4 ).toLowerCase() );
  1820. return () => nodeObject( new FlipNode( nodeObject( node ), prop ) );
  1821. } else if ( prop === 'width' || prop === 'height' || prop === 'depth' ) {
  1822. // accessing property
  1823. if ( prop === 'width' ) prop = 'x';
  1824. else if ( prop === 'height' ) prop = 'y';
  1825. else if ( prop === 'depth' ) prop = 'z';
  1826. return nodeObject( new SplitNode( node, prop ) );
  1827. } else if ( /^\d+$/.test( prop ) === true ) {
  1828. // accessing array
  1829. return nodeObject( new ArrayElementNode( nodeObj, new ConstNode( Number( prop ), 'uint' ) ) );
  1830. }
  1831. }
  1832. return Reflect.get( node, prop, nodeObj );
  1833. },
  1834. set( node, prop, value, nodeObj ) {
  1835. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  1836. // setting properties
  1837. if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true || prop === 'width' || prop === 'height' || prop === 'depth' || /^\d+$/.test( prop ) === true ) {
  1838. nodeObj[ prop ].assign( value );
  1839. return true;
  1840. }
  1841. }
  1842. return Reflect.set( node, prop, value, nodeObj );
  1843. }
  1844. };
  1845. const nodeObjectsCacheMap = new WeakMap();
  1846. const nodeBuilderFunctionsCacheMap = new WeakMap();
  1847. const ShaderNodeObject = function ( obj, altType = null ) {
  1848. const type = getValueType( obj );
  1849. if ( type === 'node' ) {
  1850. let nodeObject = nodeObjectsCacheMap.get( obj );
  1851. if ( nodeObject === undefined ) {
  1852. nodeObject = new Proxy( obj, shaderNodeHandler );
  1853. nodeObjectsCacheMap.set( obj, nodeObject );
  1854. nodeObjectsCacheMap.set( nodeObject, nodeObject );
  1855. }
  1856. return nodeObject;
  1857. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  1858. return nodeObject( getConstNode( obj, altType ) );
  1859. } else if ( type === 'shader' ) {
  1860. return Fn( obj );
  1861. }
  1862. return obj;
  1863. };
  1864. const ShaderNodeObjects = function ( objects, altType = null ) {
  1865. for ( const name in objects ) {
  1866. objects[ name ] = nodeObject( objects[ name ], altType );
  1867. }
  1868. return objects;
  1869. };
  1870. const ShaderNodeArray = function ( array, altType = null ) {
  1871. const len = array.length;
  1872. for ( let i = 0; i < len; i ++ ) {
  1873. array[ i ] = nodeObject( array[ i ], altType );
  1874. }
  1875. return array;
  1876. };
  1877. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  1878. const assignNode = ( node ) => nodeObject( settings !== null ? Object.assign( node, settings ) : node );
  1879. if ( scope === null ) {
  1880. return ( ...params ) => {
  1881. return assignNode( new NodeClass( ...nodeArray( params ) ) );
  1882. };
  1883. } else if ( factor !== null ) {
  1884. factor = nodeObject( factor );
  1885. return ( ...params ) => {
  1886. return assignNode( new NodeClass( scope, ...nodeArray( params ), factor ) );
  1887. };
  1888. } else {
  1889. return ( ...params ) => {
  1890. return assignNode( new NodeClass( scope, ...nodeArray( params ) ) );
  1891. };
  1892. }
  1893. };
  1894. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  1895. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  1896. };
  1897. class ShaderCallNodeInternal extends Node {
  1898. constructor( shaderNode, inputNodes ) {
  1899. super();
  1900. this.shaderNode = shaderNode;
  1901. this.inputNodes = inputNodes;
  1902. }
  1903. getNodeType( builder ) {
  1904. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  1905. }
  1906. call( builder ) {
  1907. const { shaderNode, inputNodes } = this;
  1908. const properties = builder.getNodeProperties( shaderNode );
  1909. if ( properties.onceOutput ) return properties.onceOutput;
  1910. //
  1911. let result = null;
  1912. if ( shaderNode.layout ) {
  1913. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  1914. if ( functionNodesCacheMap === undefined ) {
  1915. functionNodesCacheMap = new WeakMap();
  1916. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  1917. }
  1918. let functionNode = functionNodesCacheMap.get( shaderNode );
  1919. if ( functionNode === undefined ) {
  1920. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  1921. functionNodesCacheMap.set( shaderNode, functionNode );
  1922. }
  1923. if ( builder.currentFunctionNode !== null ) {
  1924. builder.currentFunctionNode.includes.push( functionNode );
  1925. }
  1926. result = nodeObject( functionNode.call( inputNodes ) );
  1927. } else {
  1928. const jsFunc = shaderNode.jsFunc;
  1929. const outputNode = inputNodes !== null ? jsFunc( inputNodes, builder ) : jsFunc( builder );
  1930. result = nodeObject( outputNode );
  1931. }
  1932. if ( shaderNode.once ) {
  1933. properties.onceOutput = result;
  1934. }
  1935. return result;
  1936. }
  1937. getOutputNode( builder ) {
  1938. const properties = builder.getNodeProperties( this );
  1939. if ( properties.outputNode === null ) {
  1940. properties.outputNode = this.setupOutput( builder );
  1941. }
  1942. return properties.outputNode;
  1943. }
  1944. setup( builder ) {
  1945. return this.getOutputNode( builder );
  1946. }
  1947. setupOutput( builder ) {
  1948. builder.addStack();
  1949. builder.stack.outputNode = this.call( builder );
  1950. return builder.removeStack();
  1951. }
  1952. generate( builder, output ) {
  1953. const outputNode = this.getOutputNode( builder );
  1954. return outputNode.build( builder, output );
  1955. }
  1956. }
  1957. class ShaderNodeInternal extends Node {
  1958. constructor( jsFunc, nodeType ) {
  1959. super( nodeType );
  1960. this.jsFunc = jsFunc;
  1961. this.layout = null;
  1962. this.global = true;
  1963. this.once = false;
  1964. }
  1965. setLayout( layout ) {
  1966. this.layout = layout;
  1967. return this;
  1968. }
  1969. call( inputs = null ) {
  1970. nodeObjects( inputs );
  1971. return nodeObject( new ShaderCallNodeInternal( this, inputs ) );
  1972. }
  1973. setup() {
  1974. return this.call();
  1975. }
  1976. }
  1977. const bools = [ false, true ];
  1978. const uints = [ 0, 1, 2, 3 ];
  1979. const ints = [ - 1, - 2 ];
  1980. 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 ];
  1981. const boolsCacheMap = new Map();
  1982. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  1983. const uintsCacheMap = new Map();
  1984. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  1985. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  1986. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  1987. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  1988. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  1989. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  1990. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  1991. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  1992. const getConstNode = ( value, type ) => {
  1993. if ( constNodesCacheMap.has( value ) ) {
  1994. return constNodesCacheMap.get( value );
  1995. } else if ( value.isNode === true ) {
  1996. return value;
  1997. } else {
  1998. return new ConstNode( value, type );
  1999. }
  2000. };
  2001. const safeGetNodeType = ( node ) => {
  2002. try {
  2003. return node.getNodeType();
  2004. } catch ( _ ) {
  2005. return undefined;
  2006. }
  2007. };
  2008. const ConvertType = function ( type, cacheMap = null ) {
  2009. return ( ...params ) => {
  2010. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => typeof param !== 'object' ) ) ) {
  2011. params = [ getValueFromType( type, ...params ) ];
  2012. }
  2013. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  2014. return nodeObject( cacheMap.get( params[ 0 ] ) );
  2015. }
  2016. if ( params.length === 1 ) {
  2017. const node = getConstNode( params[ 0 ], type );
  2018. if ( safeGetNodeType( node ) === type ) return nodeObject( node );
  2019. return nodeObject( new ConvertNode( node, type ) );
  2020. }
  2021. const nodes = params.map( param => getConstNode( param ) );
  2022. return nodeObject( new JoinNode( nodes, type ) );
  2023. };
  2024. };
  2025. // exports
  2026. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  2027. // utils
  2028. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  2029. // shader node base
  2030. function ShaderNode( jsFunc, nodeType ) {
  2031. return new Proxy( new ShaderNodeInternal( jsFunc, nodeType ), shaderNodeHandler );
  2032. }
  2033. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  2034. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  2035. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  2036. const nodeProxy = ( ...params ) => new ShaderNodeProxy( ...params );
  2037. const nodeImmutable = ( ...params ) => new ShaderNodeImmutable( ...params );
  2038. const Fn = ( jsFunc, nodeType ) => {
  2039. const shaderNode = new ShaderNode( jsFunc, nodeType );
  2040. const fn = ( ...params ) => {
  2041. let inputs;
  2042. nodeObjects( params );
  2043. if ( params[ 0 ] && params[ 0 ].isNode ) {
  2044. inputs = [ ...params ];
  2045. } else {
  2046. inputs = params[ 0 ];
  2047. }
  2048. return shaderNode.call( inputs );
  2049. };
  2050. fn.shaderNode = shaderNode;
  2051. fn.setLayout = ( layout ) => {
  2052. shaderNode.setLayout( layout );
  2053. return fn;
  2054. };
  2055. fn.once = () => {
  2056. shaderNode.once = true;
  2057. return fn;
  2058. };
  2059. return fn;
  2060. };
  2061. const tslFn = ( ...params ) => { // @deprecated, r168
  2062. console.warn( 'TSL.ShaderNode: tslFn() has been renamed to Fn().' );
  2063. return Fn( ...params );
  2064. };
  2065. //
  2066. addMethodChaining( 'toGlobal', ( node ) => {
  2067. node.global = true;
  2068. return node;
  2069. } );
  2070. //
  2071. const setCurrentStack = ( stack ) => {
  2072. currentStack = stack;
  2073. };
  2074. const getCurrentStack = () => currentStack;
  2075. const If = ( ...params ) => currentStack.If( ...params );
  2076. function append( node ) {
  2077. if ( currentStack ) currentStack.add( node );
  2078. return node;
  2079. }
  2080. addMethodChaining( 'append', append );
  2081. // types
  2082. const color = new ConvertType( 'color' );
  2083. const float = new ConvertType( 'float', cacheMaps.float );
  2084. const int = new ConvertType( 'int', cacheMaps.ints );
  2085. const uint = new ConvertType( 'uint', cacheMaps.uint );
  2086. const bool = new ConvertType( 'bool', cacheMaps.bool );
  2087. const vec2 = new ConvertType( 'vec2' );
  2088. const ivec2 = new ConvertType( 'ivec2' );
  2089. const uvec2 = new ConvertType( 'uvec2' );
  2090. const bvec2 = new ConvertType( 'bvec2' );
  2091. const vec3 = new ConvertType( 'vec3' );
  2092. const ivec3 = new ConvertType( 'ivec3' );
  2093. const uvec3 = new ConvertType( 'uvec3' );
  2094. const bvec3 = new ConvertType( 'bvec3' );
  2095. const vec4 = new ConvertType( 'vec4' );
  2096. const ivec4 = new ConvertType( 'ivec4' );
  2097. const uvec4 = new ConvertType( 'uvec4' );
  2098. const bvec4 = new ConvertType( 'bvec4' );
  2099. const mat2 = new ConvertType( 'mat2' );
  2100. const mat3 = new ConvertType( 'mat3' );
  2101. const mat4 = new ConvertType( 'mat4' );
  2102. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  2103. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  2104. addMethodChaining( 'toColor', color );
  2105. addMethodChaining( 'toFloat', float );
  2106. addMethodChaining( 'toInt', int );
  2107. addMethodChaining( 'toUint', uint );
  2108. addMethodChaining( 'toBool', bool );
  2109. addMethodChaining( 'toVec2', vec2 );
  2110. addMethodChaining( 'toIVec2', ivec2 );
  2111. addMethodChaining( 'toUVec2', uvec2 );
  2112. addMethodChaining( 'toBVec2', bvec2 );
  2113. addMethodChaining( 'toVec3', vec3 );
  2114. addMethodChaining( 'toIVec3', ivec3 );
  2115. addMethodChaining( 'toUVec3', uvec3 );
  2116. addMethodChaining( 'toBVec3', bvec3 );
  2117. addMethodChaining( 'toVec4', vec4 );
  2118. addMethodChaining( 'toIVec4', ivec4 );
  2119. addMethodChaining( 'toUVec4', uvec4 );
  2120. addMethodChaining( 'toBVec4', bvec4 );
  2121. addMethodChaining( 'toMat2', mat2 );
  2122. addMethodChaining( 'toMat3', mat3 );
  2123. addMethodChaining( 'toMat4', mat4 );
  2124. // basic nodes
  2125. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode );
  2126. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  2127. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  2128. addMethodChaining( 'element', element );
  2129. addMethodChaining( 'convert', convert );
  2130. /**
  2131. * This node can be used to group single instances of {@link UniformNode}
  2132. * and manage them as a uniform buffer.
  2133. *
  2134. * In most cases, the predefined nodes `objectGroup`, `renderGroup` and `frameGroup`
  2135. * will be used when defining the {@link UniformNode#groupNode} property.
  2136. *
  2137. * - `objectGroup`: Uniform buffer per object.
  2138. * - `renderGroup`: Shared uniform buffer, updated once per render call.
  2139. * - `frameGroup`: Shared uniform buffer, updated once per frame.
  2140. *
  2141. * @augments Node
  2142. */
  2143. class UniformGroupNode extends Node {
  2144. static get type() {
  2145. return 'UniformGroupNode';
  2146. }
  2147. /**
  2148. * Constructs a new uniform group node.
  2149. *
  2150. * @param {String} name - The name of the uniform group node.
  2151. * @param {Boolean} [shared=false] - Whether this uniform group node is shared or not.
  2152. * @param {Number} [order=1] - Influences the internal sorting.
  2153. */
  2154. constructor( name, shared = false, order = 1 ) {
  2155. super( 'string' );
  2156. /**
  2157. * The name of the uniform group node.
  2158. *
  2159. * @type {String}
  2160. */
  2161. this.name = name;
  2162. /**
  2163. * Whether this uniform group node is shared or not.
  2164. *
  2165. * @type {Boolean}
  2166. * @default false
  2167. */
  2168. this.shared = shared;
  2169. /**
  2170. * Influences the internal sorting.
  2171. * TODO: Add details when this property should be changed.
  2172. *
  2173. * @type {Number}
  2174. * @default 1
  2175. */
  2176. this.order = order;
  2177. /**
  2178. * This flag can be used for type testing.
  2179. *
  2180. * @type {Boolean}
  2181. * @readonly
  2182. * @default true
  2183. */
  2184. this.isUniformGroup = true;
  2185. }
  2186. serialize( data ) {
  2187. super.serialize( data );
  2188. data.name = this.name;
  2189. data.version = this.version;
  2190. data.shared = this.shared;
  2191. }
  2192. deserialize( data ) {
  2193. super.deserialize( data );
  2194. this.name = data.name;
  2195. this.version = data.version;
  2196. this.shared = data.shared;
  2197. }
  2198. }
  2199. const uniformGroup = ( name ) => new UniformGroupNode( name );
  2200. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  2201. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  2202. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  2203. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  2204. /**
  2205. * Class for representing a uniform.
  2206. *
  2207. * @augments InputNode
  2208. */
  2209. class UniformNode extends InputNode {
  2210. static get type() {
  2211. return 'UniformNode';
  2212. }
  2213. /**
  2214. * Constructs a new uniform node.
  2215. *
  2216. * @param {Any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  2217. * @param {String?} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2218. */
  2219. constructor( value, nodeType = null ) {
  2220. super( value, nodeType );
  2221. /**
  2222. * This flag can be used for type testing.
  2223. *
  2224. * @type {Boolean}
  2225. * @readonly
  2226. * @default true
  2227. */
  2228. this.isUniformNode = true;
  2229. /**
  2230. * The name or label of the uniform.
  2231. *
  2232. * @type {String}
  2233. * @default ''
  2234. */
  2235. this.name = '';
  2236. /**
  2237. * The uniform group of this uniform. By default, uniforms are
  2238. * managed per object but they might belong to a shared group
  2239. * which is updated per frame or render call.
  2240. *
  2241. * @type {UniformGroupNode}
  2242. */
  2243. this.groupNode = objectGroup;
  2244. }
  2245. /**
  2246. * Sets the {@link UniformNode#name} property.
  2247. *
  2248. * @param {String} name - The name of the uniform.
  2249. * @return {UniformNode} A reference to this node.
  2250. */
  2251. label( name ) {
  2252. this.name = name;
  2253. return this;
  2254. }
  2255. /**
  2256. * Sets the {@link UniformNode#groupNode} property.
  2257. *
  2258. * @param {UniformGroupNode} group - The uniform group.
  2259. * @return {UniformNode} A reference to this node.
  2260. */
  2261. setGroup( group ) {
  2262. this.groupNode = group;
  2263. return this;
  2264. }
  2265. /**
  2266. * Returns the {@link UniformNode#groupNode}.
  2267. *
  2268. * @return {UniformGroupNode} The uniform group.
  2269. */
  2270. getGroup() {
  2271. return this.groupNode;
  2272. }
  2273. /**
  2274. * By default, this method returns the result of {@link Node#getHash} but derived
  2275. * classes might overwrite this method with a different implementation.
  2276. *
  2277. * @param {NodeBuilder} builder - The current node builder.
  2278. * @return {String} The uniform hash.
  2279. */
  2280. getUniformHash( builder ) {
  2281. return this.getHash( builder );
  2282. }
  2283. onUpdate( callback, updateType ) {
  2284. const self = this.getSelf();
  2285. callback = callback.bind( self );
  2286. return super.onUpdate( ( frame ) => {
  2287. const value = callback( frame, self );
  2288. if ( value !== undefined ) {
  2289. this.value = value;
  2290. }
  2291. }, updateType );
  2292. }
  2293. generate( builder, output ) {
  2294. const type = this.getNodeType( builder );
  2295. const hash = this.getUniformHash( builder );
  2296. let sharedNode = builder.getNodeFromHash( hash );
  2297. if ( sharedNode === undefined ) {
  2298. builder.setHashNode( this, hash );
  2299. sharedNode = this;
  2300. }
  2301. const sharedNodeType = sharedNode.getInputType( builder );
  2302. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.label );
  2303. const propertyName = builder.getPropertyName( nodeUniform );
  2304. if ( builder.context.label !== undefined ) delete builder.context.label;
  2305. return builder.format( propertyName, type, output );
  2306. }
  2307. }
  2308. const uniform = ( arg1, arg2 ) => {
  2309. const nodeType = getConstNodeType( arg2 || arg1 );
  2310. // @TODO: get ConstNode from .traverse() in the future
  2311. const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1;
  2312. return nodeObject( new UniformNode( value, nodeType ) );
  2313. };
  2314. /**
  2315. * This class represents a shader property. It can be used on
  2316. * to explicitly define a property and assign a value to it.
  2317. *
  2318. * ```js
  2319. * const threshold = property( 'float', 'threshold' ).assign( THRESHOLD );
  2320. *```
  2321. * `PropertyNode` is used by the engine to predefined common material properties
  2322. * for TSL code.
  2323. *
  2324. * @augments Node
  2325. */
  2326. class PropertyNode extends Node {
  2327. static get type() {
  2328. return 'PropertyNode';
  2329. }
  2330. /**
  2331. * Constructs a new property node.
  2332. *
  2333. * @param {String} nodeType - The type of the node.
  2334. * @param {String?} [name=null] - The name of the property in the shader.
  2335. * @param {Boolean} [varying=false] - Whether this property is a varying or not.
  2336. */
  2337. constructor( nodeType, name = null, varying = false ) {
  2338. super( nodeType );
  2339. /**
  2340. * The name of the property in the shader. If no name is defined,
  2341. * the node system auto-generates one.
  2342. *
  2343. * @type {String?}
  2344. * @default null
  2345. */
  2346. this.name = name;
  2347. /**
  2348. * Whether this property is a varying or not.
  2349. *
  2350. * @type {Boolean}
  2351. * @default false
  2352. */
  2353. this.varying = varying;
  2354. /**
  2355. * This flag can be used for type testing.
  2356. *
  2357. * @type {Boolean}
  2358. * @readonly
  2359. * @default true
  2360. */
  2361. this.isPropertyNode = true;
  2362. }
  2363. getHash( builder ) {
  2364. return this.name || super.getHash( builder );
  2365. }
  2366. /**
  2367. * The method is overwritten so it always returns `true`.
  2368. *
  2369. * @param {NodeBuilder} builder - The current node builder.
  2370. * @return {Boolean} Whether this node is global or not.
  2371. */
  2372. isGlobal( /*builder*/ ) {
  2373. return true;
  2374. }
  2375. generate( builder ) {
  2376. let nodeVar;
  2377. if ( this.varying === true ) {
  2378. nodeVar = builder.getVaryingFromNode( this, this.name );
  2379. nodeVar.needsInterpolation = true;
  2380. } else {
  2381. nodeVar = builder.getVarFromNode( this, this.name );
  2382. }
  2383. return builder.getPropertyName( nodeVar );
  2384. }
  2385. }
  2386. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  2387. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  2388. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  2389. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  2390. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  2391. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  2392. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  2393. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  2394. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  2395. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  2396. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  2397. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  2398. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  2399. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  2400. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  2401. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  2402. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  2403. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  2404. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  2405. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  2406. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  2407. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  2408. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  2409. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  2410. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  2411. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  2412. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  2413. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  2414. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  2415. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  2416. /**
  2417. * These node represents an assign operation. Meaning a node is assigned
  2418. * to another node.
  2419. *
  2420. * @augments TempNode
  2421. */
  2422. class AssignNode extends TempNode {
  2423. static get type() {
  2424. return 'AssignNode';
  2425. }
  2426. /**
  2427. * Constructs a new assign node.
  2428. *
  2429. * @param {Node} targetNode - The target node.
  2430. * @param {Node} sourceNode - The source type.
  2431. */
  2432. constructor( targetNode, sourceNode ) {
  2433. super();
  2434. /**
  2435. * The target node.
  2436. *
  2437. * @type {Node}
  2438. */
  2439. this.targetNode = targetNode;
  2440. /**
  2441. * The source node.
  2442. *
  2443. * @type {Node}
  2444. */
  2445. this.sourceNode = sourceNode;
  2446. }
  2447. /**
  2448. * Whether this node is used more than once in context of other nodes. This method
  2449. * is overwritten since it always returns `false` (assigns are unique).
  2450. *
  2451. * @return {Boolean} A flag that indicates if there is more than one dependency to other nodes. Always `false`.
  2452. */
  2453. hasDependencies() {
  2454. return false;
  2455. }
  2456. getNodeType( builder, output ) {
  2457. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  2458. }
  2459. /**
  2460. * Whether a split is required when assigning source to target. This can happen when the component length of
  2461. * target and source data type does not match.
  2462. *
  2463. * @param {NodeBuilder} builder - The current node builder.
  2464. * @return {Boolean} Whether a split is required when assigning source to target.
  2465. */
  2466. needsSplitAssign( builder ) {
  2467. const { targetNode } = this;
  2468. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  2469. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  2470. const assignDifferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  2471. return assignDifferentVector;
  2472. }
  2473. return false;
  2474. }
  2475. generate( builder, output ) {
  2476. const { targetNode, sourceNode } = this;
  2477. const needsSplitAssign = this.needsSplitAssign( builder );
  2478. const targetType = targetNode.getNodeType( builder );
  2479. const target = targetNode.context( { assign: true } ).build( builder );
  2480. const source = sourceNode.build( builder, targetType );
  2481. const sourceType = sourceNode.getNodeType( builder );
  2482. const nodeData = builder.getDataFromNode( this );
  2483. //
  2484. let snippet;
  2485. if ( nodeData.initialized === true ) {
  2486. if ( output !== 'void' ) {
  2487. snippet = target;
  2488. }
  2489. } else if ( needsSplitAssign ) {
  2490. const sourceVar = builder.getVarFromNode( this, null, targetType );
  2491. const sourceProperty = builder.getPropertyName( sourceVar );
  2492. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  2493. const targetRoot = targetNode.node.context( { assign: true } ).build( builder );
  2494. for ( let i = 0; i < targetNode.components.length; i ++ ) {
  2495. const component = targetNode.components[ i ];
  2496. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  2497. }
  2498. if ( output !== 'void' ) {
  2499. snippet = target;
  2500. }
  2501. } else {
  2502. snippet = `${ target } = ${ source }`;
  2503. if ( output === 'void' || sourceType === 'void' ) {
  2504. builder.addLineFlowCode( snippet, this );
  2505. if ( output !== 'void' ) {
  2506. snippet = target;
  2507. }
  2508. }
  2509. }
  2510. nodeData.initialized = true;
  2511. return builder.format( snippet, targetType, output );
  2512. }
  2513. }
  2514. const assign = /*@__PURE__*/ nodeProxy( AssignNode );
  2515. addMethodChaining( 'assign', assign );
  2516. /**
  2517. * This module represents the call of a {@link FunctionNode}. Developers are usually not confronted
  2518. * with this module since they use the predefined TSL syntax `wgslFn` and `glslFn` which encapsulate
  2519. * this logic.
  2520. *
  2521. * @augments TempNode
  2522. */
  2523. class FunctionCallNode extends TempNode {
  2524. static get type() {
  2525. return 'FunctionCallNode';
  2526. }
  2527. /**
  2528. * Constructs a new function call node.
  2529. *
  2530. * @param {FunctionNode?} functionNode - The function node.
  2531. * @param {Object<String, Node>} [parameters={}] - The parameters for the function call.
  2532. */
  2533. constructor( functionNode = null, parameters = {} ) {
  2534. super();
  2535. /**
  2536. * The function node.
  2537. *
  2538. * @type {FunctionNode}
  2539. * @default null
  2540. */
  2541. this.functionNode = functionNode;
  2542. /**
  2543. * The parameters of the function call.
  2544. *
  2545. * @type {Object<String, Node>}
  2546. * @default {}
  2547. */
  2548. this.parameters = parameters;
  2549. }
  2550. /**
  2551. * Sets the parameters of the function call node.
  2552. *
  2553. * @param {Object<String, Node>} parameters - The parameters to set.
  2554. * @return {FunctionCallNode} A reference to this node.
  2555. */
  2556. setParameters( parameters ) {
  2557. this.parameters = parameters;
  2558. return this;
  2559. }
  2560. /**
  2561. * Returns the parameters of the function call node.
  2562. *
  2563. * @return {Object<String, Node>} The parameters of this node.
  2564. */
  2565. getParameters() {
  2566. return this.parameters;
  2567. }
  2568. getNodeType( builder ) {
  2569. return this.functionNode.getNodeType( builder );
  2570. }
  2571. generate( builder ) {
  2572. const params = [];
  2573. const functionNode = this.functionNode;
  2574. const inputs = functionNode.getInputs( builder );
  2575. const parameters = this.parameters;
  2576. const generateInput = ( node, inputNode ) => {
  2577. const type = inputNode.type;
  2578. const pointer = type === 'pointer';
  2579. let output;
  2580. if ( pointer ) output = '&' + node.build( builder );
  2581. else output = node.build( builder, type );
  2582. return output;
  2583. };
  2584. if ( Array.isArray( parameters ) ) {
  2585. for ( let i = 0; i < parameters.length; i ++ ) {
  2586. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  2587. }
  2588. } else {
  2589. for ( const inputNode of inputs ) {
  2590. const node = parameters[ inputNode.name ];
  2591. if ( node !== undefined ) {
  2592. params.push( generateInput( node, inputNode ) );
  2593. } else {
  2594. throw new Error( `FunctionCallNode: Input '${inputNode.name}' not found in FunctionNode.` );
  2595. }
  2596. }
  2597. }
  2598. const functionName = functionNode.build( builder, 'property' );
  2599. return `${functionName}( ${params.join( ', ' )} )`;
  2600. }
  2601. }
  2602. const call = ( func, ...params ) => {
  2603. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  2604. return nodeObject( new FunctionCallNode( nodeObject( func ), params ) );
  2605. };
  2606. addMethodChaining( 'call', call );
  2607. class OperatorNode extends TempNode {
  2608. static get type() {
  2609. return 'OperatorNode';
  2610. }
  2611. constructor( op, aNode, bNode, ...params ) {
  2612. super();
  2613. if ( params.length > 0 ) {
  2614. let finalOp = new OperatorNode( op, aNode, bNode );
  2615. for ( let i = 0; i < params.length - 1; i ++ ) {
  2616. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  2617. }
  2618. aNode = finalOp;
  2619. bNode = params[ params.length - 1 ];
  2620. }
  2621. this.op = op;
  2622. this.aNode = aNode;
  2623. this.bNode = bNode;
  2624. }
  2625. getNodeType( builder, output ) {
  2626. const op = this.op;
  2627. const aNode = this.aNode;
  2628. const bNode = this.bNode;
  2629. const typeA = aNode.getNodeType( builder );
  2630. const typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  2631. if ( typeA === 'void' || typeB === 'void' ) {
  2632. return 'void';
  2633. } else if ( op === '%' ) {
  2634. return typeA;
  2635. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  2636. return builder.getIntegerType( typeA );
  2637. } else if ( op === '!' || op === '==' || op === '&&' || op === '||' || op === '^^' ) {
  2638. return 'bool';
  2639. } else if ( op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  2640. const typeLength = output ? builder.getTypeLength( output ) : Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  2641. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  2642. } else {
  2643. if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  2644. return typeB;
  2645. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  2646. // matrix x vector
  2647. return builder.getVectorFromMatrix( typeA );
  2648. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  2649. // vector x matrix
  2650. return builder.getVectorFromMatrix( typeB );
  2651. } else if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  2652. // anytype x anytype: use the greater length vector
  2653. return typeB;
  2654. }
  2655. return typeA;
  2656. }
  2657. }
  2658. generate( builder, output ) {
  2659. const op = this.op;
  2660. const aNode = this.aNode;
  2661. const bNode = this.bNode;
  2662. const type = this.getNodeType( builder, output );
  2663. let typeA = null;
  2664. let typeB = null;
  2665. if ( type !== 'void' ) {
  2666. typeA = aNode.getNodeType( builder );
  2667. typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  2668. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' ) {
  2669. if ( builder.isVector( typeA ) ) {
  2670. typeB = typeA;
  2671. } else if ( typeA !== typeB ) {
  2672. typeA = typeB = 'float';
  2673. }
  2674. } else if ( op === '>>' || op === '<<' ) {
  2675. typeA = type;
  2676. typeB = builder.changeComponentType( typeB, 'uint' );
  2677. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  2678. // matrix x vector
  2679. typeB = builder.getVectorFromMatrix( typeA );
  2680. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  2681. // vector x matrix
  2682. typeA = builder.getVectorFromMatrix( typeB );
  2683. } else {
  2684. // anytype x anytype
  2685. typeA = typeB = type;
  2686. }
  2687. } else {
  2688. typeA = typeB = type;
  2689. }
  2690. const a = aNode.build( builder, typeA );
  2691. const b = typeof bNode !== 'undefined' ? bNode.build( builder, typeB ) : null;
  2692. const outputLength = builder.getTypeLength( output );
  2693. const fnOpSnippet = builder.getFunctionOperator( op );
  2694. if ( output !== 'void' ) {
  2695. if ( op === '<' && outputLength > 1 ) {
  2696. if ( builder.useComparisonMethod ) {
  2697. return builder.format( `${ builder.getMethod( 'lessThan', output ) }( ${ a }, ${ b } )`, type, output );
  2698. } else {
  2699. return builder.format( `( ${ a } < ${ b } )`, type, output );
  2700. }
  2701. } else if ( op === '<=' && outputLength > 1 ) {
  2702. if ( builder.useComparisonMethod ) {
  2703. return builder.format( `${ builder.getMethod( 'lessThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  2704. } else {
  2705. return builder.format( `( ${ a } <= ${ b } )`, type, output );
  2706. }
  2707. } else if ( op === '>' && outputLength > 1 ) {
  2708. if ( builder.useComparisonMethod ) {
  2709. return builder.format( `${ builder.getMethod( 'greaterThan', output ) }( ${ a }, ${ b } )`, type, output );
  2710. } else {
  2711. return builder.format( `( ${ a } > ${ b } )`, type, output );
  2712. }
  2713. } else if ( op === '>=' && outputLength > 1 ) {
  2714. if ( builder.useComparisonMethod ) {
  2715. return builder.format( `${ builder.getMethod( 'greaterThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  2716. } else {
  2717. return builder.format( `( ${ a } >= ${ b } )`, type, output );
  2718. }
  2719. } else if ( op === '!' || op === '~' ) {
  2720. return builder.format( `(${op}${a})`, typeA, output );
  2721. } else if ( fnOpSnippet ) {
  2722. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  2723. } else {
  2724. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  2725. }
  2726. } else if ( typeA !== 'void' ) {
  2727. if ( fnOpSnippet ) {
  2728. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  2729. } else {
  2730. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  2731. }
  2732. }
  2733. }
  2734. serialize( data ) {
  2735. super.serialize( data );
  2736. data.op = this.op;
  2737. }
  2738. deserialize( data ) {
  2739. super.deserialize( data );
  2740. this.op = data.op;
  2741. }
  2742. }
  2743. const add = /*@__PURE__*/ nodeProxy( OperatorNode, '+' );
  2744. const sub = /*@__PURE__*/ nodeProxy( OperatorNode, '-' );
  2745. const mul = /*@__PURE__*/ nodeProxy( OperatorNode, '*' );
  2746. const div = /*@__PURE__*/ nodeProxy( OperatorNode, '/' );
  2747. const modInt = /*@__PURE__*/ nodeProxy( OperatorNode, '%' );
  2748. const equal = /*@__PURE__*/ nodeProxy( OperatorNode, '==' );
  2749. const notEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '!=' );
  2750. const lessThan = /*@__PURE__*/ nodeProxy( OperatorNode, '<' );
  2751. const greaterThan = /*@__PURE__*/ nodeProxy( OperatorNode, '>' );
  2752. const lessThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '<=' );
  2753. const greaterThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '>=' );
  2754. const and = /*@__PURE__*/ nodeProxy( OperatorNode, '&&' );
  2755. const or = /*@__PURE__*/ nodeProxy( OperatorNode, '||' );
  2756. const not = /*@__PURE__*/ nodeProxy( OperatorNode, '!' );
  2757. const xor = /*@__PURE__*/ nodeProxy( OperatorNode, '^^' );
  2758. const bitAnd = /*@__PURE__*/ nodeProxy( OperatorNode, '&' );
  2759. const bitNot = /*@__PURE__*/ nodeProxy( OperatorNode, '~' );
  2760. const bitOr = /*@__PURE__*/ nodeProxy( OperatorNode, '|' );
  2761. const bitXor = /*@__PURE__*/ nodeProxy( OperatorNode, '^' );
  2762. const shiftLeft = /*@__PURE__*/ nodeProxy( OperatorNode, '<<' );
  2763. const shiftRight = /*@__PURE__*/ nodeProxy( OperatorNode, '>>' );
  2764. addMethodChaining( 'add', add );
  2765. addMethodChaining( 'sub', sub );
  2766. addMethodChaining( 'mul', mul );
  2767. addMethodChaining( 'div', div );
  2768. addMethodChaining( 'modInt', modInt );
  2769. addMethodChaining( 'equal', equal );
  2770. addMethodChaining( 'notEqual', notEqual );
  2771. addMethodChaining( 'lessThan', lessThan );
  2772. addMethodChaining( 'greaterThan', greaterThan );
  2773. addMethodChaining( 'lessThanEqual', lessThanEqual );
  2774. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  2775. addMethodChaining( 'and', and );
  2776. addMethodChaining( 'or', or );
  2777. addMethodChaining( 'not', not );
  2778. addMethodChaining( 'xor', xor );
  2779. addMethodChaining( 'bitAnd', bitAnd );
  2780. addMethodChaining( 'bitNot', bitNot );
  2781. addMethodChaining( 'bitOr', bitOr );
  2782. addMethodChaining( 'bitXor', bitXor );
  2783. addMethodChaining( 'shiftLeft', shiftLeft );
  2784. addMethodChaining( 'shiftRight', shiftRight );
  2785. const remainder = ( ...params ) => { // @deprecated, r168
  2786. console.warn( 'TSL.OperatorNode: .remainder() has been renamed to .modInt().' );
  2787. return modInt( ...params );
  2788. };
  2789. addMethodChaining( 'remainder', remainder );
  2790. class MathNode extends TempNode {
  2791. static get type() {
  2792. return 'MathNode';
  2793. }
  2794. constructor( method, aNode, bNode = null, cNode = null ) {
  2795. super();
  2796. this.method = method;
  2797. this.aNode = aNode;
  2798. this.bNode = bNode;
  2799. this.cNode = cNode;
  2800. }
  2801. getInputType( builder ) {
  2802. const aType = this.aNode.getNodeType( builder );
  2803. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  2804. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  2805. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  2806. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  2807. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  2808. if ( aLen > bLen && aLen > cLen ) {
  2809. return aType;
  2810. } else if ( bLen > cLen ) {
  2811. return bType;
  2812. } else if ( cLen > aLen ) {
  2813. return cType;
  2814. }
  2815. return aType;
  2816. }
  2817. getNodeType( builder ) {
  2818. const method = this.method;
  2819. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  2820. return 'float';
  2821. } else if ( method === MathNode.CROSS ) {
  2822. return 'vec3';
  2823. } else if ( method === MathNode.ALL ) {
  2824. return 'bool';
  2825. } else if ( method === MathNode.EQUALS ) {
  2826. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  2827. } else if ( method === MathNode.MOD ) {
  2828. return this.aNode.getNodeType( builder );
  2829. } else {
  2830. return this.getInputType( builder );
  2831. }
  2832. }
  2833. generate( builder, output ) {
  2834. const method = this.method;
  2835. const type = this.getNodeType( builder );
  2836. const inputType = this.getInputType( builder );
  2837. const a = this.aNode;
  2838. const b = this.bNode;
  2839. const c = this.cNode;
  2840. const isWebGL = builder.renderer.isWebGLRenderer === true;
  2841. if ( method === MathNode.TRANSFORM_DIRECTION ) {
  2842. // dir can be either a direction vector or a normal vector
  2843. // upper-left 3x3 of matrix is assumed to be orthogonal
  2844. let tA = a;
  2845. let tB = b;
  2846. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  2847. tB = vec4( vec3( tB ), 0.0 );
  2848. } else {
  2849. tA = vec4( vec3( tA ), 0.0 );
  2850. }
  2851. const mulNode = mul( tA, tB ).xyz;
  2852. return normalize( mulNode ).build( builder, output );
  2853. } else if ( method === MathNode.NEGATE ) {
  2854. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  2855. } else if ( method === MathNode.ONE_MINUS ) {
  2856. return sub( 1.0, a ).build( builder, output );
  2857. } else if ( method === MathNode.RECIPROCAL ) {
  2858. return div( 1.0, a ).build( builder, output );
  2859. } else if ( method === MathNode.DIFFERENCE ) {
  2860. return abs( sub( a, b ) ).build( builder, output );
  2861. } else {
  2862. const params = [];
  2863. if ( method === MathNode.CROSS || method === MathNode.MOD ) {
  2864. params.push(
  2865. a.build( builder, type ),
  2866. b.build( builder, type )
  2867. );
  2868. } else if ( isWebGL && method === MathNode.STEP ) {
  2869. params.push(
  2870. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  2871. b.build( builder, inputType )
  2872. );
  2873. } else if ( ( isWebGL && ( method === MathNode.MIN || method === MathNode.MAX ) ) || method === MathNode.MOD ) {
  2874. params.push(
  2875. a.build( builder, inputType ),
  2876. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  2877. );
  2878. } else if ( method === MathNode.REFRACT ) {
  2879. params.push(
  2880. a.build( builder, inputType ),
  2881. b.build( builder, inputType ),
  2882. c.build( builder, 'float' )
  2883. );
  2884. } else if ( method === MathNode.MIX ) {
  2885. params.push(
  2886. a.build( builder, inputType ),
  2887. b.build( builder, inputType ),
  2888. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  2889. );
  2890. } else {
  2891. params.push( a.build( builder, inputType ) );
  2892. if ( b !== null ) params.push( b.build( builder, inputType ) );
  2893. if ( c !== null ) params.push( c.build( builder, inputType ) );
  2894. }
  2895. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  2896. }
  2897. }
  2898. serialize( data ) {
  2899. super.serialize( data );
  2900. data.method = this.method;
  2901. }
  2902. deserialize( data ) {
  2903. super.deserialize( data );
  2904. this.method = data.method;
  2905. }
  2906. }
  2907. // 1 input
  2908. MathNode.ALL = 'all';
  2909. MathNode.ANY = 'any';
  2910. MathNode.EQUALS = 'equals';
  2911. MathNode.RADIANS = 'radians';
  2912. MathNode.DEGREES = 'degrees';
  2913. MathNode.EXP = 'exp';
  2914. MathNode.EXP2 = 'exp2';
  2915. MathNode.LOG = 'log';
  2916. MathNode.LOG2 = 'log2';
  2917. MathNode.SQRT = 'sqrt';
  2918. MathNode.INVERSE_SQRT = 'inversesqrt';
  2919. MathNode.FLOOR = 'floor';
  2920. MathNode.CEIL = 'ceil';
  2921. MathNode.NORMALIZE = 'normalize';
  2922. MathNode.FRACT = 'fract';
  2923. MathNode.SIN = 'sin';
  2924. MathNode.COS = 'cos';
  2925. MathNode.TAN = 'tan';
  2926. MathNode.ASIN = 'asin';
  2927. MathNode.ACOS = 'acos';
  2928. MathNode.ATAN = 'atan';
  2929. MathNode.ABS = 'abs';
  2930. MathNode.SIGN = 'sign';
  2931. MathNode.LENGTH = 'length';
  2932. MathNode.NEGATE = 'negate';
  2933. MathNode.ONE_MINUS = 'oneMinus';
  2934. MathNode.DFDX = 'dFdx';
  2935. MathNode.DFDY = 'dFdy';
  2936. MathNode.ROUND = 'round';
  2937. MathNode.RECIPROCAL = 'reciprocal';
  2938. MathNode.TRUNC = 'trunc';
  2939. MathNode.FWIDTH = 'fwidth';
  2940. MathNode.BITCAST = 'bitcast';
  2941. MathNode.TRANSPOSE = 'transpose';
  2942. // 2 inputs
  2943. MathNode.ATAN2 = 'atan2';
  2944. MathNode.MIN = 'min';
  2945. MathNode.MAX = 'max';
  2946. MathNode.MOD = 'mod';
  2947. MathNode.STEP = 'step';
  2948. MathNode.REFLECT = 'reflect';
  2949. MathNode.DISTANCE = 'distance';
  2950. MathNode.DIFFERENCE = 'difference';
  2951. MathNode.DOT = 'dot';
  2952. MathNode.CROSS = 'cross';
  2953. MathNode.POW = 'pow';
  2954. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  2955. // 3 inputs
  2956. MathNode.MIX = 'mix';
  2957. MathNode.CLAMP = 'clamp';
  2958. MathNode.REFRACT = 'refract';
  2959. MathNode.SMOOTHSTEP = 'smoothstep';
  2960. MathNode.FACEFORWARD = 'faceforward';
  2961. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  2962. const INFINITY = /*@__PURE__*/ float( 1e6 );
  2963. const PI = /*@__PURE__*/ float( Math.PI );
  2964. const PI2 = /*@__PURE__*/ float( Math.PI * 2 );
  2965. const all = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ALL );
  2966. const any = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ANY );
  2967. const equals = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EQUALS );
  2968. const radians = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RADIANS );
  2969. const degrees = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DEGREES );
  2970. const exp = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP );
  2971. const exp2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP2 );
  2972. const log = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG );
  2973. const log2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG2 );
  2974. const sqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SQRT );
  2975. const inverseSqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.INVERSE_SQRT );
  2976. const floor = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FLOOR );
  2977. const ceil = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CEIL );
  2978. const normalize = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NORMALIZE );
  2979. const fract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FRACT );
  2980. const sin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIN );
  2981. const cos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.COS );
  2982. const tan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TAN );
  2983. const asin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ASIN );
  2984. const acos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ACOS );
  2985. const atan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN );
  2986. const abs = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ABS );
  2987. const sign = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIGN );
  2988. const length = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LENGTH );
  2989. const negate = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NEGATE );
  2990. const oneMinus = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ONE_MINUS );
  2991. const dFdx = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDX );
  2992. const dFdy = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDY );
  2993. const round = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ROUND );
  2994. const reciprocal = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RECIPROCAL );
  2995. const trunc = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRUNC );
  2996. const fwidth = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FWIDTH );
  2997. const bitcast = /*@__PURE__*/ nodeProxy( MathNode, MathNode.BITCAST );
  2998. const transpose = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSPOSE );
  2999. const atan2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN2 );
  3000. const min$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIN );
  3001. const max$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MAX );
  3002. const mod = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MOD );
  3003. const step = /*@__PURE__*/ nodeProxy( MathNode, MathNode.STEP );
  3004. const reflect = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFLECT );
  3005. const distance = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DISTANCE );
  3006. const difference = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DIFFERENCE );
  3007. const dot = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DOT );
  3008. const cross = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CROSS );
  3009. const pow = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW );
  3010. const pow2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 2 );
  3011. const pow3 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 3 );
  3012. const pow4 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 4 );
  3013. const transformDirection = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSFORM_DIRECTION );
  3014. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  3015. const lengthSq = ( a ) => dot( a, a );
  3016. const mix = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIX );
  3017. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  3018. const saturate = ( value ) => clamp( value );
  3019. const refract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFRACT );
  3020. const smoothstep = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SMOOTHSTEP );
  3021. const faceForward = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FACEFORWARD );
  3022. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  3023. const a = 12.9898, b = 78.233, c = 43758.5453;
  3024. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  3025. return fract( sin( sn ).mul( c ) );
  3026. } );
  3027. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  3028. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  3029. addMethodChaining( 'all', all );
  3030. addMethodChaining( 'any', any );
  3031. addMethodChaining( 'equals', equals );
  3032. addMethodChaining( 'radians', radians );
  3033. addMethodChaining( 'degrees', degrees );
  3034. addMethodChaining( 'exp', exp );
  3035. addMethodChaining( 'exp2', exp2 );
  3036. addMethodChaining( 'log', log );
  3037. addMethodChaining( 'log2', log2 );
  3038. addMethodChaining( 'sqrt', sqrt );
  3039. addMethodChaining( 'inverseSqrt', inverseSqrt );
  3040. addMethodChaining( 'floor', floor );
  3041. addMethodChaining( 'ceil', ceil );
  3042. addMethodChaining( 'normalize', normalize );
  3043. addMethodChaining( 'fract', fract );
  3044. addMethodChaining( 'sin', sin );
  3045. addMethodChaining( 'cos', cos );
  3046. addMethodChaining( 'tan', tan );
  3047. addMethodChaining( 'asin', asin );
  3048. addMethodChaining( 'acos', acos );
  3049. addMethodChaining( 'atan', atan );
  3050. addMethodChaining( 'abs', abs );
  3051. addMethodChaining( 'sign', sign );
  3052. addMethodChaining( 'length', length );
  3053. addMethodChaining( 'lengthSq', lengthSq );
  3054. addMethodChaining( 'negate', negate );
  3055. addMethodChaining( 'oneMinus', oneMinus );
  3056. addMethodChaining( 'dFdx', dFdx );
  3057. addMethodChaining( 'dFdy', dFdy );
  3058. addMethodChaining( 'round', round );
  3059. addMethodChaining( 'reciprocal', reciprocal );
  3060. addMethodChaining( 'trunc', trunc );
  3061. addMethodChaining( 'fwidth', fwidth );
  3062. addMethodChaining( 'atan2', atan2 );
  3063. addMethodChaining( 'min', min$1 );
  3064. addMethodChaining( 'max', max$1 );
  3065. addMethodChaining( 'mod', mod );
  3066. addMethodChaining( 'step', step );
  3067. addMethodChaining( 'reflect', reflect );
  3068. addMethodChaining( 'distance', distance );
  3069. addMethodChaining( 'dot', dot );
  3070. addMethodChaining( 'cross', cross );
  3071. addMethodChaining( 'pow', pow );
  3072. addMethodChaining( 'pow2', pow2 );
  3073. addMethodChaining( 'pow3', pow3 );
  3074. addMethodChaining( 'pow4', pow4 );
  3075. addMethodChaining( 'transformDirection', transformDirection );
  3076. addMethodChaining( 'mix', mixElement );
  3077. addMethodChaining( 'clamp', clamp );
  3078. addMethodChaining( 'refract', refract );
  3079. addMethodChaining( 'smoothstep', smoothstepElement );
  3080. addMethodChaining( 'faceForward', faceForward );
  3081. addMethodChaining( 'difference', difference );
  3082. addMethodChaining( 'saturate', saturate );
  3083. addMethodChaining( 'cbrt', cbrt );
  3084. addMethodChaining( 'transpose', transpose );
  3085. addMethodChaining( 'rand', rand );
  3086. class ConditionalNode extends Node {
  3087. static get type() {
  3088. return 'ConditionalNode';
  3089. }
  3090. constructor( condNode, ifNode, elseNode = null ) {
  3091. super();
  3092. this.condNode = condNode;
  3093. this.ifNode = ifNode;
  3094. this.elseNode = elseNode;
  3095. }
  3096. getNodeType( builder ) {
  3097. const ifType = this.ifNode.getNodeType( builder );
  3098. if ( this.elseNode !== null ) {
  3099. const elseType = this.elseNode.getNodeType( builder );
  3100. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  3101. return elseType;
  3102. }
  3103. }
  3104. return ifType;
  3105. }
  3106. setup( builder ) {
  3107. const condNode = this.condNode.cache();
  3108. const ifNode = this.ifNode.cache();
  3109. const elseNode = this.elseNode ? this.elseNode.cache() : null;
  3110. //
  3111. const currentNodeBlock = builder.context.nodeBlock;
  3112. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  3113. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  3114. //
  3115. const properties = builder.getNodeProperties( this );
  3116. properties.condNode = condNode;
  3117. properties.ifNode = ifNode.context( { nodeBlock: ifNode } );
  3118. properties.elseNode = elseNode ? elseNode.context( { nodeBlock: elseNode } ) : null;
  3119. }
  3120. generate( builder, output ) {
  3121. const type = this.getNodeType( builder );
  3122. const nodeData = builder.getDataFromNode( this );
  3123. if ( nodeData.nodeProperty !== undefined ) {
  3124. return nodeData.nodeProperty;
  3125. }
  3126. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  3127. const needsOutput = output !== 'void';
  3128. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  3129. nodeData.nodeProperty = nodeProperty;
  3130. const nodeSnippet = condNode.build( builder, 'bool' );
  3131. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  3132. let ifSnippet = ifNode.build( builder, type );
  3133. if ( ifSnippet ) {
  3134. if ( needsOutput ) {
  3135. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  3136. } else {
  3137. ifSnippet = 'return ' + ifSnippet + ';';
  3138. }
  3139. }
  3140. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  3141. if ( elseNode !== null ) {
  3142. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  3143. let elseSnippet = elseNode.build( builder, type );
  3144. if ( elseSnippet ) {
  3145. if ( needsOutput ) {
  3146. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  3147. } else {
  3148. elseSnippet = 'return ' + elseSnippet + ';';
  3149. }
  3150. }
  3151. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  3152. } else {
  3153. builder.addFlowCode( '\n\n' );
  3154. }
  3155. return builder.format( nodeProperty, type, output );
  3156. }
  3157. }
  3158. const select = /*@__PURE__*/ nodeProxy( ConditionalNode );
  3159. addMethodChaining( 'select', select );
  3160. //
  3161. const cond = ( ...params ) => { // @deprecated, r168
  3162. console.warn( 'TSL.ConditionalNode: cond() has been renamed to select().' );
  3163. return select( ...params );
  3164. };
  3165. addMethodChaining( 'cond', cond );
  3166. /**
  3167. * This node can be used as a context management component for another node.
  3168. * {@link NodeBuilder} performs its node building process in a specific context and
  3169. * this node allows the modify the context. A typical use case is to overwrite `getUV()` e.g.:
  3170. *
  3171. * ```js
  3172. *node.context( { getUV: () => customCoord } );
  3173. *```
  3174. * @augments Node
  3175. */
  3176. class ContextNode extends Node {
  3177. static get type() {
  3178. return 'ContextNode';
  3179. }
  3180. /**
  3181. * Constructs a new context node.
  3182. *
  3183. * @param {Node} node - The node whose context should be modified.
  3184. * @param {Object} [value={}] - The modified context data.
  3185. */
  3186. constructor( node, value = {} ) {
  3187. super();
  3188. /**
  3189. * This flag can be used for type testing.
  3190. *
  3191. * @type {Boolean}
  3192. * @readonly
  3193. * @default true
  3194. */
  3195. this.isContextNode = true;
  3196. /**
  3197. * The node whose context should be modified.
  3198. *
  3199. * @type {Node}
  3200. */
  3201. this.node = node;
  3202. /**
  3203. * The modified context data.
  3204. *
  3205. * @type {Object}
  3206. * @default {}
  3207. */
  3208. this.value = value;
  3209. }
  3210. /**
  3211. * This method is overwritten to ensure it returns the reference to {@link ContextNode#node}.
  3212. *
  3213. * @return {Node} A reference to {@link ContextNode#node}.
  3214. */
  3215. getScope() {
  3216. return this.node.getScope();
  3217. }
  3218. /**
  3219. * This method is overwritten to ensure it returns the type to {@link ContextNode#node}.
  3220. *
  3221. * @param {NodeBuilder} builder - The current node builder.
  3222. * @return {String} The type of {@link ContextNode#node}.
  3223. */
  3224. getNodeType( builder ) {
  3225. return this.node.getNodeType( builder );
  3226. }
  3227. analyze( builder ) {
  3228. this.node.build( builder );
  3229. }
  3230. setup( builder ) {
  3231. const previousContext = builder.getContext();
  3232. builder.setContext( { ...builder.context, ...this.value } );
  3233. const node = this.node.build( builder );
  3234. builder.setContext( previousContext );
  3235. return node;
  3236. }
  3237. generate( builder, output ) {
  3238. const previousContext = builder.getContext();
  3239. builder.setContext( { ...builder.context, ...this.value } );
  3240. const snippet = this.node.build( builder, output );
  3241. builder.setContext( previousContext );
  3242. return snippet;
  3243. }
  3244. }
  3245. const context = /*@__PURE__*/ nodeProxy( ContextNode );
  3246. const label = ( node, name ) => context( node, { label: name } );
  3247. addMethodChaining( 'context', context );
  3248. addMethodChaining( 'label', label );
  3249. /**
  3250. * Class for representing shader variables as nodes. Variables are created from
  3251. * existing nodes like the following:
  3252. *
  3253. * ```js
  3254. * const depth = sampleDepth( uvNode ).toVar( 'depth' );
  3255. * ```
  3256. *
  3257. * @augments Node
  3258. */
  3259. class VarNode extends Node {
  3260. static get type() {
  3261. return 'VarNode';
  3262. }
  3263. /**
  3264. * Constructs a new variable node.
  3265. *
  3266. * @param {Node} node - The node for which a variable should be created.
  3267. * @param {String?} name - The name of the variable in the shader.
  3268. */
  3269. constructor( node, name = null ) {
  3270. super();
  3271. /**
  3272. * The node for which a variable should be created.
  3273. *
  3274. * @type {Node}
  3275. */
  3276. this.node = node;
  3277. /**
  3278. * The name of the variable in the shader. If no name is defined,
  3279. * the node system auto-generates one.
  3280. *
  3281. * @type {String?}
  3282. * @default null
  3283. */
  3284. this.name = name;
  3285. /**
  3286. * `VarNode` sets this property to `true` by default.
  3287. *
  3288. * @type {Boolean}
  3289. * @default true
  3290. */
  3291. this.global = true;
  3292. /**
  3293. * This flag can be used for type testing.
  3294. *
  3295. * @type {Boolean}
  3296. * @readonly
  3297. * @default true
  3298. */
  3299. this.isVarNode = true;
  3300. }
  3301. getHash( builder ) {
  3302. return this.name || super.getHash( builder );
  3303. }
  3304. getNodeType( builder ) {
  3305. return this.node.getNodeType( builder );
  3306. }
  3307. generate( builder ) {
  3308. const { node, name } = this;
  3309. const nodeVar = builder.getVarFromNode( this, name, builder.getVectorType( this.getNodeType( builder ) ) );
  3310. const propertyName = builder.getPropertyName( nodeVar );
  3311. const snippet = node.build( builder, nodeVar.type );
  3312. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  3313. return propertyName;
  3314. }
  3315. }
  3316. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  3317. addMethodChaining( 'toVar', ( ...params ) => createVar( ...params ).append() );
  3318. // Deprecated
  3319. const temp = ( node ) => { // @deprecated, r170
  3320. console.warn( 'TSL: "temp" is deprecated. Use ".toVar()" instead.' );
  3321. return createVar( node );
  3322. };
  3323. addMethodChaining( 'temp', temp );
  3324. /**
  3325. * Class for representing shader varyings as nodes. Varyings are create from
  3326. * existing nodes like the following:
  3327. *
  3328. * ```js
  3329. * const positionLocal = positionGeometry.varying( 'vPositionLocal' );
  3330. * ```
  3331. *
  3332. * @augments Node
  3333. */
  3334. class VaryingNode extends Node {
  3335. static get type() {
  3336. return 'VaryingNode';
  3337. }
  3338. /**
  3339. * Constructs a new varying node.
  3340. *
  3341. * @param {Node} node - The node for which a varying should be created.
  3342. * @param {String?} name - The name of the varying in the shader.
  3343. */
  3344. constructor( node, name = null ) {
  3345. super();
  3346. /**
  3347. * The node for which a varying should be created.
  3348. *
  3349. * @type {Node}
  3350. */
  3351. this.node = node;
  3352. /**
  3353. * The name of the varying in the shader. If no name is defined,
  3354. * the node system auto-generates one.
  3355. *
  3356. * @type {String?}
  3357. * @default null
  3358. */
  3359. this.name = name;
  3360. /**
  3361. * This flag can be used for type testing.
  3362. *
  3363. * @type {Boolean}
  3364. * @readonly
  3365. * @default true
  3366. */
  3367. this.isVaryingNode = true;
  3368. }
  3369. /**
  3370. * The method is overwritten so it always returns `true`.
  3371. *
  3372. * @param {NodeBuilder} builder - The current node builder.
  3373. * @return {Boolean} Whether this node is global or not.
  3374. */
  3375. isGlobal( /*builder*/ ) {
  3376. return true;
  3377. }
  3378. getHash( builder ) {
  3379. return this.name || super.getHash( builder );
  3380. }
  3381. getNodeType( builder ) {
  3382. // VaryingNode is auto type
  3383. return this.node.getNodeType( builder );
  3384. }
  3385. /**
  3386. * This method performs the setup of a varying node with the current node builder.
  3387. *
  3388. * @param {NodeBuilder} builder - The current node builder.
  3389. * @return {NodeVarying} The node varying from the node builder.
  3390. */
  3391. setupVarying( builder ) {
  3392. const properties = builder.getNodeProperties( this );
  3393. let varying = properties.varying;
  3394. if ( varying === undefined ) {
  3395. const name = this.name;
  3396. const type = this.getNodeType( builder );
  3397. properties.varying = varying = builder.getVaryingFromNode( this, name, type );
  3398. properties.node = this.node;
  3399. }
  3400. // this property can be used to check if the varying can be optimized for a variable
  3401. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  3402. return varying;
  3403. }
  3404. setup( builder ) {
  3405. this.setupVarying( builder );
  3406. }
  3407. analyze( builder ) {
  3408. this.setupVarying( builder );
  3409. return this.node.analyze( builder );
  3410. }
  3411. generate( builder ) {
  3412. const properties = builder.getNodeProperties( this );
  3413. const varying = this.setupVarying( builder );
  3414. if ( properties.propertyName === undefined ) {
  3415. const type = this.getNodeType( builder );
  3416. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  3417. // force node run in vertex stage
  3418. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node, type, propertyName );
  3419. properties.propertyName = propertyName;
  3420. }
  3421. return builder.getPropertyName( varying );
  3422. }
  3423. }
  3424. const varying = /*@__PURE__*/ nodeProxy( VaryingNode );
  3425. addMethodChaining( 'varying', varying );
  3426. /** @module ColorSpaceFunctions **/
  3427. /**
  3428. * Converts the given color value from sRGB to linear-sRGB color space.
  3429. *
  3430. * @method
  3431. * @param {vec3} color - The sRGB color.
  3432. * @return {vec3} The linear-sRGB color.
  3433. */
  3434. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  3435. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  3436. const b = color.mul( 0.0773993808 );
  3437. const factor = color.lessThanEqual( 0.04045 );
  3438. const rgbResult = mix( a, b, factor );
  3439. return rgbResult;
  3440. } ).setLayout( {
  3441. name: 'sRGBTransferEOTF',
  3442. type: 'vec3',
  3443. inputs: [
  3444. { name: 'color', type: 'vec3' }
  3445. ]
  3446. } );
  3447. /**
  3448. * Converts the given color value from linear-sRGB to sRGB color space.
  3449. *
  3450. * @method
  3451. * @param {vec3} color - The linear-sRGB color.
  3452. * @return {vec3} The sRGB color.
  3453. */
  3454. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  3455. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  3456. const b = color.mul( 12.92 );
  3457. const factor = color.lessThanEqual( 0.0031308 );
  3458. const rgbResult = mix( a, b, factor );
  3459. return rgbResult;
  3460. } ).setLayout( {
  3461. name: 'sRGBTransferOETF',
  3462. type: 'vec3',
  3463. inputs: [
  3464. { name: 'color', type: 'vec3' }
  3465. ]
  3466. } );
  3467. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  3468. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  3469. /**
  3470. * This node represents a color space conversion. Meaning it converts
  3471. * a color value from a source to a target color space.
  3472. *
  3473. * @augments TempNode
  3474. */
  3475. class ColorSpaceNode extends TempNode {
  3476. static get type() {
  3477. return 'ColorSpaceNode';
  3478. }
  3479. /**
  3480. * Constructs a new color space node.
  3481. *
  3482. * @param {Node} colorNode - Represents the color to convert.
  3483. * @param {String} source - The source color space.
  3484. * @param {String} target - The target color space.
  3485. */
  3486. constructor( colorNode, source, target ) {
  3487. super( 'vec4' );
  3488. /**
  3489. * Represents the color to convert.
  3490. *
  3491. * @type {Node}
  3492. */
  3493. this.colorNode = colorNode;
  3494. /**
  3495. * The source color space.
  3496. *
  3497. * @type {Node}
  3498. */
  3499. this.source = source;
  3500. /**
  3501. * The target color space.
  3502. *
  3503. * @type {Node}
  3504. */
  3505. this.target = target;
  3506. }
  3507. /**
  3508. * This method resolves the constants `WORKING_COLOR_SPACE` and
  3509. * `OUTPUT_COLOR_SPACE` based on the current configuration of the
  3510. * color management and renderer.
  3511. *
  3512. * @param {NodeBuilder} builder - The current node builder.
  3513. * @param {String} colorSpace - The color space to resolve.
  3514. * @return {String} The resolved color space.
  3515. */
  3516. resolveColorSpace( builder, colorSpace ) {
  3517. if ( colorSpace === WORKING_COLOR_SPACE ) {
  3518. return ColorManagement.workingColorSpace;
  3519. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  3520. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  3521. }
  3522. return colorSpace;
  3523. }
  3524. setup( builder ) {
  3525. const { colorNode } = this;
  3526. const source = this.resolveColorSpace( builder, this.source );
  3527. const target = this.resolveColorSpace( builder, this.target );
  3528. let outputNode = colorNode;
  3529. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  3530. return outputNode;
  3531. }
  3532. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  3533. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  3534. }
  3535. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  3536. outputNode = vec4(
  3537. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  3538. outputNode.a
  3539. );
  3540. }
  3541. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  3542. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  3543. }
  3544. return outputNode;
  3545. }
  3546. }
  3547. const toOutputColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, OUTPUT_COLOR_SPACE ) );
  3548. const toWorkingColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), OUTPUT_COLOR_SPACE, WORKING_COLOR_SPACE ) );
  3549. const workingToColorSpace = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, colorSpace ) );
  3550. const colorSpaceToWorking = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), colorSpace, WORKING_COLOR_SPACE ) );
  3551. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  3552. addMethodChaining( 'toOutputColorSpace', toOutputColorSpace );
  3553. addMethodChaining( 'toWorkingColorSpace', toWorkingColorSpace );
  3554. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  3555. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  3556. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  3557. static get type() {
  3558. return 'ReferenceElementNode';
  3559. }
  3560. constructor( referenceNode, indexNode ) {
  3561. super( referenceNode, indexNode );
  3562. this.referenceNode = referenceNode;
  3563. this.isReferenceElementNode = true;
  3564. }
  3565. getNodeType() {
  3566. return this.referenceNode.uniformType;
  3567. }
  3568. generate( builder ) {
  3569. const snippet = super.generate( builder );
  3570. const arrayType = this.referenceNode.getNodeType();
  3571. const elementType = this.getNodeType();
  3572. return builder.format( snippet, arrayType, elementType );
  3573. }
  3574. };
  3575. class ReferenceBaseNode extends Node {
  3576. static get type() {
  3577. return 'ReferenceBaseNode';
  3578. }
  3579. constructor( property, uniformType, object = null, count = null ) {
  3580. super();
  3581. this.property = property;
  3582. this.uniformType = uniformType;
  3583. this.object = object;
  3584. this.count = count;
  3585. this.properties = property.split( '.' );
  3586. this.reference = object;
  3587. this.node = null;
  3588. this.group = null;
  3589. this.updateType = NodeUpdateType.OBJECT;
  3590. }
  3591. setGroup( group ) {
  3592. this.group = group;
  3593. return this;
  3594. }
  3595. element( indexNode ) {
  3596. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  3597. }
  3598. setNodeType( uniformType ) {
  3599. const node = uniform( null, uniformType ).getSelf();
  3600. if ( this.group !== null ) {
  3601. node.setGroup( this.group );
  3602. }
  3603. this.node = node;
  3604. }
  3605. getNodeType( builder ) {
  3606. if ( this.node === null ) {
  3607. this.updateReference( builder );
  3608. this.updateValue();
  3609. }
  3610. return this.node.getNodeType( builder );
  3611. }
  3612. getValueFromReference( object = this.reference ) {
  3613. const { properties } = this;
  3614. let value = object[ properties[ 0 ] ];
  3615. for ( let i = 1; i < properties.length; i ++ ) {
  3616. value = value[ properties[ i ] ];
  3617. }
  3618. return value;
  3619. }
  3620. updateReference( state ) {
  3621. this.reference = this.object !== null ? this.object : state.object;
  3622. return this.reference;
  3623. }
  3624. setup() {
  3625. this.updateValue();
  3626. return this.node;
  3627. }
  3628. update( /*frame*/ ) {
  3629. this.updateValue();
  3630. }
  3631. updateValue() {
  3632. if ( this.node === null ) this.setNodeType( this.uniformType );
  3633. const value = this.getValueFromReference();
  3634. if ( Array.isArray( value ) ) {
  3635. this.node.array = value;
  3636. } else {
  3637. this.node.value = value;
  3638. }
  3639. }
  3640. }
  3641. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  3642. class RendererReferenceNode extends ReferenceBaseNode {
  3643. static get type() {
  3644. return 'RendererReferenceNode';
  3645. }
  3646. constructor( property, inputType, renderer = null ) {
  3647. super( property, inputType, renderer );
  3648. this.renderer = renderer;
  3649. this.setGroup( renderGroup );
  3650. }
  3651. updateReference( state ) {
  3652. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  3653. return this.reference;
  3654. }
  3655. }
  3656. const rendererReference = ( name, type, renderer ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  3657. /**
  3658. * This node represents a tone mapping operation.
  3659. *
  3660. * @augments TempNode
  3661. */
  3662. class ToneMappingNode extends TempNode {
  3663. static get type() {
  3664. return 'ToneMappingNode';
  3665. }
  3666. /**
  3667. * Constructs a new tone mapping node.
  3668. *
  3669. * @param {Number} toneMapping - The tone mapping type.
  3670. * @param {Node} exposureNode - The tone mapping exposure.
  3671. * @param {Node} [colorNode=null] - The color node to process.
  3672. */
  3673. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  3674. super( 'vec3' );
  3675. /**
  3676. * The tone mapping type.
  3677. *
  3678. * @type {Number}
  3679. */
  3680. this.toneMapping = toneMapping;
  3681. /**
  3682. * The tone mapping exposure.
  3683. *
  3684. * @type {Node}
  3685. * @default null
  3686. */
  3687. this.exposureNode = exposureNode;
  3688. /**
  3689. * Represents the color to process.
  3690. *
  3691. * @type {Node}
  3692. * @default null
  3693. */
  3694. this.colorNode = colorNode;
  3695. }
  3696. /**
  3697. * Overwrites the default `customCacheKey()` implementation by including the tone
  3698. * mapping type into the cache key.
  3699. *
  3700. * @return {Number} The hash.
  3701. */
  3702. customCacheKey() {
  3703. return hash$1( this.toneMapping );
  3704. }
  3705. setup( builder ) {
  3706. const colorNode = this.colorNode || builder.context.color;
  3707. const toneMapping = this.toneMapping;
  3708. if ( toneMapping === NoToneMapping ) return colorNode;
  3709. let outputNode = null;
  3710. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  3711. if ( toneMappingFn !== null ) {
  3712. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  3713. } else {
  3714. console.error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  3715. outputNode = colorNode;
  3716. }
  3717. return outputNode;
  3718. }
  3719. }
  3720. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  3721. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  3722. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  3723. class BufferAttributeNode extends InputNode {
  3724. static get type() {
  3725. return 'BufferAttributeNode';
  3726. }
  3727. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  3728. super( value, bufferType );
  3729. this.isBufferNode = true;
  3730. this.bufferType = bufferType;
  3731. this.bufferStride = bufferStride;
  3732. this.bufferOffset = bufferOffset;
  3733. this.usage = StaticDrawUsage;
  3734. this.instanced = false;
  3735. this.attribute = null;
  3736. this.global = true;
  3737. if ( value && value.isBufferAttribute === true ) {
  3738. this.attribute = value;
  3739. this.usage = value.usage;
  3740. this.instanced = value.isInstancedBufferAttribute;
  3741. }
  3742. }
  3743. getHash( builder ) {
  3744. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  3745. let bufferData = builder.globalCache.getData( this.value );
  3746. if ( bufferData === undefined ) {
  3747. bufferData = {
  3748. node: this
  3749. };
  3750. builder.globalCache.setData( this.value, bufferData );
  3751. }
  3752. return bufferData.node.uuid;
  3753. }
  3754. return this.uuid;
  3755. }
  3756. getNodeType( builder ) {
  3757. if ( this.bufferType === null ) {
  3758. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  3759. }
  3760. return this.bufferType;
  3761. }
  3762. setup( builder ) {
  3763. if ( this.attribute !== null ) return;
  3764. const type = this.getNodeType( builder );
  3765. const array = this.value;
  3766. const itemSize = builder.getTypeLength( type );
  3767. const stride = this.bufferStride || itemSize;
  3768. const offset = this.bufferOffset;
  3769. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  3770. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  3771. buffer.setUsage( this.usage );
  3772. this.attribute = bufferAttribute;
  3773. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  3774. }
  3775. generate( builder ) {
  3776. const nodeType = this.getNodeType( builder );
  3777. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  3778. const propertyName = builder.getPropertyName( nodeAttribute );
  3779. let output = null;
  3780. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  3781. this.name = propertyName;
  3782. output = propertyName;
  3783. } else {
  3784. const nodeVarying = varying( this );
  3785. output = nodeVarying.build( builder, nodeType );
  3786. }
  3787. return output;
  3788. }
  3789. getInputType( /*builder*/ ) {
  3790. return 'bufferAttribute';
  3791. }
  3792. setUsage( value ) {
  3793. this.usage = value;
  3794. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  3795. this.attribute.usage = value;
  3796. }
  3797. return this;
  3798. }
  3799. setInstanced( value ) {
  3800. this.instanced = value;
  3801. return this;
  3802. }
  3803. }
  3804. const bufferAttribute = ( array, type, stride, offset ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  3805. const dynamicBufferAttribute = ( array, type, stride, offset ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  3806. const instancedBufferAttribute = ( array, type, stride, offset ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  3807. const instancedDynamicBufferAttribute = ( array, type, stride, offset ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  3808. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  3809. class ComputeNode extends Node {
  3810. static get type() {
  3811. return 'ComputeNode';
  3812. }
  3813. constructor( computeNode, count, workgroupSize = [ 64 ] ) {
  3814. super( 'void' );
  3815. this.isComputeNode = true;
  3816. this.computeNode = computeNode;
  3817. this.count = count;
  3818. this.workgroupSize = workgroupSize;
  3819. this.dispatchCount = 0;
  3820. this.version = 1;
  3821. this.updateBeforeType = NodeUpdateType.OBJECT;
  3822. this.onInitFunction = null;
  3823. this.updateDispatchCount();
  3824. }
  3825. dispose() {
  3826. this.dispatchEvent( { type: 'dispose' } );
  3827. }
  3828. set needsUpdate( value ) {
  3829. if ( value === true ) this.version ++;
  3830. }
  3831. updateDispatchCount() {
  3832. const { count, workgroupSize } = this;
  3833. let size = workgroupSize[ 0 ];
  3834. for ( let i = 1; i < workgroupSize.length; i ++ )
  3835. size *= workgroupSize[ i ];
  3836. this.dispatchCount = Math.ceil( count / size );
  3837. }
  3838. onInit( callback ) {
  3839. this.onInitFunction = callback;
  3840. return this;
  3841. }
  3842. updateBefore( { renderer } ) {
  3843. renderer.compute( this );
  3844. }
  3845. generate( builder ) {
  3846. const { shaderStage } = builder;
  3847. if ( shaderStage === 'compute' ) {
  3848. const snippet = this.computeNode.build( builder, 'void' );
  3849. if ( snippet !== '' ) {
  3850. builder.addLineFlowCode( snippet, this );
  3851. }
  3852. }
  3853. }
  3854. }
  3855. const compute = ( node, count, workgroupSize ) => nodeObject( new ComputeNode( nodeObject( node ), count, workgroupSize ) );
  3856. addMethodChaining( 'compute', compute );
  3857. /**
  3858. * This node can be used as a cache management component for another node.
  3859. * Caching is in general used by default in {@link NodeBuilder} but this node
  3860. * allows the usage of a shared parent cache during the build process.
  3861. *
  3862. * @augments Node
  3863. */
  3864. class CacheNode extends Node {
  3865. static get type() {
  3866. return 'CacheNode';
  3867. }
  3868. /**
  3869. * Constructs a new cache node.
  3870. *
  3871. * @param {Node} node - The node that should be cached.
  3872. * @param {Boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  3873. */
  3874. constructor( node, parent = true ) {
  3875. super();
  3876. /**
  3877. * The node that should be cached.
  3878. *
  3879. * @type {Node}
  3880. */
  3881. this.node = node;
  3882. /**
  3883. * Whether this node refers to a shared parent cache or not.
  3884. *
  3885. * @type {Boolean}
  3886. * @default true
  3887. */
  3888. this.parent = parent;
  3889. /**
  3890. * This flag can be used for type testing.
  3891. *
  3892. * @type {Boolean}
  3893. * @readonly
  3894. * @default true
  3895. */
  3896. this.isCacheNode = true;
  3897. }
  3898. getNodeType( builder ) {
  3899. return this.node.getNodeType( builder );
  3900. }
  3901. build( builder, ...params ) {
  3902. const previousCache = builder.getCache();
  3903. const cache = builder.getCacheFromNode( this, this.parent );
  3904. builder.setCache( cache );
  3905. const data = this.node.build( builder, ...params );
  3906. builder.setCache( previousCache );
  3907. return data;
  3908. }
  3909. }
  3910. const cache = ( node, ...params ) => nodeObject( new CacheNode( nodeObject( node ), ...params ) );
  3911. addMethodChaining( 'cache', cache );
  3912. /**
  3913. * The class generates the code of a given node but returns another node in the output.
  3914. * This can be used to call a method or node that does not return a value, i.e.
  3915. * type `void` on an input where returning a value is required. Example:
  3916. *
  3917. * ```js
  3918. * material.colorNode = myColor.bypass( runVoidFn() )
  3919. *```
  3920. *
  3921. * @augments Node
  3922. */
  3923. class BypassNode extends Node {
  3924. static get type() {
  3925. return 'BypassNode';
  3926. }
  3927. /**
  3928. * Constructs a new bypass node.
  3929. *
  3930. * @param {Node} outputNode - The output node.
  3931. * @param {Node} callNode - The call node.
  3932. */
  3933. constructor( outputNode, callNode ) {
  3934. super();
  3935. /**
  3936. * This flag can be used for type testing.
  3937. *
  3938. * @type {Boolean}
  3939. * @readonly
  3940. * @default true
  3941. */
  3942. this.isBypassNode = true;
  3943. /**
  3944. * The output node.
  3945. *
  3946. * @type {Node}
  3947. */
  3948. this.outputNode = outputNode;
  3949. /**
  3950. * The call node.
  3951. *
  3952. * @type {Node}
  3953. */
  3954. this.callNode = callNode;
  3955. }
  3956. getNodeType( builder ) {
  3957. return this.outputNode.getNodeType( builder );
  3958. }
  3959. generate( builder ) {
  3960. const snippet = this.callNode.build( builder, 'void' );
  3961. if ( snippet !== '' ) {
  3962. builder.addLineFlowCode( snippet, this );
  3963. }
  3964. return this.outputNode.build( builder );
  3965. }
  3966. }
  3967. const bypass = /*@__PURE__*/ nodeProxy( BypassNode );
  3968. addMethodChaining( 'bypass', bypass );
  3969. /**
  3970. * This node allows to remap a node value from one range into another. E.g a value of
  3971. * `0.4` in the range `[ 0.3, 0.5 ]` should be remapped into the normalized range `[ 0, 1 ]`.
  3972. * `RemapNode` takes care of that and converts the original value of `0.4` to `0.5`.
  3973. *
  3974. * @augments Node
  3975. */
  3976. class RemapNode extends Node {
  3977. static get type() {
  3978. return 'RemapNode';
  3979. }
  3980. /**
  3981. * Constructs a new remap node.
  3982. *
  3983. * @param {Node} node - The node that should be remapped.
  3984. * @param {Node} inLowNode - The source or current lower bound of the range.
  3985. * @param {Node} inLowNode - The source or current upper bound of the range.
  3986. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  3987. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  3988. */
  3989. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  3990. super();
  3991. /**
  3992. * The node that should be remapped.
  3993. *
  3994. * @type {Node}
  3995. */
  3996. this.node = node;
  3997. /**
  3998. * The source or current lower bound of the range.
  3999. *
  4000. * @type {Node}
  4001. */
  4002. this.inLowNode = inLowNode;
  4003. /**
  4004. * The source or current upper bound of the range.
  4005. *
  4006. * @type {Node}
  4007. */
  4008. this.inHighNode = inHighNode;
  4009. /**
  4010. * The target lower bound of the range.
  4011. *
  4012. * @type {Node}
  4013. * @default float(0)
  4014. */
  4015. this.outLowNode = outLowNode;
  4016. /**
  4017. * The target upper bound of the range.
  4018. *
  4019. * @type {Node}
  4020. * @default float(1)
  4021. */
  4022. this.outHighNode = outHighNode;
  4023. /**
  4024. * Whether the node value should be clamped before
  4025. * remapping it to the target range.
  4026. *
  4027. * @type {Boolean}
  4028. * @default true
  4029. */
  4030. this.doClamp = true;
  4031. }
  4032. setup() {
  4033. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  4034. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  4035. if ( doClamp === true ) t = t.clamp();
  4036. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  4037. }
  4038. }
  4039. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } );
  4040. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode );
  4041. addMethodChaining( 'remap', remap );
  4042. addMethodChaining( 'remapClamp', remapClamp );
  4043. /**
  4044. * This class can be used to implement basic expressions in shader code.
  4045. * Basic examples for that are `return`, `continue` or `discard` statements.
  4046. *
  4047. * @augments Node
  4048. */
  4049. class ExpressionNode extends Node {
  4050. static get type() {
  4051. return 'ExpressionNode';
  4052. }
  4053. /**
  4054. * Constructs a new expression node.
  4055. *
  4056. * @param {String} [snippet=''] - The native code snippet.
  4057. * @param {String} [includes='void'] - The node type.
  4058. */
  4059. constructor( snippet = '', nodeType = 'void' ) {
  4060. super( nodeType );
  4061. /**
  4062. * The native code snippet.
  4063. *
  4064. * @type {String}
  4065. * @default ''
  4066. */
  4067. this.snippet = snippet;
  4068. }
  4069. generate( builder, output ) {
  4070. const type = this.getNodeType( builder );
  4071. const snippet = this.snippet;
  4072. if ( type === 'void' ) {
  4073. builder.addLineFlowCode( snippet, this );
  4074. } else {
  4075. return builder.format( `( ${ snippet } )`, type, output );
  4076. }
  4077. }
  4078. }
  4079. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode );
  4080. /** @module Discard **/
  4081. /**
  4082. * Represents a `discard` shader operation in TSL.
  4083. *
  4084. * @method
  4085. * @param {ConditionalNode?} conditional - An optional conditional node. It allows to decide whether the discard should be executed or not.
  4086. * @return {Node} The `discard` expression.
  4087. */
  4088. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).append();
  4089. /**
  4090. * Represents a `return` shader operation in TSL.
  4091. *
  4092. * @method
  4093. * @return {ExpressionNode} The `return` expression.
  4094. */
  4095. const Return = () => expression( 'return' ).append();
  4096. addMethodChaining( 'discard', Discard );
  4097. /**
  4098. * Normally, tone mapping and color conversion happens automatically
  4099. * before outputting pixel too the default (screen) framebuffer. In certain
  4100. * post processing setups this happens to late because certain effects
  4101. * require e.g. sRGB input. For such scenarios, `RenderOutputNode` can be used
  4102. * to apply tone mapping and color space conversion at an arbitrary point
  4103. * in the effect chain.
  4104. *
  4105. * When applying tone mapping and color space conversion manually with this node,
  4106. * you have to set {@link PostProcessing#outputColorTransform} to `false`.
  4107. *
  4108. * ```js
  4109. * const postProcessing = new PostProcessing( renderer );
  4110. * postProcessing.outputColorTransform = false;
  4111. *
  4112. * const scenePass = pass( scene, camera );
  4113. * const outputPass = renderOutput( scenePass );
  4114. *
  4115. * postProcessing.outputNode = outputPass;
  4116. * ```
  4117. *
  4118. * @augments TempNode
  4119. */
  4120. class RenderOutputNode extends TempNode {
  4121. static get type() {
  4122. return 'RenderOutputNode';
  4123. }
  4124. /**
  4125. * Constructs a new render output node.
  4126. *
  4127. * @param {Node} colorNode - The color node to process.
  4128. * @param {String} toneMapping - The tone mapping type.
  4129. * @param {String} outputColorSpace - The output color space.
  4130. */
  4131. constructor( colorNode, toneMapping, outputColorSpace ) {
  4132. super( 'vec4' );
  4133. /**
  4134. * The color node to process.
  4135. *
  4136. * @type {Node}
  4137. */
  4138. this.colorNode = colorNode;
  4139. /**
  4140. * The tone mapping type.
  4141. *
  4142. * @type {Number?}
  4143. */
  4144. this.toneMapping = toneMapping;
  4145. /**
  4146. * The output color space.
  4147. *
  4148. * @type {String?}
  4149. */
  4150. this.outputColorSpace = outputColorSpace;
  4151. /**
  4152. * This flag can be used for type testing.
  4153. *
  4154. * @type {Boolean}
  4155. * @readonly
  4156. * @default true
  4157. */
  4158. this.isRenderOutputNode = true;
  4159. }
  4160. setup( { context } ) {
  4161. let outputNode = this.colorNode || context.color;
  4162. // tone mapping
  4163. const toneMapping = ( this.toneMapping !== null ? this.toneMapping : context.toneMapping ) || NoToneMapping;
  4164. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  4165. if ( toneMapping !== NoToneMapping ) {
  4166. outputNode = outputNode.toneMapping( toneMapping );
  4167. }
  4168. // working to output color space
  4169. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  4170. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  4171. }
  4172. return outputNode;
  4173. }
  4174. }
  4175. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  4176. addMethodChaining( 'renderOutput', renderOutput );
  4177. // Non-PURE exports list, side-effects are required here.
  4178. // TSL Base Syntax
  4179. function addNodeElement( name/*, nodeElement*/ ) {
  4180. console.warn( 'THREE.TSLBase: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  4181. }
  4182. /**
  4183. * Base class for representing shader attributes as nodes.
  4184. *
  4185. * @augments Node
  4186. */
  4187. class AttributeNode extends Node {
  4188. static get type() {
  4189. return 'AttributeNode';
  4190. }
  4191. /**
  4192. * Constructs a new attribute node.
  4193. *
  4194. * @param {String} attributeName - The name of the attribute.
  4195. * @param {String?} nodeType - The node type.
  4196. */
  4197. constructor( attributeName, nodeType = null ) {
  4198. super( nodeType );
  4199. /**
  4200. * `AttributeNode` sets this property to `true` by default.
  4201. *
  4202. * @type {Boolean}
  4203. * @default true
  4204. */
  4205. this.global = true;
  4206. this._attributeName = attributeName;
  4207. }
  4208. getHash( builder ) {
  4209. return this.getAttributeName( builder );
  4210. }
  4211. getNodeType( builder ) {
  4212. let nodeType = this.nodeType;
  4213. if ( nodeType === null ) {
  4214. const attributeName = this.getAttributeName( builder );
  4215. if ( builder.hasGeometryAttribute( attributeName ) ) {
  4216. const attribute = builder.geometry.getAttribute( attributeName );
  4217. nodeType = builder.getTypeFromAttribute( attribute );
  4218. } else {
  4219. nodeType = 'float';
  4220. }
  4221. }
  4222. return nodeType;
  4223. }
  4224. /**
  4225. * Sets the attribute name to the given value. The method can be
  4226. * overwritten in derived classes if the final name must be computed
  4227. * analytically.
  4228. *
  4229. * @param {String} attributeName - The name of the attribute.
  4230. * @return {AttributeNode} A reference to this node.
  4231. */
  4232. setAttributeName( attributeName ) {
  4233. this._attributeName = attributeName;
  4234. return this;
  4235. }
  4236. /**
  4237. * Returns the attribute name of this node. The method can be
  4238. * overwritten in derived classes if the final name must be computed
  4239. * analytically.
  4240. *
  4241. * @param {NodeBuilder} builder - The current node builder.
  4242. * @return {String} The attribute name.
  4243. */
  4244. getAttributeName( /*builder*/ ) {
  4245. return this._attributeName;
  4246. }
  4247. generate( builder ) {
  4248. const attributeName = this.getAttributeName( builder );
  4249. const nodeType = this.getNodeType( builder );
  4250. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  4251. if ( geometryAttribute === true ) {
  4252. const attribute = builder.geometry.getAttribute( attributeName );
  4253. const attributeType = builder.getTypeFromAttribute( attribute );
  4254. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  4255. if ( builder.shaderStage === 'vertex' ) {
  4256. return builder.format( nodeAttribute.name, attributeType, nodeType );
  4257. } else {
  4258. const nodeVarying = varying( this );
  4259. return nodeVarying.build( builder, nodeType );
  4260. }
  4261. } else {
  4262. console.warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  4263. return builder.generateConst( nodeType );
  4264. }
  4265. }
  4266. serialize( data ) {
  4267. super.serialize( data );
  4268. data.global = this.global;
  4269. data._attributeName = this._attributeName;
  4270. }
  4271. deserialize( data ) {
  4272. super.deserialize( data );
  4273. this.global = data.global;
  4274. this._attributeName = data._attributeName;
  4275. }
  4276. }
  4277. const attribute = ( name, nodeType ) => nodeObject( new AttributeNode( name, nodeType ) );
  4278. const uv = ( index ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  4279. class TextureSizeNode extends Node {
  4280. static get type() {
  4281. return 'TextureSizeNode';
  4282. }
  4283. constructor( textureNode, levelNode = null ) {
  4284. super( 'uvec2' );
  4285. this.isTextureSizeNode = true;
  4286. this.textureNode = textureNode;
  4287. this.levelNode = levelNode;
  4288. }
  4289. generate( builder, output ) {
  4290. const textureProperty = this.textureNode.build( builder, 'property' );
  4291. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  4292. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  4293. }
  4294. }
  4295. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode );
  4296. /**
  4297. * A special type of uniform node that computes the
  4298. * maximum mipmap level for a given texture node.
  4299. *
  4300. * ```js
  4301. * const level = maxMipLevel( textureNode );
  4302. * ```
  4303. *
  4304. * @augments UniformNode
  4305. */
  4306. class MaxMipLevelNode extends UniformNode {
  4307. static get type() {
  4308. return 'MaxMipLevelNode';
  4309. }
  4310. /**
  4311. * Constructs a new max mip level node.
  4312. *
  4313. * @param {TextureNode} node - The texture node to compute the max mip level for.
  4314. */
  4315. constructor( textureNode ) {
  4316. super( 0 );
  4317. /**
  4318. * The texture node to compute the max mip level for.
  4319. *
  4320. * @private
  4321. * @type {TextureNode}
  4322. */
  4323. this._textureNode = textureNode;
  4324. /**
  4325. * The `updateType` is set to `NodeUpdateType.FRAME` since the node updates
  4326. * the texture once per frame in its {@link MaxMipLevelNode#update} method.
  4327. *
  4328. * @type {String}
  4329. * @default 'frame'
  4330. */
  4331. this.updateType = NodeUpdateType.FRAME;
  4332. }
  4333. /**
  4334. * The texture node to compute the max mip level for.
  4335. *
  4336. * @readonly
  4337. * @type {TextureNode}
  4338. */
  4339. get textureNode() {
  4340. return this._textureNode;
  4341. }
  4342. /**
  4343. * The texture.
  4344. *
  4345. * @readonly
  4346. * @type {Texture}
  4347. */
  4348. get texture() {
  4349. return this._textureNode.value;
  4350. }
  4351. update() {
  4352. const texture = this.texture;
  4353. const images = texture.images;
  4354. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  4355. if ( image && image.width !== undefined ) {
  4356. const { width, height } = image;
  4357. this.value = Math.log2( Math.max( width, height ) );
  4358. }
  4359. }
  4360. }
  4361. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode );
  4362. class TextureNode extends UniformNode {
  4363. static get type() {
  4364. return 'TextureNode';
  4365. }
  4366. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  4367. super( value );
  4368. this.isTextureNode = true;
  4369. this.uvNode = uvNode;
  4370. this.levelNode = levelNode;
  4371. this.biasNode = biasNode;
  4372. this.compareNode = null;
  4373. this.depthNode = null;
  4374. this.gradNode = null;
  4375. this.sampler = true;
  4376. this.updateMatrix = false;
  4377. this.updateType = NodeUpdateType.NONE;
  4378. this.referenceNode = null;
  4379. this._value = value;
  4380. this._matrixUniform = null;
  4381. this.setUpdateMatrix( uvNode === null );
  4382. }
  4383. set value( value ) {
  4384. if ( this.referenceNode ) {
  4385. this.referenceNode.value = value;
  4386. } else {
  4387. this._value = value;
  4388. }
  4389. }
  4390. get value() {
  4391. return this.referenceNode ? this.referenceNode.value : this._value;
  4392. }
  4393. getUniformHash( /*builder*/ ) {
  4394. return this.value.uuid;
  4395. }
  4396. getNodeType( /*builder*/ ) {
  4397. if ( this.value.isDepthTexture === true ) return 'float';
  4398. if ( this.value.type === UnsignedIntType ) {
  4399. return 'uvec4';
  4400. } else if ( this.value.type === IntType ) {
  4401. return 'ivec4';
  4402. }
  4403. return 'vec4';
  4404. }
  4405. getInputType( /*builder*/ ) {
  4406. return 'texture';
  4407. }
  4408. getDefaultUV() {
  4409. return uv( this.value.channel );
  4410. }
  4411. updateReference( /*state*/ ) {
  4412. return this.value;
  4413. }
  4414. getTransformedUV( uvNode ) {
  4415. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  4416. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  4417. }
  4418. setUpdateMatrix( value ) {
  4419. this.updateMatrix = value;
  4420. this.updateType = value ? NodeUpdateType.FRAME : NodeUpdateType.NONE;
  4421. return this;
  4422. }
  4423. setupUV( builder, uvNode ) {
  4424. const texture = this.value;
  4425. if ( builder.isFlipY() && ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true ) ) {
  4426. if ( this.sampler ) {
  4427. uvNode = uvNode.flipY();
  4428. } else {
  4429. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  4430. }
  4431. }
  4432. return uvNode;
  4433. }
  4434. setup( builder ) {
  4435. const properties = builder.getNodeProperties( this );
  4436. properties.referenceNode = this.referenceNode;
  4437. //
  4438. let uvNode = this.uvNode;
  4439. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  4440. uvNode = builder.context.getUV( this );
  4441. }
  4442. if ( ! uvNode ) uvNode = this.getDefaultUV();
  4443. if ( this.updateMatrix === true ) {
  4444. uvNode = this.getTransformedUV( uvNode );
  4445. }
  4446. uvNode = this.setupUV( builder, uvNode );
  4447. //
  4448. let levelNode = this.levelNode;
  4449. if ( levelNode === null && builder.context.getTextureLevel ) {
  4450. levelNode = builder.context.getTextureLevel( this );
  4451. }
  4452. //
  4453. properties.uvNode = uvNode;
  4454. properties.levelNode = levelNode;
  4455. properties.biasNode = this.biasNode;
  4456. properties.compareNode = this.compareNode;
  4457. properties.gradNode = this.gradNode;
  4458. properties.depthNode = this.depthNode;
  4459. }
  4460. generateUV( builder, uvNode ) {
  4461. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  4462. }
  4463. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet ) {
  4464. const texture = this.value;
  4465. let snippet;
  4466. if ( levelSnippet ) {
  4467. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  4468. } else if ( biasSnippet ) {
  4469. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet );
  4470. } else if ( gradSnippet ) {
  4471. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet );
  4472. } else if ( compareSnippet ) {
  4473. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet );
  4474. } else if ( this.sampler === false ) {
  4475. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, depthSnippet );
  4476. } else {
  4477. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet );
  4478. }
  4479. return snippet;
  4480. }
  4481. generate( builder, output ) {
  4482. const properties = builder.getNodeProperties( this );
  4483. const texture = this.value;
  4484. if ( ! texture || texture.isTexture !== true ) {
  4485. throw new Error( 'TextureNode: Need a three.js texture.' );
  4486. }
  4487. const textureProperty = super.generate( builder, 'property' );
  4488. if ( output === 'sampler' ) {
  4489. return textureProperty + '_sampler';
  4490. } else if ( builder.isReference( output ) ) {
  4491. return textureProperty;
  4492. } else {
  4493. const nodeData = builder.getDataFromNode( this );
  4494. let propertyName = nodeData.propertyName;
  4495. if ( propertyName === undefined ) {
  4496. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode } = properties;
  4497. const uvSnippet = this.generateUV( builder, uvNode );
  4498. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  4499. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  4500. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  4501. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  4502. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  4503. const nodeVar = builder.getVarFromNode( this );
  4504. propertyName = builder.getPropertyName( nodeVar );
  4505. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet );
  4506. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  4507. nodeData.snippet = snippet;
  4508. nodeData.propertyName = propertyName;
  4509. }
  4510. let snippet = propertyName;
  4511. const nodeType = this.getNodeType( builder );
  4512. if ( builder.needsToWorkingColorSpace( texture ) ) {
  4513. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  4514. }
  4515. return builder.format( snippet, nodeType, output );
  4516. }
  4517. }
  4518. setSampler( value ) {
  4519. this.sampler = value;
  4520. return this;
  4521. }
  4522. getSampler() {
  4523. return this.sampler;
  4524. }
  4525. // @TODO: Move to TSL
  4526. uv( uvNode ) { // @deprecated, r172
  4527. console.warn( 'THREE.TextureNode: .uv() has been renamed. Use .sample() instead.' );
  4528. return this.sample( uvNode );
  4529. }
  4530. sample( uvNode ) {
  4531. const textureNode = this.clone();
  4532. textureNode.uvNode = nodeObject( uvNode );
  4533. textureNode.referenceNode = this.getSelf();
  4534. return nodeObject( textureNode );
  4535. }
  4536. blur( amountNode ) {
  4537. const textureNode = this.clone();
  4538. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  4539. textureNode.referenceNode = this.getSelf();
  4540. return nodeObject( textureNode );
  4541. }
  4542. level( levelNode ) {
  4543. const textureNode = this.clone();
  4544. textureNode.levelNode = nodeObject( levelNode );
  4545. textureNode.referenceNode = this.getSelf();
  4546. return nodeObject( textureNode );
  4547. }
  4548. size( levelNode ) {
  4549. return textureSize( this, levelNode );
  4550. }
  4551. bias( biasNode ) {
  4552. const textureNode = this.clone();
  4553. textureNode.biasNode = nodeObject( biasNode );
  4554. textureNode.referenceNode = this.getSelf();
  4555. return nodeObject( textureNode );
  4556. }
  4557. compare( compareNode ) {
  4558. const textureNode = this.clone();
  4559. textureNode.compareNode = nodeObject( compareNode );
  4560. textureNode.referenceNode = this.getSelf();
  4561. return nodeObject( textureNode );
  4562. }
  4563. grad( gradNodeX, gradNodeY ) {
  4564. const textureNode = this.clone();
  4565. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  4566. textureNode.referenceNode = this.getSelf();
  4567. return nodeObject( textureNode );
  4568. }
  4569. depth( depthNode ) {
  4570. const textureNode = this.clone();
  4571. textureNode.depthNode = nodeObject( depthNode );
  4572. textureNode.referenceNode = this.getSelf();
  4573. return nodeObject( textureNode );
  4574. }
  4575. // --
  4576. serialize( data ) {
  4577. super.serialize( data );
  4578. data.value = this.value.toJSON( data.meta ).uuid;
  4579. data.sampler = this.sampler;
  4580. data.updateMatrix = this.updateMatrix;
  4581. data.updateType = this.updateType;
  4582. }
  4583. deserialize( data ) {
  4584. super.deserialize( data );
  4585. this.value = data.meta.textures[ data.value ];
  4586. this.sampler = data.sampler;
  4587. this.updateMatrix = data.updateMatrix;
  4588. this.updateType = data.updateType;
  4589. }
  4590. update() {
  4591. const texture = this.value;
  4592. const matrixUniform = this._matrixUniform;
  4593. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  4594. if ( texture.matrixAutoUpdate === true ) {
  4595. texture.updateMatrix();
  4596. }
  4597. }
  4598. clone() {
  4599. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  4600. newNode.sampler = this.sampler;
  4601. return newNode;
  4602. }
  4603. }
  4604. const texture = /*@__PURE__*/ nodeProxy( TextureNode );
  4605. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  4606. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  4607. const sampler = ( aTexture ) => ( aTexture.isNode === true ? aTexture : texture( aTexture ) ).convert( 'sampler' );
  4608. const cameraNear = /*@__PURE__*/ uniform( 'float' ).label( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  4609. const cameraFar = /*@__PURE__*/ uniform( 'float' ).label( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  4610. const cameraProjectionMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  4611. const cameraProjectionMatrixInverse = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  4612. const cameraViewMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  4613. const cameraWorldMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  4614. const cameraNormalMatrix = /*@__PURE__*/ uniform( 'mat3' ).label( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  4615. const cameraPosition = /*@__PURE__*/ uniform( new Vector3() ).label( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  4616. class Object3DNode extends Node {
  4617. static get type() {
  4618. return 'Object3DNode';
  4619. }
  4620. constructor( scope, object3d = null ) {
  4621. super();
  4622. this.scope = scope;
  4623. this.object3d = object3d;
  4624. this.updateType = NodeUpdateType.OBJECT;
  4625. this._uniformNode = new UniformNode( null );
  4626. }
  4627. getNodeType() {
  4628. const scope = this.scope;
  4629. if ( scope === Object3DNode.WORLD_MATRIX ) {
  4630. return 'mat4';
  4631. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  4632. return 'vec3';
  4633. }
  4634. }
  4635. update( frame ) {
  4636. const object = this.object3d;
  4637. const uniformNode = this._uniformNode;
  4638. const scope = this.scope;
  4639. if ( scope === Object3DNode.WORLD_MATRIX ) {
  4640. uniformNode.value = object.matrixWorld;
  4641. } else if ( scope === Object3DNode.POSITION ) {
  4642. uniformNode.value = uniformNode.value || new Vector3();
  4643. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  4644. } else if ( scope === Object3DNode.SCALE ) {
  4645. uniformNode.value = uniformNode.value || new Vector3();
  4646. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  4647. } else if ( scope === Object3DNode.DIRECTION ) {
  4648. uniformNode.value = uniformNode.value || new Vector3();
  4649. object.getWorldDirection( uniformNode.value );
  4650. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  4651. const camera = frame.camera;
  4652. uniformNode.value = uniformNode.value || new Vector3();
  4653. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  4654. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  4655. }
  4656. }
  4657. generate( builder ) {
  4658. const scope = this.scope;
  4659. if ( scope === Object3DNode.WORLD_MATRIX ) {
  4660. this._uniformNode.nodeType = 'mat4';
  4661. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  4662. this._uniformNode.nodeType = 'vec3';
  4663. }
  4664. return this._uniformNode.build( builder );
  4665. }
  4666. serialize( data ) {
  4667. super.serialize( data );
  4668. data.scope = this.scope;
  4669. }
  4670. deserialize( data ) {
  4671. super.deserialize( data );
  4672. this.scope = data.scope;
  4673. }
  4674. }
  4675. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  4676. Object3DNode.POSITION = 'position';
  4677. Object3DNode.SCALE = 'scale';
  4678. Object3DNode.VIEW_POSITION = 'viewPosition';
  4679. Object3DNode.DIRECTION = 'direction';
  4680. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION );
  4681. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX );
  4682. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION );
  4683. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE );
  4684. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION );
  4685. class ModelNode extends Object3DNode {
  4686. static get type() {
  4687. return 'ModelNode';
  4688. }
  4689. constructor( scope ) {
  4690. super( scope );
  4691. }
  4692. update( frame ) {
  4693. this.object3d = frame.object;
  4694. super.update( frame );
  4695. }
  4696. }
  4697. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  4698. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  4699. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  4700. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  4701. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  4702. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  4703. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  4704. const modelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix ).toVar( 'modelViewMatrix' );
  4705. const highPrecisionModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  4706. builder.context.isHighPrecisionModelViewMatrix = true;
  4707. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  4708. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  4709. } );
  4710. } ).once() )().toVar( 'highPrecisionModelViewMatrix' );
  4711. const highPrecisionModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  4712. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  4713. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  4714. if ( isHighPrecisionModelViewMatrix !== true ) {
  4715. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  4716. }
  4717. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  4718. } );
  4719. } ).once() )().toVar( 'highPrecisionModelNormalMatrix' );
  4720. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  4721. const positionLocal = /*@__PURE__*/ positionGeometry.varying( 'positionLocal' );
  4722. const positionPrevious = /*@__PURE__*/ positionGeometry.varying( 'positionPrevious' );
  4723. const positionWorld = /*@__PURE__*/ modelWorldMatrix.mul( positionLocal ).xyz.varying( 'v_positionWorld' );
  4724. const positionWorldDirection = /*@__PURE__*/ positionLocal.transformDirection( modelWorldMatrix ).varying( 'v_positionWorldDirection' ).normalize().toVar( 'positionWorldDirection' );
  4725. const positionView = /*@__PURE__*/ modelViewMatrix.mul( positionLocal ).xyz.varying( 'v_positionView' );
  4726. const positionViewDirection = /*@__PURE__*/ positionView.negate().varying( 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  4727. /**
  4728. * This node can be used to evaluate whether a primitive is front or back facing.
  4729. *
  4730. * @augments Node
  4731. */
  4732. class FrontFacingNode extends Node {
  4733. static get type() {
  4734. return 'FrontFacingNode';
  4735. }
  4736. /**
  4737. * Constructs a new front facing node.
  4738. */
  4739. constructor() {
  4740. super( 'bool' );
  4741. /**
  4742. * This flag can be used for type testing.
  4743. *
  4744. * @type {Boolean}
  4745. * @readonly
  4746. * @default true
  4747. */
  4748. this.isFrontFacingNode = true;
  4749. }
  4750. generate( builder ) {
  4751. const { renderer, material } = builder;
  4752. if ( renderer.coordinateSystem === WebGLCoordinateSystem ) {
  4753. if ( material.side === BackSide ) {
  4754. return 'false';
  4755. }
  4756. }
  4757. return builder.getFrontFacing();
  4758. }
  4759. }
  4760. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  4761. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  4762. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  4763. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  4764. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  4765. console.warn( 'TSL.NormalNode: Vertex attribute "normal" not found on geometry.' );
  4766. return vec3( 0, 1, 0 );
  4767. }
  4768. return normalGeometry;
  4769. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  4770. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  4771. const normalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  4772. let node;
  4773. if ( builder.material.flatShading === true ) {
  4774. node = normalFlat;
  4775. } else {
  4776. node = varying( transformNormalToView( normalLocal ), 'v_normalView' ).normalize();
  4777. }
  4778. return node;
  4779. }, 'vec3' ).once() )().toVar( 'normalView' );
  4780. const normalWorld = /*@__PURE__*/ varying( normalView.transformDirection( cameraViewMatrix ), 'v_normalWorld' ).normalize().toVar( 'normalWorld' );
  4781. const transformedNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  4782. return builder.context.setupNormal();
  4783. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedNormalView' );
  4784. const transformedNormalWorld = /*@__PURE__*/ transformedNormalView.transformDirection( cameraViewMatrix ).toVar( 'transformedNormalWorld' );
  4785. const transformedClearcoatNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  4786. return builder.context.setupClearcoatNormal();
  4787. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedClearcoatNormalView' );
  4788. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  4789. const m = mat3( matrix );
  4790. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  4791. return m.mul( transformedNormal ).xyz;
  4792. } );
  4793. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  4794. const modelNormalViewMatrix = builder.renderer.nodes.modelNormalViewMatrix;
  4795. if ( modelNormalViewMatrix !== null ) {
  4796. return modelNormalViewMatrix.transformDirection( normal );
  4797. }
  4798. //
  4799. const transformedNormal = modelNormalMatrix.mul( normal );
  4800. return cameraViewMatrix.transformDirection( transformedNormal );
  4801. } );
  4802. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onRenderUpdate( ( { material } ) => material.refractionRatio );
  4803. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( transformedNormalView );
  4804. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( transformedNormalView, materialRefractionRatio );
  4805. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  4806. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  4807. class CubeTextureNode extends TextureNode {
  4808. static get type() {
  4809. return 'CubeTextureNode';
  4810. }
  4811. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  4812. super( value, uvNode, levelNode, biasNode );
  4813. this.isCubeTextureNode = true;
  4814. }
  4815. getInputType( /*builder*/ ) {
  4816. return 'cubeTexture';
  4817. }
  4818. getDefaultUV() {
  4819. const texture = this.value;
  4820. if ( texture.mapping === CubeReflectionMapping ) {
  4821. return reflectVector;
  4822. } else if ( texture.mapping === CubeRefractionMapping ) {
  4823. return refractVector;
  4824. } else {
  4825. console.error( 'THREE.CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  4826. return vec3( 0, 0, 0 );
  4827. }
  4828. }
  4829. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  4830. setupUV( builder, uvNode ) {
  4831. const texture = this.value;
  4832. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  4833. return vec3( uvNode.x.negate(), uvNode.yz );
  4834. } else {
  4835. return uvNode;
  4836. }
  4837. }
  4838. generateUV( builder, cubeUV ) {
  4839. return cubeUV.build( builder, 'vec3' );
  4840. }
  4841. }
  4842. const cubeTexture = /*@__PURE__*/ nodeProxy( CubeTextureNode );
  4843. class BufferNode extends UniformNode {
  4844. static get type() {
  4845. return 'BufferNode';
  4846. }
  4847. constructor( value, bufferType, bufferCount = 0 ) {
  4848. super( value, bufferType );
  4849. this.isBufferNode = true;
  4850. this.bufferType = bufferType;
  4851. this.bufferCount = bufferCount;
  4852. }
  4853. getElementType( builder ) {
  4854. return this.getNodeType( builder );
  4855. }
  4856. getInputType( /*builder*/ ) {
  4857. return 'buffer';
  4858. }
  4859. }
  4860. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  4861. class UniformArrayElementNode extends ArrayElementNode {
  4862. static get type() {
  4863. return 'UniformArrayElementNode';
  4864. }
  4865. constructor( arrayBuffer, indexNode ) {
  4866. super( arrayBuffer, indexNode );
  4867. this.isArrayBufferElementNode = true;
  4868. }
  4869. generate( builder ) {
  4870. const snippet = super.generate( builder );
  4871. const type = this.getNodeType();
  4872. const paddedType = this.node.getPaddedType();
  4873. return builder.format( snippet, paddedType, type );
  4874. }
  4875. }
  4876. class UniformArrayNode extends BufferNode {
  4877. static get type() {
  4878. return 'UniformArrayNode';
  4879. }
  4880. constructor( value, elementType = null ) {
  4881. super( null );
  4882. this.array = value;
  4883. this.elementType = elementType === null ? getValueType( value[ 0 ] ) : elementType;
  4884. this.paddedType = this.getPaddedType();
  4885. this.updateType = NodeUpdateType.RENDER;
  4886. this.isArrayBufferNode = true;
  4887. }
  4888. getNodeType() {
  4889. return this.paddedType;
  4890. }
  4891. getElementType() {
  4892. return this.elementType;
  4893. }
  4894. getPaddedType() {
  4895. const elementType = this.elementType;
  4896. let paddedType = 'vec4';
  4897. if ( elementType === 'mat2' ) {
  4898. paddedType = 'mat2';
  4899. } else if ( /mat/.test( elementType ) === true ) {
  4900. paddedType = 'mat4';
  4901. } else if ( elementType.charAt( 0 ) === 'i' ) {
  4902. paddedType = 'ivec4';
  4903. } else if ( elementType.charAt( 0 ) === 'u' ) {
  4904. paddedType = 'uvec4';
  4905. }
  4906. return paddedType;
  4907. }
  4908. update( /*frame*/ ) {
  4909. const { array, value } = this;
  4910. const elementType = this.elementType;
  4911. if ( elementType === 'float' || elementType === 'int' || elementType === 'uint' ) {
  4912. for ( let i = 0; i < array.length; i ++ ) {
  4913. const index = i * 4;
  4914. value[ index ] = array[ i ];
  4915. }
  4916. } else if ( elementType === 'color' ) {
  4917. for ( let i = 0; i < array.length; i ++ ) {
  4918. const index = i * 4;
  4919. const vector = array[ i ];
  4920. value[ index ] = vector.r;
  4921. value[ index + 1 ] = vector.g;
  4922. value[ index + 2 ] = vector.b || 0;
  4923. //value[ index + 3 ] = vector.a || 0;
  4924. }
  4925. } else if ( elementType === 'mat2' ) {
  4926. for ( let i = 0; i < array.length; i ++ ) {
  4927. const index = i * 4;
  4928. const matrix = array[ i ];
  4929. value[ index ] = matrix.elements[ 0 ];
  4930. value[ index + 1 ] = matrix.elements[ 1 ];
  4931. value[ index + 2 ] = matrix.elements[ 2 ];
  4932. value[ index + 3 ] = matrix.elements[ 3 ];
  4933. }
  4934. } else if ( elementType === 'mat3' ) {
  4935. for ( let i = 0; i < array.length; i ++ ) {
  4936. const index = i * 16;
  4937. const matrix = array[ i ];
  4938. value[ index ] = matrix.elements[ 0 ];
  4939. value[ index + 1 ] = matrix.elements[ 1 ];
  4940. value[ index + 2 ] = matrix.elements[ 2 ];
  4941. value[ index + 4 ] = matrix.elements[ 3 ];
  4942. value[ index + 5 ] = matrix.elements[ 4 ];
  4943. value[ index + 6 ] = matrix.elements[ 5 ];
  4944. value[ index + 8 ] = matrix.elements[ 6 ];
  4945. value[ index + 9 ] = matrix.elements[ 7 ];
  4946. value[ index + 10 ] = matrix.elements[ 8 ];
  4947. value[ index + 15 ] = 1;
  4948. }
  4949. } else if ( elementType === 'mat4' ) {
  4950. for ( let i = 0; i < array.length; i ++ ) {
  4951. const index = i * 16;
  4952. const matrix = array[ i ];
  4953. for ( let i = 0; i < matrix.elements.length; i ++ ) {
  4954. value[ index + i ] = matrix.elements[ i ];
  4955. }
  4956. }
  4957. } else {
  4958. for ( let i = 0; i < array.length; i ++ ) {
  4959. const index = i * 4;
  4960. const vector = array[ i ];
  4961. value[ index ] = vector.x;
  4962. value[ index + 1 ] = vector.y;
  4963. value[ index + 2 ] = vector.z || 0;
  4964. value[ index + 3 ] = vector.w || 0;
  4965. }
  4966. }
  4967. }
  4968. setup( builder ) {
  4969. const length = this.array.length;
  4970. const elementType = this.elementType;
  4971. let arrayType = Float32Array;
  4972. const paddedType = this.paddedType;
  4973. const paddedElementLength = builder.getTypeLength( paddedType );
  4974. if ( elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  4975. if ( elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  4976. this.value = new arrayType( length * paddedElementLength );
  4977. this.bufferCount = length;
  4978. this.bufferType = paddedType;
  4979. return super.setup( builder );
  4980. }
  4981. element( indexNode ) {
  4982. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  4983. }
  4984. }
  4985. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  4986. //
  4987. const uniforms = ( values, nodeType ) => { // @deprecated, r168
  4988. console.warn( 'TSL.UniformArrayNode: uniforms() has been renamed to uniformArray().' );
  4989. return nodeObject( new UniformArrayNode( values, nodeType ) );
  4990. };
  4991. class ReferenceElementNode extends ArrayElementNode {
  4992. static get type() {
  4993. return 'ReferenceElementNode';
  4994. }
  4995. constructor( referenceNode, indexNode ) {
  4996. super( referenceNode, indexNode );
  4997. this.referenceNode = referenceNode;
  4998. this.isReferenceElementNode = true;
  4999. }
  5000. getNodeType() {
  5001. return this.referenceNode.uniformType;
  5002. }
  5003. generate( builder ) {
  5004. const snippet = super.generate( builder );
  5005. const arrayType = this.referenceNode.getNodeType();
  5006. const elementType = this.getNodeType();
  5007. return builder.format( snippet, arrayType, elementType );
  5008. }
  5009. }
  5010. // TODO: Extends this from ReferenceBaseNode
  5011. class ReferenceNode extends Node {
  5012. static get type() {
  5013. return 'ReferenceNode';
  5014. }
  5015. constructor( property, uniformType, object = null, count = null ) {
  5016. super();
  5017. this.property = property;
  5018. this.uniformType = uniformType;
  5019. this.object = object;
  5020. this.count = count;
  5021. this.properties = property.split( '.' );
  5022. this.reference = object;
  5023. this.node = null;
  5024. this.group = null;
  5025. this.name = null;
  5026. this.updateType = NodeUpdateType.OBJECT;
  5027. }
  5028. element( indexNode ) {
  5029. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  5030. }
  5031. setGroup( group ) {
  5032. this.group = group;
  5033. return this;
  5034. }
  5035. label( name ) {
  5036. this.name = name;
  5037. return this;
  5038. }
  5039. setNodeType( uniformType ) {
  5040. let node = null;
  5041. if ( this.count !== null ) {
  5042. node = buffer( null, uniformType, this.count );
  5043. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  5044. node = uniformArray( null, uniformType );
  5045. } else if ( uniformType === 'texture' ) {
  5046. node = texture( null );
  5047. } else if ( uniformType === 'cubeTexture' ) {
  5048. node = cubeTexture( null );
  5049. } else {
  5050. node = uniform( null, uniformType );
  5051. }
  5052. if ( this.group !== null ) {
  5053. node.setGroup( this.group );
  5054. }
  5055. if ( this.name !== null ) node.label( this.name );
  5056. this.node = node.getSelf();
  5057. }
  5058. getNodeType( builder ) {
  5059. if ( this.node === null ) {
  5060. this.updateReference( builder );
  5061. this.updateValue();
  5062. }
  5063. return this.node.getNodeType( builder );
  5064. }
  5065. getValueFromReference( object = this.reference ) {
  5066. const { properties } = this;
  5067. let value = object[ properties[ 0 ] ];
  5068. for ( let i = 1; i < properties.length; i ++ ) {
  5069. value = value[ properties[ i ] ];
  5070. }
  5071. return value;
  5072. }
  5073. updateReference( state ) {
  5074. this.reference = this.object !== null ? this.object : state.object;
  5075. return this.reference;
  5076. }
  5077. setup() {
  5078. this.updateValue();
  5079. return this.node;
  5080. }
  5081. update( /*frame*/ ) {
  5082. this.updateValue();
  5083. }
  5084. updateValue() {
  5085. if ( this.node === null ) this.setNodeType( this.uniformType );
  5086. const value = this.getValueFromReference();
  5087. if ( Array.isArray( value ) ) {
  5088. this.node.array = value;
  5089. } else {
  5090. this.node.value = value;
  5091. }
  5092. }
  5093. }
  5094. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  5095. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  5096. class MaterialReferenceNode extends ReferenceNode {
  5097. static get type() {
  5098. return 'MaterialReferenceNode';
  5099. }
  5100. constructor( property, inputType, material = null ) {
  5101. super( property, inputType, material );
  5102. this.material = material;
  5103. //this.updateType = NodeUpdateType.RENDER;
  5104. this.isMaterialReferenceNode = true;
  5105. }
  5106. /*setNodeType( node ) {
  5107. super.setNodeType( node );
  5108. this.node.groupNode = renderGroup;
  5109. }*/
  5110. updateReference( state ) {
  5111. this.reference = this.material !== null ? this.material : state.material;
  5112. return this.reference;
  5113. }
  5114. }
  5115. const materialReference = ( name, type, material ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  5116. const tangentGeometry = /*@__PURE__*/ Fn( ( builder ) => {
  5117. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  5118. builder.geometry.computeTangents();
  5119. }
  5120. return attribute( 'tangent', 'vec4' );
  5121. } )();
  5122. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  5123. const tangentView = /*@__PURE__*/ modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.varying( 'v_tangentView' ).normalize().toVar( 'tangentView' );
  5124. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).varying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  5125. const transformedTangentView = /*@__PURE__*/ tangentView.toVar( 'transformedTangentView' );
  5126. const transformedTangentWorld = /*@__PURE__*/ transformedTangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedTangentWorld' );
  5127. const getBitangent = ( crossNormalTangent ) => crossNormalTangent.mul( tangentGeometry.w ).xyz;
  5128. const bitangentGeometry = /*@__PURE__*/ varying( getBitangent( normalGeometry.cross( tangentGeometry ) ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  5129. const bitangentLocal = /*@__PURE__*/ varying( getBitangent( normalLocal.cross( tangentLocal ) ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  5130. const bitangentView = /*@__PURE__*/ varying( getBitangent( normalView.cross( tangentView ) ), 'v_bitangentView' ).normalize().toVar( 'bitangentView' );
  5131. const bitangentWorld = /*@__PURE__*/ varying( getBitangent( normalWorld.cross( tangentWorld ) ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  5132. const transformedBitangentView = /*@__PURE__*/ getBitangent( transformedNormalView.cross( transformedTangentView ) ).normalize().toVar( 'transformedBitangentView' );
  5133. const transformedBitangentWorld = /*@__PURE__*/ transformedBitangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedBitangentWorld' );
  5134. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView );
  5135. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  5136. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  5137. const transformedBentNormalView = /*@__PURE__*/ ( () => {
  5138. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  5139. let bentNormal = anisotropyB.cross( positionViewDirection );
  5140. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  5141. bentNormal = mix( bentNormal, transformedNormalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  5142. return bentNormal;
  5143. } )();
  5144. // Normal Mapping Without Precomputed Tangents
  5145. // http://www.thetenthplanet.de/archives/1180
  5146. const perturbNormal2Arb = /*@__PURE__*/ Fn( ( inputs ) => {
  5147. const { eye_pos, surf_norm, mapN, uv } = inputs;
  5148. const q0 = eye_pos.dFdx();
  5149. const q1 = eye_pos.dFdy();
  5150. const st0 = uv.dFdx();
  5151. const st1 = uv.dFdy();
  5152. const N = surf_norm; // normalized
  5153. const q1perp = q1.cross( N );
  5154. const q0perp = N.cross( q0 );
  5155. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  5156. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  5157. const det = T.dot( T ).max( B.dot( B ) );
  5158. const scale = faceDirection.mul( det.inverseSqrt() );
  5159. return add( T.mul( mapN.x, scale ), B.mul( mapN.y, scale ), N.mul( mapN.z ) ).normalize();
  5160. } );
  5161. /**
  5162. * This class can be used for applying normals maps to materials.
  5163. *
  5164. * ```js
  5165. * material.normalNode = normalMap( texture( normalTex ) );
  5166. * ```
  5167. *
  5168. * @augments TempNode
  5169. */
  5170. class NormalMapNode extends TempNode {
  5171. static get type() {
  5172. return 'NormalMapNode';
  5173. }
  5174. /**
  5175. * Constructs a new normal map node.
  5176. *
  5177. * @param {Node} textureNode - Represents the normal map data.
  5178. * @param {Node?} [scaleNode=null] - Controls the intensity of the effect.
  5179. */
  5180. constructor( node, scaleNode = null ) {
  5181. super( 'vec3' );
  5182. /**
  5183. * Represents the normal map data.
  5184. *
  5185. * @type {Node}
  5186. */
  5187. this.node = node;
  5188. /**
  5189. * Controls the intensity of the effect.
  5190. *
  5191. * @type {Node?}
  5192. * @default null
  5193. */
  5194. this.scaleNode = scaleNode;
  5195. /**
  5196. * The normal map type.
  5197. *
  5198. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  5199. * @default TangentSpaceNormalMap
  5200. */
  5201. this.normalMapType = TangentSpaceNormalMap;
  5202. }
  5203. setup( builder ) {
  5204. const { normalMapType, scaleNode } = this;
  5205. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  5206. if ( scaleNode !== null ) {
  5207. normalMap = vec3( normalMap.xy.mul( scaleNode ), normalMap.z );
  5208. }
  5209. let outputNode = null;
  5210. if ( normalMapType === ObjectSpaceNormalMap ) {
  5211. outputNode = transformNormalToView( normalMap );
  5212. } else if ( normalMapType === TangentSpaceNormalMap ) {
  5213. const tangent = builder.hasGeometryAttribute( 'tangent' );
  5214. if ( tangent === true ) {
  5215. outputNode = TBNViewMatrix.mul( normalMap ).normalize();
  5216. } else {
  5217. outputNode = perturbNormal2Arb( {
  5218. eye_pos: positionView,
  5219. surf_norm: normalView,
  5220. mapN: normalMap,
  5221. uv: uv()
  5222. } );
  5223. }
  5224. }
  5225. return outputNode;
  5226. }
  5227. }
  5228. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode );
  5229. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  5230. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  5231. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  5232. // It's used to preserve the same TextureNode instance
  5233. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv() ), forceUVContext: true } );
  5234. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  5235. return vec2(
  5236. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  5237. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  5238. ).mul( bumpScale );
  5239. } );
  5240. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  5241. const perturbNormalArb = Fn( ( inputs ) => {
  5242. const { surf_pos, surf_norm, dHdxy } = inputs;
  5243. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  5244. const vSigmaX = surf_pos.dFdx().normalize();
  5245. const vSigmaY = surf_pos.dFdy().normalize();
  5246. const vN = surf_norm; // normalized
  5247. const R1 = vSigmaY.cross( vN );
  5248. const R2 = vN.cross( vSigmaX );
  5249. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  5250. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  5251. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  5252. } );
  5253. /**
  5254. * This class can be used for applying bump maps to materials.
  5255. *
  5256. * ```js
  5257. * material.normalNode = bumpMap( texture( bumpTex ) );
  5258. * ```
  5259. *
  5260. * @augments TempNode
  5261. */
  5262. class BumpMapNode extends TempNode {
  5263. static get type() {
  5264. return 'BumpMapNode';
  5265. }
  5266. /**
  5267. * Constructs a new bump map node.
  5268. *
  5269. * @param {Node} textureNode - Represents the bump map data.
  5270. * @param {Node?} [scaleNode=null] - Controls the intensity of the bump effect.
  5271. */
  5272. constructor( textureNode, scaleNode = null ) {
  5273. super( 'vec3' );
  5274. /**
  5275. * Represents the bump map data.
  5276. *
  5277. * @type {Node}
  5278. */
  5279. this.textureNode = textureNode;
  5280. /**
  5281. * Controls the intensity of the bump effect.
  5282. *
  5283. * @type {Node?}
  5284. * @default null
  5285. */
  5286. this.scaleNode = scaleNode;
  5287. }
  5288. setup() {
  5289. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  5290. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  5291. return perturbNormalArb( {
  5292. surf_pos: positionView,
  5293. surf_norm: normalView,
  5294. dHdxy
  5295. } );
  5296. }
  5297. }
  5298. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode );
  5299. const _propertyCache = new Map();
  5300. class MaterialNode extends Node {
  5301. static get type() {
  5302. return 'MaterialNode';
  5303. }
  5304. constructor( scope ) {
  5305. super();
  5306. this.scope = scope;
  5307. }
  5308. getCache( property, type ) {
  5309. let node = _propertyCache.get( property );
  5310. if ( node === undefined ) {
  5311. node = materialReference( property, type );
  5312. _propertyCache.set( property, node );
  5313. }
  5314. return node;
  5315. }
  5316. getFloat( property ) {
  5317. return this.getCache( property, 'float' );
  5318. }
  5319. getColor( property ) {
  5320. return this.getCache( property, 'color' );
  5321. }
  5322. getTexture( property ) {
  5323. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  5324. }
  5325. setup( builder ) {
  5326. const material = builder.context.material;
  5327. const scope = this.scope;
  5328. let node = null;
  5329. if ( scope === MaterialNode.COLOR ) {
  5330. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  5331. if ( material.map && material.map.isTexture === true ) {
  5332. node = colorNode.mul( this.getTexture( 'map' ) );
  5333. } else {
  5334. node = colorNode;
  5335. }
  5336. } else if ( scope === MaterialNode.OPACITY ) {
  5337. const opacityNode = this.getFloat( scope );
  5338. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  5339. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  5340. } else {
  5341. node = opacityNode;
  5342. }
  5343. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  5344. if ( material.specularMap && material.specularMap.isTexture === true ) {
  5345. node = this.getTexture( 'specular' ).r;
  5346. } else {
  5347. node = float( 1 );
  5348. }
  5349. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  5350. const specularIntensity = this.getFloat( scope );
  5351. if ( material.specularMap ) {
  5352. node = specularIntensity.mul( this.getTexture( scope ).a );
  5353. } else {
  5354. node = specularIntensity;
  5355. }
  5356. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  5357. const specularColorNode = this.getColor( scope );
  5358. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  5359. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  5360. } else {
  5361. node = specularColorNode;
  5362. }
  5363. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  5364. const roughnessNode = this.getFloat( scope );
  5365. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  5366. node = roughnessNode.mul( this.getTexture( scope ).g );
  5367. } else {
  5368. node = roughnessNode;
  5369. }
  5370. } else if ( scope === MaterialNode.METALNESS ) {
  5371. const metalnessNode = this.getFloat( scope );
  5372. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  5373. node = metalnessNode.mul( this.getTexture( scope ).b );
  5374. } else {
  5375. node = metalnessNode;
  5376. }
  5377. } else if ( scope === MaterialNode.EMISSIVE ) {
  5378. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  5379. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  5380. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  5381. node = emissiveNode.mul( this.getTexture( scope ) );
  5382. } else {
  5383. node = emissiveNode;
  5384. }
  5385. } else if ( scope === MaterialNode.NORMAL ) {
  5386. if ( material.normalMap ) {
  5387. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  5388. node.normalMapType = material.normalMapType;
  5389. } else if ( material.bumpMap ) {
  5390. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  5391. } else {
  5392. node = normalView;
  5393. }
  5394. } else if ( scope === MaterialNode.CLEARCOAT ) {
  5395. const clearcoatNode = this.getFloat( scope );
  5396. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  5397. node = clearcoatNode.mul( this.getTexture( scope ).r );
  5398. } else {
  5399. node = clearcoatNode;
  5400. }
  5401. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  5402. const clearcoatRoughnessNode = this.getFloat( scope );
  5403. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  5404. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  5405. } else {
  5406. node = clearcoatRoughnessNode;
  5407. }
  5408. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  5409. if ( material.clearcoatNormalMap ) {
  5410. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  5411. } else {
  5412. node = normalView;
  5413. }
  5414. } else if ( scope === MaterialNode.SHEEN ) {
  5415. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  5416. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  5417. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  5418. } else {
  5419. node = sheenNode;
  5420. }
  5421. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  5422. const sheenRoughnessNode = this.getFloat( scope );
  5423. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  5424. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  5425. } else {
  5426. node = sheenRoughnessNode;
  5427. }
  5428. node = node.clamp( 0.07, 1.0 );
  5429. } else if ( scope === MaterialNode.ANISOTROPY ) {
  5430. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  5431. const anisotropyPolar = this.getTexture( scope );
  5432. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  5433. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  5434. } else {
  5435. node = materialAnisotropyVector;
  5436. }
  5437. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  5438. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  5439. if ( material.iridescenceThicknessMap ) {
  5440. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  5441. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  5442. } else {
  5443. node = iridescenceThicknessMaximum;
  5444. }
  5445. } else if ( scope === MaterialNode.TRANSMISSION ) {
  5446. const transmissionNode = this.getFloat( scope );
  5447. if ( material.transmissionMap ) {
  5448. node = transmissionNode.mul( this.getTexture( scope ).r );
  5449. } else {
  5450. node = transmissionNode;
  5451. }
  5452. } else if ( scope === MaterialNode.THICKNESS ) {
  5453. const thicknessNode = this.getFloat( scope );
  5454. if ( material.thicknessMap ) {
  5455. node = thicknessNode.mul( this.getTexture( scope ).g );
  5456. } else {
  5457. node = thicknessNode;
  5458. }
  5459. } else if ( scope === MaterialNode.IOR ) {
  5460. node = this.getFloat( scope );
  5461. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  5462. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  5463. } else if ( scope === MaterialNode.AO_MAP ) {
  5464. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  5465. } else {
  5466. const outputType = this.getNodeType( builder );
  5467. node = this.getCache( scope, outputType );
  5468. }
  5469. return node;
  5470. }
  5471. }
  5472. MaterialNode.ALPHA_TEST = 'alphaTest';
  5473. MaterialNode.COLOR = 'color';
  5474. MaterialNode.OPACITY = 'opacity';
  5475. MaterialNode.SHININESS = 'shininess';
  5476. MaterialNode.SPECULAR = 'specular';
  5477. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  5478. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  5479. MaterialNode.SPECULAR_COLOR = 'specularColor';
  5480. MaterialNode.REFLECTIVITY = 'reflectivity';
  5481. MaterialNode.ROUGHNESS = 'roughness';
  5482. MaterialNode.METALNESS = 'metalness';
  5483. MaterialNode.NORMAL = 'normal';
  5484. MaterialNode.CLEARCOAT = 'clearcoat';
  5485. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  5486. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  5487. MaterialNode.EMISSIVE = 'emissive';
  5488. MaterialNode.ROTATION = 'rotation';
  5489. MaterialNode.SHEEN = 'sheen';
  5490. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  5491. MaterialNode.ANISOTROPY = 'anisotropy';
  5492. MaterialNode.IRIDESCENCE = 'iridescence';
  5493. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  5494. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  5495. MaterialNode.IOR = 'ior';
  5496. MaterialNode.TRANSMISSION = 'transmission';
  5497. MaterialNode.THICKNESS = 'thickness';
  5498. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  5499. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  5500. MaterialNode.LINE_SCALE = 'scale';
  5501. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  5502. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  5503. MaterialNode.LINE_WIDTH = 'linewidth';
  5504. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  5505. MaterialNode.POINT_WIDTH = 'pointWidth';
  5506. MaterialNode.DISPERSION = 'dispersion';
  5507. MaterialNode.LIGHT_MAP = 'light';
  5508. MaterialNode.AO_MAP = 'ao';
  5509. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  5510. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  5511. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  5512. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  5513. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  5514. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  5515. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  5516. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  5517. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  5518. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  5519. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  5520. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  5521. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL ).context( { getUV: null } );
  5522. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  5523. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  5524. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL ).context( { getUV: null } );
  5525. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  5526. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  5527. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  5528. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  5529. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  5530. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  5531. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  5532. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  5533. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  5534. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  5535. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  5536. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  5537. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  5538. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  5539. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  5540. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  5541. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  5542. const materialPointWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_WIDTH );
  5543. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  5544. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  5545. const materialAOMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO_MAP );
  5546. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  5547. return frame.material;
  5548. } ).onRenderUpdate( function ( { material } ) {
  5549. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  5550. } );
  5551. class ModelViewProjectionNode extends TempNode {
  5552. static get type() {
  5553. return 'ModelViewProjectionNode';
  5554. }
  5555. constructor( positionNode = null ) {
  5556. super( 'vec4' );
  5557. this.positionNode = positionNode;
  5558. }
  5559. setup( builder ) {
  5560. if ( builder.shaderStage === 'fragment' ) {
  5561. return varying( builder.context.mvp );
  5562. }
  5563. const position = this.positionNode || positionLocal;
  5564. const viewMatrix = builder.renderer.nodes.modelViewMatrix || modelViewMatrix;
  5565. return cameraProjectionMatrix.mul( viewMatrix ).mul( position );
  5566. }
  5567. }
  5568. const modelViewProjection = /*@__PURE__*/ nodeProxy( ModelViewProjectionNode );
  5569. /**
  5570. * This class represents shader indices of different types. The following predefined node
  5571. * objects cover frequent use cases:
  5572. *
  5573. * - `vertexIndex`: The index of a vertex within a mesh.
  5574. * - `instanceIndex`: The index of either a mesh instance or an invocation of a compute shader.
  5575. * - `drawIndex`: The index of a draw call.
  5576. * - `invocationLocalIndex`: The index of a compute invocation within the scope of a workgroup load.
  5577. * - `invocationSubgroupIndex`: The index of a compute invocation within the scope of a subgroup.
  5578. * - `subgroupIndex`: The index of the subgroup the current compute invocation belongs to.
  5579. *
  5580. * @augments Node
  5581. */
  5582. class IndexNode extends Node {
  5583. static get type() {
  5584. return 'IndexNode';
  5585. }
  5586. /**
  5587. * Constructs a new index node.
  5588. *
  5589. * @param {('vertex'|'instance'|'subgroup'|'invocationLocal'|'invocationSubgroup'|'draw')} value - The scope of the index node.
  5590. */
  5591. constructor( scope ) {
  5592. super( 'uint' );
  5593. /**
  5594. * The scope of the index node.
  5595. *
  5596. * @type {String}
  5597. */
  5598. this.scope = scope;
  5599. /**
  5600. * This flag can be used for type testing.
  5601. *
  5602. * @type {Boolean}
  5603. * @readonly
  5604. * @default true
  5605. */
  5606. this.isIndexNode = true;
  5607. }
  5608. generate( builder ) {
  5609. const nodeType = this.getNodeType( builder );
  5610. const scope = this.scope;
  5611. let propertyName;
  5612. if ( scope === IndexNode.VERTEX ) {
  5613. propertyName = builder.getVertexIndex();
  5614. } else if ( scope === IndexNode.INSTANCE ) {
  5615. propertyName = builder.getInstanceIndex();
  5616. } else if ( scope === IndexNode.DRAW ) {
  5617. propertyName = builder.getDrawIndex();
  5618. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  5619. propertyName = builder.getInvocationLocalIndex();
  5620. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  5621. propertyName = builder.getInvocationSubgroupIndex();
  5622. } else if ( scope === IndexNode.SUBGROUP ) {
  5623. propertyName = builder.getSubgroupIndex();
  5624. } else {
  5625. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  5626. }
  5627. let output;
  5628. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  5629. output = propertyName;
  5630. } else {
  5631. const nodeVarying = varying( this );
  5632. output = nodeVarying.build( builder, nodeType );
  5633. }
  5634. return output;
  5635. }
  5636. }
  5637. IndexNode.VERTEX = 'vertex';
  5638. IndexNode.INSTANCE = 'instance';
  5639. IndexNode.SUBGROUP = 'subgroup';
  5640. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  5641. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  5642. IndexNode.DRAW = 'draw';
  5643. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  5644. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  5645. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  5646. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  5647. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  5648. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  5649. class InstanceNode extends Node {
  5650. static get type() {
  5651. return 'InstanceNode';
  5652. }
  5653. constructor( count, instanceMatrix, instanceColor ) {
  5654. super( 'void' );
  5655. this.count = count;
  5656. this.instanceMatrix = instanceMatrix;
  5657. this.instanceColor = instanceColor;
  5658. this.instanceMatrixNode = null;
  5659. this.instanceColorNode = null;
  5660. this.updateType = NodeUpdateType.FRAME;
  5661. this.buffer = null;
  5662. this.bufferColor = null;
  5663. }
  5664. setup( builder ) {
  5665. const { count, instanceMatrix, instanceColor } = this;
  5666. let { instanceMatrixNode, instanceColorNode } = this;
  5667. if ( instanceMatrixNode === null ) {
  5668. // 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.
  5669. if ( count <= 1000 ) {
  5670. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  5671. } else {
  5672. const buffer = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  5673. this.buffer = buffer;
  5674. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  5675. const instanceBuffers = [
  5676. // F.Signature -> bufferAttribute( array, type, stride, offset )
  5677. bufferFn( buffer, 'vec4', 16, 0 ),
  5678. bufferFn( buffer, 'vec4', 16, 4 ),
  5679. bufferFn( buffer, 'vec4', 16, 8 ),
  5680. bufferFn( buffer, 'vec4', 16, 12 )
  5681. ];
  5682. instanceMatrixNode = mat4( ...instanceBuffers );
  5683. }
  5684. this.instanceMatrixNode = instanceMatrixNode;
  5685. }
  5686. if ( instanceColor && instanceColorNode === null ) {
  5687. const buffer = new InstancedBufferAttribute( instanceColor.array, 3 );
  5688. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  5689. this.bufferColor = buffer;
  5690. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  5691. this.instanceColorNode = instanceColorNode;
  5692. }
  5693. // POSITION
  5694. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  5695. positionLocal.assign( instancePosition );
  5696. // NORMAL
  5697. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  5698. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  5699. // ASSIGNS
  5700. normalLocal.assign( instanceNormal );
  5701. }
  5702. // COLOR
  5703. if ( this.instanceColorNode !== null ) {
  5704. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  5705. }
  5706. }
  5707. update( /*frame*/ ) {
  5708. if ( this.instanceMatrix.usage !== DynamicDrawUsage && this.buffer != null && this.instanceMatrix.version !== this.buffer.version ) {
  5709. this.buffer.version = this.instanceMatrix.version;
  5710. }
  5711. if ( this.instanceColor && this.instanceColor.usage !== DynamicDrawUsage && this.bufferColor != null && this.instanceColor.version !== this.bufferColor.version ) {
  5712. this.bufferColor.version = this.instanceColor.version;
  5713. }
  5714. }
  5715. }
  5716. const instance = /*@__PURE__*/ nodeProxy( InstanceNode );
  5717. class InstancedMeshNode extends InstanceNode {
  5718. static get type() {
  5719. return 'InstancedMeshNode';
  5720. }
  5721. constructor( instanceMesh ) {
  5722. const { count, instanceMatrix, instanceColor } = instanceMesh;
  5723. super( count, instanceMatrix, instanceColor );
  5724. this.instanceMesh = instanceMesh;
  5725. }
  5726. }
  5727. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode );
  5728. class BatchNode extends Node {
  5729. static get type() {
  5730. return 'BatchNode';
  5731. }
  5732. constructor( batchMesh ) {
  5733. super( 'void' );
  5734. this.batchMesh = batchMesh;
  5735. this.batchingIdNode = null;
  5736. }
  5737. setup( builder ) {
  5738. // POSITION
  5739. if ( this.batchingIdNode === null ) {
  5740. if ( builder.getDrawIndex() === null ) {
  5741. this.batchingIdNode = instanceIndex;
  5742. } else {
  5743. this.batchingIdNode = drawIndex;
  5744. }
  5745. }
  5746. const getIndirectIndex = Fn( ( [ id ] ) => {
  5747. const size = textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 );
  5748. const x = int( id ).modInt( int( size ) );
  5749. const y = int( id ).div( int( size ) );
  5750. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  5751. } ).setLayout( {
  5752. name: 'getIndirectIndex',
  5753. type: 'uint',
  5754. inputs: [
  5755. { name: 'id', type: 'int' }
  5756. ]
  5757. } );
  5758. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  5759. const matricesTexture = this.batchMesh._matricesTexture;
  5760. const size = textureSize( textureLoad( matricesTexture ), 0 );
  5761. const j = float( indirectId ).mul( 4 ).toInt().toVar();
  5762. const x = j.modInt( size );
  5763. const y = j.div( int( size ) );
  5764. const batchingMatrix = mat4(
  5765. textureLoad( matricesTexture, ivec2( x, y ) ),
  5766. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  5767. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  5768. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  5769. );
  5770. const colorsTexture = this.batchMesh._colorsTexture;
  5771. if ( colorsTexture !== null ) {
  5772. const getBatchingColor = Fn( ( [ id ] ) => {
  5773. const size = textureSize( textureLoad( colorsTexture ), 0 ).x;
  5774. const j = id;
  5775. const x = j.modInt( size );
  5776. const y = j.div( size );
  5777. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  5778. } ).setLayout( {
  5779. name: 'getBatchingColor',
  5780. type: 'vec3',
  5781. inputs: [
  5782. { name: 'id', type: 'int' }
  5783. ]
  5784. } );
  5785. const color = getBatchingColor( indirectId );
  5786. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  5787. }
  5788. const bm = mat3( batchingMatrix );
  5789. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  5790. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  5791. const batchingNormal = bm.mul( transformedNormal ).xyz;
  5792. normalLocal.assign( batchingNormal );
  5793. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  5794. tangentLocal.mulAssign( bm );
  5795. }
  5796. }
  5797. }
  5798. const batch = /*@__PURE__*/ nodeProxy( BatchNode );
  5799. const _frameId = new WeakMap();
  5800. class SkinningNode extends Node {
  5801. static get type() {
  5802. return 'SkinningNode';
  5803. }
  5804. constructor( skinnedMesh, useReference = false ) {
  5805. super( 'void' );
  5806. this.skinnedMesh = skinnedMesh;
  5807. this.useReference = useReference;
  5808. this.updateType = NodeUpdateType.OBJECT;
  5809. //
  5810. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  5811. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  5812. let bindMatrixNode, bindMatrixInverseNode, boneMatricesNode;
  5813. if ( useReference ) {
  5814. bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  5815. bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  5816. boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  5817. } else {
  5818. bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  5819. bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  5820. boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  5821. }
  5822. this.bindMatrixNode = bindMatrixNode;
  5823. this.bindMatrixInverseNode = bindMatrixInverseNode;
  5824. this.boneMatricesNode = boneMatricesNode;
  5825. this.previousBoneMatricesNode = null;
  5826. }
  5827. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = positionLocal ) {
  5828. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  5829. const boneMatX = boneMatrices.element( skinIndexNode.x );
  5830. const boneMatY = boneMatrices.element( skinIndexNode.y );
  5831. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  5832. const boneMatW = boneMatrices.element( skinIndexNode.w );
  5833. // POSITION
  5834. const skinVertex = bindMatrixNode.mul( position );
  5835. const skinned = add(
  5836. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  5837. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  5838. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  5839. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  5840. );
  5841. return bindMatrixInverseNode.mul( skinned ).xyz;
  5842. }
  5843. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  5844. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  5845. const boneMatX = boneMatrices.element( skinIndexNode.x );
  5846. const boneMatY = boneMatrices.element( skinIndexNode.y );
  5847. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  5848. const boneMatW = boneMatrices.element( skinIndexNode.w );
  5849. // NORMAL
  5850. let skinMatrix = add(
  5851. skinWeightNode.x.mul( boneMatX ),
  5852. skinWeightNode.y.mul( boneMatY ),
  5853. skinWeightNode.z.mul( boneMatZ ),
  5854. skinWeightNode.w.mul( boneMatW )
  5855. );
  5856. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  5857. return skinMatrix.transformDirection( normal ).xyz;
  5858. }
  5859. getPreviousSkinnedPosition( builder ) {
  5860. const skinnedMesh = builder.object;
  5861. if ( this.previousBoneMatricesNode === null ) {
  5862. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  5863. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  5864. }
  5865. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  5866. }
  5867. needsPreviousBoneMatrices( builder ) {
  5868. const mrt = builder.renderer.getMRT();
  5869. return mrt && mrt.has( 'velocity' );
  5870. }
  5871. setup( builder ) {
  5872. if ( this.needsPreviousBoneMatrices( builder ) ) {
  5873. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  5874. }
  5875. const skinPosition = this.getSkinnedPosition();
  5876. positionLocal.assign( skinPosition );
  5877. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  5878. const skinNormal = this.getSkinnedNormal();
  5879. normalLocal.assign( skinNormal );
  5880. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  5881. tangentLocal.assign( skinNormal );
  5882. }
  5883. }
  5884. }
  5885. generate( builder, output ) {
  5886. if ( output !== 'void' ) {
  5887. return positionLocal.build( builder, output );
  5888. }
  5889. }
  5890. update( frame ) {
  5891. const object = this.useReference ? frame.object : this.skinnedMesh;
  5892. const skeleton = object.skeleton;
  5893. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  5894. _frameId.set( skeleton, frame.frameId );
  5895. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  5896. skeleton.update();
  5897. }
  5898. }
  5899. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  5900. const skinningReference = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh, true ) );
  5901. /**
  5902. * This module offers a variety of ways to implement loops in TSL. In it's basic form it's:
  5903. * ```js
  5904. * Loop( count, ( { i } ) => {
  5905. *
  5906. * } );
  5907. * ```
  5908. * However, it is also possible to define a start and end ranges, data types and loop conditions:
  5909. * ```js
  5910. * Loop( { start: int( 0 ), end: int( 10 ), type: 'int', condition: '<' }, ( { i } ) => {
  5911. *
  5912. * } );
  5913. *```
  5914. * Nested loops can be definde in a compacted form:
  5915. * ```js
  5916. * Loop( 10, 5, ( { i, j } ) => {
  5917. *
  5918. * } );
  5919. * ```
  5920. * Loops that should run backwards can be defined like so:
  5921. * ```js
  5922. * Loop( { start: 10 }, () => {} );
  5923. * ```
  5924. * The module also provides `Break()` and `Continue()` TSL expression for loop control.
  5925. * @augments Node
  5926. */
  5927. class LoopNode extends Node {
  5928. static get type() {
  5929. return 'LoopNode';
  5930. }
  5931. /**
  5932. * Constructs a new loop node.
  5933. *
  5934. * @param {Array<Any>} params - Depending on the loop type, array holds different parameterization values for the loop.
  5935. */
  5936. constructor( params = [] ) {
  5937. super();
  5938. this.params = params;
  5939. }
  5940. /**
  5941. * Returns a loop variable name based on an index. The pattern is
  5942. * `0` = `i`, `1`= `j`, `2`= `k` and so on.
  5943. *
  5944. * @param {Number} index - The index.
  5945. * @return {String} The loop variable name.
  5946. */
  5947. getVarName( index ) {
  5948. return String.fromCharCode( 'i'.charCodeAt() + index );
  5949. }
  5950. /**
  5951. * Returns properties about this node.
  5952. *
  5953. * @param {NodeBuilder} builder - The current node builder.
  5954. * @return {Object} The node properties.
  5955. */
  5956. getProperties( builder ) {
  5957. const properties = builder.getNodeProperties( this );
  5958. if ( properties.stackNode !== undefined ) return properties;
  5959. //
  5960. const inputs = {};
  5961. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  5962. const param = this.params[ i ];
  5963. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  5964. const type = ( param.isNode !== true && param.type ) || 'int';
  5965. inputs[ name ] = expression( name, type );
  5966. }
  5967. const stack = builder.addStack(); // TODO: cache() it
  5968. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, stack, builder );
  5969. properties.stackNode = stack;
  5970. builder.removeStack();
  5971. return properties;
  5972. }
  5973. /**
  5974. * This method is overwritten since the node type is inferred based on the loop configuration.
  5975. *
  5976. * @param {NodeBuilder} builder - The current node builder.
  5977. * @return {String} The node type.
  5978. */
  5979. getNodeType( builder ) {
  5980. const { returnsNode } = this.getProperties( builder );
  5981. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  5982. }
  5983. setup( builder ) {
  5984. // setup properties
  5985. this.getProperties( builder );
  5986. }
  5987. generate( builder ) {
  5988. const properties = this.getProperties( builder );
  5989. const params = this.params;
  5990. const stackNode = properties.stackNode;
  5991. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  5992. const param = params[ i ];
  5993. let start = null, end = null, name = null, type = null, condition = null, update = null;
  5994. if ( param.isNode ) {
  5995. type = 'int';
  5996. name = this.getVarName( i );
  5997. start = '0';
  5998. end = param.build( builder, type );
  5999. condition = '<';
  6000. } else {
  6001. type = param.type || 'int';
  6002. name = param.name || this.getVarName( i );
  6003. start = param.start;
  6004. end = param.end;
  6005. condition = param.condition;
  6006. update = param.update;
  6007. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  6008. else if ( start && start.isNode ) start = start.build( builder, type );
  6009. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  6010. else if ( end && end.isNode ) end = end.build( builder, type );
  6011. if ( start !== undefined && end === undefined ) {
  6012. start = start + ' - 1';
  6013. end = '0';
  6014. condition = '>=';
  6015. } else if ( end !== undefined && start === undefined ) {
  6016. start = '0';
  6017. condition = '<';
  6018. }
  6019. if ( condition === undefined ) {
  6020. if ( Number( start ) > Number( end ) ) {
  6021. condition = '>=';
  6022. } else {
  6023. condition = '<';
  6024. }
  6025. }
  6026. }
  6027. const internalParam = { start, end, condition };
  6028. //
  6029. const startSnippet = internalParam.start;
  6030. const endSnippet = internalParam.end;
  6031. let declarationSnippet = '';
  6032. let conditionalSnippet = '';
  6033. let updateSnippet = '';
  6034. if ( ! update ) {
  6035. if ( type === 'int' || type === 'uint' ) {
  6036. if ( condition.includes( '<' ) ) update = '++';
  6037. else update = '--';
  6038. } else {
  6039. if ( condition.includes( '<' ) ) update = '+= 1.';
  6040. else update = '-= 1.';
  6041. }
  6042. }
  6043. declarationSnippet += builder.getVar( type, name ) + ' = ' + startSnippet;
  6044. conditionalSnippet += name + ' ' + condition + ' ' + endSnippet;
  6045. updateSnippet += name + ' ' + update;
  6046. const forSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  6047. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + forSnippet + ' {\n\n' ).addFlowTab();
  6048. }
  6049. const stackSnippet = stackNode.build( builder, 'void' );
  6050. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  6051. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  6052. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  6053. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  6054. }
  6055. builder.addFlowTab();
  6056. return returnsSnippet;
  6057. }
  6058. }
  6059. const Loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).append();
  6060. const Continue = () => expression( 'continue' ).append();
  6061. const Break = () => expression( 'break' ).append();
  6062. //
  6063. const loop = ( ...params ) => { // @deprecated, r168
  6064. console.warn( 'TSL.LoopNode: loop() has been renamed to Loop().' );
  6065. return Loop( ...params );
  6066. };
  6067. const _morphTextures = /*@__PURE__*/ new WeakMap();
  6068. const _morphVec4 = /*@__PURE__*/ new Vector4();
  6069. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  6070. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  6071. const y = texelIndex.div( width );
  6072. const x = texelIndex.sub( y.mul( width ) );
  6073. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth );
  6074. return bufferAttrib.mul( influence );
  6075. } );
  6076. function getEntry( geometry ) {
  6077. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  6078. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  6079. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  6080. // instead of using attributes, the WebGL 2 code path encodes morph targets
  6081. // into an array of data textures. Each layer represents a single morph target.
  6082. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  6083. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  6084. let entry = _morphTextures.get( geometry );
  6085. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  6086. if ( entry !== undefined ) entry.texture.dispose();
  6087. const morphTargets = geometry.morphAttributes.position || [];
  6088. const morphNormals = geometry.morphAttributes.normal || [];
  6089. const morphColors = geometry.morphAttributes.color || [];
  6090. let vertexDataCount = 0;
  6091. if ( hasMorphPosition === true ) vertexDataCount = 1;
  6092. if ( hasMorphNormals === true ) vertexDataCount = 2;
  6093. if ( hasMorphColors === true ) vertexDataCount = 3;
  6094. let width = geometry.attributes.position.count * vertexDataCount;
  6095. let height = 1;
  6096. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  6097. if ( width > maxTextureSize ) {
  6098. height = Math.ceil( width / maxTextureSize );
  6099. width = maxTextureSize;
  6100. }
  6101. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  6102. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  6103. bufferTexture.type = FloatType;
  6104. bufferTexture.needsUpdate = true;
  6105. // fill buffer
  6106. const vertexDataStride = vertexDataCount * 4;
  6107. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  6108. const morphTarget = morphTargets[ i ];
  6109. const morphNormal = morphNormals[ i ];
  6110. const morphColor = morphColors[ i ];
  6111. const offset = width * height * 4 * i;
  6112. for ( let j = 0; j < morphTarget.count; j ++ ) {
  6113. const stride = j * vertexDataStride;
  6114. if ( hasMorphPosition === true ) {
  6115. _morphVec4.fromBufferAttribute( morphTarget, j );
  6116. buffer[ offset + stride + 0 ] = _morphVec4.x;
  6117. buffer[ offset + stride + 1 ] = _morphVec4.y;
  6118. buffer[ offset + stride + 2 ] = _morphVec4.z;
  6119. buffer[ offset + stride + 3 ] = 0;
  6120. }
  6121. if ( hasMorphNormals === true ) {
  6122. _morphVec4.fromBufferAttribute( morphNormal, j );
  6123. buffer[ offset + stride + 4 ] = _morphVec4.x;
  6124. buffer[ offset + stride + 5 ] = _morphVec4.y;
  6125. buffer[ offset + stride + 6 ] = _morphVec4.z;
  6126. buffer[ offset + stride + 7 ] = 0;
  6127. }
  6128. if ( hasMorphColors === true ) {
  6129. _morphVec4.fromBufferAttribute( morphColor, j );
  6130. buffer[ offset + stride + 8 ] = _morphVec4.x;
  6131. buffer[ offset + stride + 9 ] = _morphVec4.y;
  6132. buffer[ offset + stride + 10 ] = _morphVec4.z;
  6133. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  6134. }
  6135. }
  6136. }
  6137. entry = {
  6138. count: morphTargetsCount,
  6139. texture: bufferTexture,
  6140. stride: vertexDataCount,
  6141. size: new Vector2( width, height )
  6142. };
  6143. _morphTextures.set( geometry, entry );
  6144. function disposeTexture() {
  6145. bufferTexture.dispose();
  6146. _morphTextures.delete( geometry );
  6147. geometry.removeEventListener( 'dispose', disposeTexture );
  6148. }
  6149. geometry.addEventListener( 'dispose', disposeTexture );
  6150. }
  6151. return entry;
  6152. }
  6153. class MorphNode extends Node {
  6154. static get type() {
  6155. return 'MorphNode';
  6156. }
  6157. constructor( mesh ) {
  6158. super( 'void' );
  6159. this.mesh = mesh;
  6160. this.morphBaseInfluence = uniform( 1 );
  6161. this.updateType = NodeUpdateType.OBJECT;
  6162. }
  6163. setup( builder ) {
  6164. const { geometry } = builder;
  6165. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  6166. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  6167. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  6168. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  6169. // nodes
  6170. const { texture: bufferMap, stride, size } = getEntry( geometry );
  6171. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  6172. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  6173. const width = int( size.width );
  6174. Loop( morphTargetsCount, ( { i } ) => {
  6175. const influence = float( 0 ).toVar();
  6176. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  6177. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  6178. } else {
  6179. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  6180. }
  6181. if ( hasMorphPosition === true ) {
  6182. positionLocal.addAssign( getMorph( {
  6183. bufferMap,
  6184. influence,
  6185. stride,
  6186. width,
  6187. depth: i,
  6188. offset: int( 0 )
  6189. } ) );
  6190. }
  6191. if ( hasMorphNormals === true ) {
  6192. normalLocal.addAssign( getMorph( {
  6193. bufferMap,
  6194. influence,
  6195. stride,
  6196. width,
  6197. depth: i,
  6198. offset: int( 1 )
  6199. } ) );
  6200. }
  6201. } );
  6202. }
  6203. update() {
  6204. const morphBaseInfluence = this.morphBaseInfluence;
  6205. if ( this.mesh.geometry.morphTargetsRelative ) {
  6206. morphBaseInfluence.value = 1;
  6207. } else {
  6208. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  6209. }
  6210. }
  6211. }
  6212. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode );
  6213. class LightingNode extends Node {
  6214. static get type() {
  6215. return 'LightingNode';
  6216. }
  6217. constructor() {
  6218. super( 'vec3' );
  6219. this.isLightingNode = true;
  6220. }
  6221. generate( /*builder*/ ) {
  6222. console.warn( 'Abstract function.' );
  6223. }
  6224. }
  6225. class AONode extends LightingNode {
  6226. static get type() {
  6227. return 'AONode';
  6228. }
  6229. constructor( aoNode = null ) {
  6230. super();
  6231. this.aoNode = aoNode;
  6232. }
  6233. setup( builder ) {
  6234. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  6235. }
  6236. }
  6237. class LightingContextNode extends ContextNode {
  6238. static get type() {
  6239. return 'LightingContextNode';
  6240. }
  6241. constructor( node, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  6242. super( node );
  6243. this.lightingModel = lightingModel;
  6244. this.backdropNode = backdropNode;
  6245. this.backdropAlphaNode = backdropAlphaNode;
  6246. this._value = null;
  6247. }
  6248. getContext() {
  6249. const { backdropNode, backdropAlphaNode } = this;
  6250. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  6251. directSpecular = vec3().toVar( 'directSpecular' ),
  6252. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  6253. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  6254. const reflectedLight = {
  6255. directDiffuse,
  6256. directSpecular,
  6257. indirectDiffuse,
  6258. indirectSpecular
  6259. };
  6260. const context = {
  6261. radiance: vec3().toVar( 'radiance' ),
  6262. irradiance: vec3().toVar( 'irradiance' ),
  6263. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  6264. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  6265. reflectedLight,
  6266. backdrop: backdropNode,
  6267. backdropAlpha: backdropAlphaNode
  6268. };
  6269. return context;
  6270. }
  6271. setup( builder ) {
  6272. this.value = this._value || ( this._value = this.getContext() );
  6273. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  6274. return super.setup( builder );
  6275. }
  6276. }
  6277. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  6278. class IrradianceNode extends LightingNode {
  6279. static get type() {
  6280. return 'IrradianceNode';
  6281. }
  6282. constructor( node ) {
  6283. super();
  6284. this.node = node;
  6285. }
  6286. setup( builder ) {
  6287. builder.context.irradiance.addAssign( this.node );
  6288. }
  6289. }
  6290. let screenSizeVec, viewportVec;
  6291. /**
  6292. * This node provides a collection of screen related metrics.
  6293. * Depending on {@link ScreenNode#scope}, the nodes can represent
  6294. * resolution or viewport data as well as fragment or uv coordinates.
  6295. *
  6296. * @augments Node
  6297. */
  6298. class ScreenNode extends Node {
  6299. static get type() {
  6300. return 'ScreenNode';
  6301. }
  6302. /**
  6303. * Constructs a new screen node.
  6304. *
  6305. * @param {('coordinate'|'viewport'|'size'|'uv')} scope - The node's scope.
  6306. */
  6307. constructor( scope ) {
  6308. super();
  6309. /**
  6310. * The node represents different metric depending on which scope is selected.
  6311. *
  6312. * - `ScreenNode.COORDINATE`: Window-relative coordinates of the current fragment according to WebGPU standards.
  6313. * - `ScreenNode.VIEWPORT`: The current viewport defined as a four-dimensional vector.
  6314. * - `ScreenNode.SIZE`: The dimensions of the current bound framebuffer.
  6315. * - `ScreenNode.UV`: Normalized screen coordinates.
  6316. *
  6317. * @type {('coordinate'|'viewport'|'size'|'uv')}
  6318. */
  6319. this.scope = scope;
  6320. /**
  6321. * This flag can be used for type testing.
  6322. *
  6323. * @type {Boolean}
  6324. * @readonly
  6325. * @default true
  6326. */
  6327. this.isViewportNode = true;
  6328. }
  6329. /**
  6330. * This method is overwritten since the node type depends on the selected scope.
  6331. *
  6332. * @return {('vec2'|'vec4')} The node type.
  6333. */
  6334. getNodeType() {
  6335. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  6336. else return 'vec2';
  6337. }
  6338. /**
  6339. * This method is overwritten since the node's update type depends on the selected scope.
  6340. *
  6341. * @return {NodeUpdateType} The update type.
  6342. */
  6343. getUpdateType() {
  6344. let updateType = NodeUpdateType.NONE;
  6345. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT ) {
  6346. updateType = NodeUpdateType.RENDER;
  6347. }
  6348. this.updateType = updateType;
  6349. return updateType;
  6350. }
  6351. /**
  6352. * `ScreenNode` implements {@link Node#update} to retrieve viewport and size information
  6353. * from the current renderer.
  6354. *
  6355. * @param {NodeFrame} frame - A reference to the current node frame.
  6356. * @return {Boolean?} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  6357. */
  6358. update( { renderer } ) {
  6359. const renderTarget = renderer.getRenderTarget();
  6360. if ( this.scope === ScreenNode.VIEWPORT ) {
  6361. if ( renderTarget !== null ) {
  6362. viewportVec.copy( renderTarget.viewport );
  6363. } else {
  6364. renderer.getViewport( viewportVec );
  6365. viewportVec.multiplyScalar( renderer.getPixelRatio() );
  6366. }
  6367. } else {
  6368. if ( renderTarget !== null ) {
  6369. screenSizeVec.width = renderTarget.width;
  6370. screenSizeVec.height = renderTarget.height;
  6371. } else {
  6372. renderer.getDrawingBufferSize( screenSizeVec );
  6373. }
  6374. }
  6375. }
  6376. setup( /*builder*/ ) {
  6377. const scope = this.scope;
  6378. let output = null;
  6379. if ( scope === ScreenNode.SIZE ) {
  6380. output = uniform( screenSizeVec || ( screenSizeVec = new Vector2() ) );
  6381. } else if ( scope === ScreenNode.VIEWPORT ) {
  6382. output = uniform( viewportVec || ( viewportVec = new Vector4() ) );
  6383. } else {
  6384. output = vec2( screenCoordinate.div( screenSize ) );
  6385. }
  6386. return output;
  6387. }
  6388. generate( builder ) {
  6389. if ( this.scope === ScreenNode.COORDINATE ) {
  6390. let coord = builder.getFragCoord();
  6391. if ( builder.isFlipY() ) {
  6392. // follow webgpu standards
  6393. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  6394. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  6395. }
  6396. return coord;
  6397. }
  6398. return super.generate( builder );
  6399. }
  6400. }
  6401. ScreenNode.COORDINATE = 'coordinate';
  6402. ScreenNode.VIEWPORT = 'viewport';
  6403. ScreenNode.SIZE = 'size';
  6404. ScreenNode.UV = 'uv';
  6405. // Screen
  6406. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  6407. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  6408. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  6409. // Viewport
  6410. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  6411. const viewportSize = viewport.zw;
  6412. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  6413. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  6414. // Deprecated
  6415. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  6416. console.warn( 'TSL.ViewportNode: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  6417. return screenSize;
  6418. }, 'vec2' ).once() )();
  6419. const viewportTopLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  6420. console.warn( 'TSL.ViewportNode: "viewportTopLeft" is deprecated. Use "screenUV" instead.' );
  6421. return screenUV;
  6422. }, 'vec2' ).once() )();
  6423. const viewportBottomLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  6424. console.warn( 'TSL.ViewportNode: "viewportBottomLeft" is deprecated. Use "screenUV.flipY()" instead.' );
  6425. return screenUV.flipY();
  6426. }, 'vec2' ).once() )();
  6427. const _size$4 = /*@__PURE__*/ new Vector2();
  6428. /**
  6429. * A special type of texture node which represents the data of the current viewport
  6430. * as a texture. The module extracts data from the current bound framebuffer with
  6431. * a copy operation so no extra render pass is required to produce the texture data
  6432. * (which is good for performance). `ViewportTextureNode` can be used as an input for a
  6433. * variety of effects like refractive or transmissive materials.
  6434. *
  6435. * @augments TextureNode
  6436. */
  6437. class ViewportTextureNode extends TextureNode {
  6438. static get type() {
  6439. return 'ViewportTextureNode';
  6440. }
  6441. /**
  6442. * Constructs a new viewport texture node.
  6443. *
  6444. * @param {Node} [uvNode=screenUV] - The uv node.
  6445. * @param {Node?} [levelNode=null] - The level node.
  6446. * @param {Texture?} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  6447. */
  6448. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  6449. if ( framebufferTexture === null ) {
  6450. framebufferTexture = new FramebufferTexture();
  6451. framebufferTexture.minFilter = LinearMipmapLinearFilter;
  6452. }
  6453. super( framebufferTexture, uvNode, levelNode );
  6454. /**
  6455. * Whether to generate mipmaps or not.
  6456. *
  6457. * @type {Boolean}
  6458. * @default false
  6459. */
  6460. this.generateMipmaps = false;
  6461. /**
  6462. * This flag can be used for type testing.
  6463. *
  6464. * @type {Boolean}
  6465. * @readonly
  6466. * @default true
  6467. */
  6468. this.isOutputTextureNode = true;
  6469. /**
  6470. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  6471. * scene once per frame in its {@link ViewportTextureNode#updateBefore} method.
  6472. *
  6473. * @type {String}
  6474. * @default 'frame'
  6475. */
  6476. this.updateBeforeType = NodeUpdateType.FRAME;
  6477. }
  6478. updateBefore( frame ) {
  6479. const renderer = frame.renderer;
  6480. renderer.getDrawingBufferSize( _size$4 );
  6481. //
  6482. const framebufferTexture = this.value;
  6483. if ( framebufferTexture.image.width !== _size$4.width || framebufferTexture.image.height !== _size$4.height ) {
  6484. framebufferTexture.image.width = _size$4.width;
  6485. framebufferTexture.image.height = _size$4.height;
  6486. framebufferTexture.needsUpdate = true;
  6487. }
  6488. //
  6489. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  6490. framebufferTexture.generateMipmaps = this.generateMipmaps;
  6491. renderer.copyFramebufferToTexture( framebufferTexture );
  6492. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  6493. }
  6494. clone() {
  6495. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  6496. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  6497. return viewportTextureNode;
  6498. }
  6499. }
  6500. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode );
  6501. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } );
  6502. let sharedDepthbuffer = null;
  6503. /**
  6504. * Represents the depth of the current viewport as a texture. This module
  6505. * can be used in combination with viewport texture to achieve effects
  6506. * that require depth evaluation.
  6507. *
  6508. * @augments ViewportTextureNode
  6509. */
  6510. class ViewportDepthTextureNode extends ViewportTextureNode {
  6511. static get type() {
  6512. return 'ViewportDepthTextureNode';
  6513. }
  6514. /**
  6515. * Constructs a new viewport shared texture node.
  6516. *
  6517. * @param {Node} [uvNode=screenUV] - The uv node.
  6518. * @param {Node?} [levelNode=null] - The level node.
  6519. */
  6520. constructor( uvNode = screenUV, levelNode = null ) {
  6521. if ( sharedDepthbuffer === null ) {
  6522. sharedDepthbuffer = new DepthTexture();
  6523. }
  6524. super( uvNode, levelNode, sharedDepthbuffer );
  6525. }
  6526. }
  6527. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode );
  6528. /**
  6529. * This node offers a collection of features in context of the depth logic in the fragment shader.
  6530. * Depending on {@link ViewportDepthNode#scope}, it can be used to define a depth value for the current
  6531. * fragment or for depth evaluation purposes.
  6532. *
  6533. * @augments Node
  6534. */
  6535. class ViewportDepthNode extends Node {
  6536. static get type() {
  6537. return 'ViewportDepthNode';
  6538. }
  6539. /**
  6540. * Constructs a new viewport depth node.
  6541. *
  6542. * @param {('depth'|'depthBase'|'linearDepth')} scope - The node's scope.
  6543. * @param {Node?} [valueNode=null] - The value node.
  6544. */
  6545. constructor( scope, valueNode = null ) {
  6546. super( 'float' );
  6547. /**
  6548. * The node behaves differently depending on which scope is selected.
  6549. *
  6550. * - `ViewportDepthNode.DEPTH_BASE`: Allows to define a value for the current fragment's depth.
  6551. * - `ViewportDepthNode.DEPTH`: Represents the depth value for the current fragment (`valueNode` is ignored).
  6552. * - `ViewportDepthNode.LINEAR_DEPTH`: Represents the linear (orthographic) depth value of the current fragment.
  6553. * If a `valueNode` is set, the scope can be used to convert perspective depth data to linear data.
  6554. *
  6555. * @type {('depth'|'depthBase'|'linearDepth')}
  6556. */
  6557. this.scope = scope;
  6558. /**
  6559. * Can be used to define a custom depth value.
  6560. * The property is ignored in the `ViewportDepthNode.DEPTH` scope.
  6561. *
  6562. * @type {Node}
  6563. * @default null
  6564. */
  6565. this.valueNode = valueNode;
  6566. /**
  6567. * This flag can be used for type testing.
  6568. *
  6569. * @type {Boolean}
  6570. * @readonly
  6571. * @default true
  6572. */
  6573. this.isViewportDepthNode = true;
  6574. }
  6575. generate( builder ) {
  6576. const { scope } = this;
  6577. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  6578. return builder.getFragDepth();
  6579. }
  6580. return super.generate( builder );
  6581. }
  6582. setup( { camera } ) {
  6583. const { scope } = this;
  6584. const value = this.valueNode;
  6585. let node = null;
  6586. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  6587. if ( value !== null ) {
  6588. node = depthBase().assign( value );
  6589. }
  6590. } else if ( scope === ViewportDepthNode.DEPTH ) {
  6591. if ( camera.isPerspectiveCamera ) {
  6592. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  6593. } else {
  6594. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  6595. }
  6596. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  6597. if ( value !== null ) {
  6598. if ( camera.isPerspectiveCamera ) {
  6599. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  6600. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  6601. } else {
  6602. node = value;
  6603. }
  6604. } else {
  6605. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  6606. }
  6607. }
  6608. return node;
  6609. }
  6610. }
  6611. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  6612. ViewportDepthNode.DEPTH = 'depth';
  6613. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  6614. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  6615. // -near maps to 0; -far maps to 1
  6616. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  6617. // maps orthographic depth in [ 0, 1 ] to viewZ
  6618. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  6619. // NOTE: https://twitter.com/gonnavis/status/1377183786949959682
  6620. // -near maps to 0; -far maps to 1
  6621. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  6622. // maps perspective depth in [ 0, 1 ] to viewZ
  6623. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  6624. // -near maps to 0; -far maps to 1
  6625. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  6626. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  6627. // The final logarithmic depth formula used here is adapted from one described in an
  6628. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  6629. // which was an improvement upon an earlier formula one described in an
  6630. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  6631. // Ulrich's formula is the following:
  6632. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  6633. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  6634. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  6635. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  6636. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  6637. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  6638. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  6639. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  6640. // be used, and ultimately Ulrich's "near plane" version was chosen.
  6641. // Outerra eventually made another improvement to their original "C-constant" variant,
  6642. // but it still does not incorporate the camera near plane (for this version,
  6643. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  6644. // Here we make 4 changes to Ulrich's formula:
  6645. // 1. Clamp the camera near plane so we don't divide by 0.
  6646. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  6647. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  6648. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  6649. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  6650. // so we do the same here, hence the 'viewZ.negate()' call.
  6651. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  6652. near = near.max( 1e-6 ).toVar();
  6653. const numerator = log2( viewZ.negate().div( near ) );
  6654. const denominator = log2( far.div( near ) );
  6655. return numerator.div( denominator );
  6656. };
  6657. // maps logarithmic depth in [ 0, 1 ] to viewZ
  6658. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  6659. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  6660. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  6661. // a negative viewZ).
  6662. const exponent = depth.mul( log( far.div( near ) ) );
  6663. return float( Math.E ).pow( exponent ).mul( near ).negate();
  6664. };
  6665. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  6666. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  6667. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH );
  6668. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  6669. depth.assign = ( value ) => depthBase( value );
  6670. class BuiltinNode extends Node {
  6671. constructor( name ) {
  6672. super( 'float' );
  6673. this.name = name;
  6674. this.isBuiltinNode = true;
  6675. }
  6676. generate( /* builder */ ) {
  6677. return this.name;
  6678. }
  6679. }
  6680. const builtin = nodeProxy( BuiltinNode );
  6681. class ClippingNode extends Node {
  6682. static get type() {
  6683. return 'ClippingNode';
  6684. }
  6685. constructor( scope = ClippingNode.DEFAULT ) {
  6686. super();
  6687. this.scope = scope;
  6688. }
  6689. setup( builder ) {
  6690. super.setup( builder );
  6691. const clippingContext = builder.clippingContext;
  6692. const { intersectionPlanes, unionPlanes } = clippingContext;
  6693. this.hardwareClipping = builder.material.hardwareClipping;
  6694. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  6695. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  6696. } else if ( this.scope === ClippingNode.HARDWARE ) {
  6697. return this.setupHardwareClipping( unionPlanes, builder );
  6698. } else {
  6699. return this.setupDefault( intersectionPlanes, unionPlanes );
  6700. }
  6701. }
  6702. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  6703. return Fn( () => {
  6704. const distanceToPlane = float().toVar( 'distanceToPlane' );
  6705. const distanceGradient = float().toVar( 'distanceToGradient' );
  6706. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  6707. const numUnionPlanes = unionPlanes.length;
  6708. if ( ! this.hardwareClipping && numUnionPlanes > 0 ) {
  6709. const clippingPlanes = uniformArray( unionPlanes );
  6710. Loop( numUnionPlanes, ( { i } ) => {
  6711. const plane = clippingPlanes.element( i );
  6712. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  6713. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  6714. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  6715. } );
  6716. }
  6717. const numIntersectionPlanes = intersectionPlanes.length;
  6718. if ( numIntersectionPlanes > 0 ) {
  6719. const clippingPlanes = uniformArray( intersectionPlanes );
  6720. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  6721. Loop( numIntersectionPlanes, ( { i } ) => {
  6722. const plane = clippingPlanes.element( i );
  6723. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  6724. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  6725. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  6726. } );
  6727. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  6728. }
  6729. diffuseColor.a.mulAssign( clipOpacity );
  6730. diffuseColor.a.equal( 0.0 ).discard();
  6731. } )();
  6732. }
  6733. setupDefault( intersectionPlanes, unionPlanes ) {
  6734. return Fn( () => {
  6735. const numUnionPlanes = unionPlanes.length;
  6736. if ( ! this.hardwareClipping && numUnionPlanes > 0 ) {
  6737. const clippingPlanes = uniformArray( unionPlanes );
  6738. Loop( numUnionPlanes, ( { i } ) => {
  6739. const plane = clippingPlanes.element( i );
  6740. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  6741. } );
  6742. }
  6743. const numIntersectionPlanes = intersectionPlanes.length;
  6744. if ( numIntersectionPlanes > 0 ) {
  6745. const clippingPlanes = uniformArray( intersectionPlanes );
  6746. const clipped = bool( true ).toVar( 'clipped' );
  6747. Loop( numIntersectionPlanes, ( { i } ) => {
  6748. const plane = clippingPlanes.element( i );
  6749. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  6750. } );
  6751. clipped.discard();
  6752. }
  6753. } )();
  6754. }
  6755. setupHardwareClipping( unionPlanes, builder ) {
  6756. const numUnionPlanes = unionPlanes.length;
  6757. builder.enableHardwareClipping( numUnionPlanes );
  6758. return Fn( () => {
  6759. const clippingPlanes = uniformArray( unionPlanes );
  6760. const hw_clip_distances = builtin( builder.getClipDistance() );
  6761. Loop( numUnionPlanes, ( { i } ) => {
  6762. const plane = clippingPlanes.element( i );
  6763. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  6764. hw_clip_distances.element( i ).assign( distance );
  6765. } );
  6766. } )();
  6767. }
  6768. }
  6769. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  6770. ClippingNode.DEFAULT = 'default';
  6771. ClippingNode.HARDWARE = 'hardware';
  6772. const clipping = () => nodeObject( new ClippingNode() );
  6773. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  6774. const hardwareClipping = () => nodeObject( new ClippingNode( ClippingNode.HARDWARE ) );
  6775. // See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  6776. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  6777. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  6778. 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 ) ) ) ) ) );
  6779. } );
  6780. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  6781. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  6782. } );
  6783. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  6784. // Find the discretized derivatives of our coordinates
  6785. const maxDeriv = max$1(
  6786. length( dFdx( position.xyz ) ),
  6787. length( dFdy( position.xyz ) )
  6788. );
  6789. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  6790. // Find two nearest log-discretized noise scales
  6791. const pixScales = vec2(
  6792. exp2( floor( log2( pixScale ) ) ),
  6793. exp2( ceil( log2( pixScale ) ) )
  6794. );
  6795. // Compute alpha thresholds at our two noise scales
  6796. const alpha = vec2(
  6797. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  6798. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  6799. );
  6800. // Factor to interpolate lerp with
  6801. const lerpFactor = fract( log2( pixScale ) );
  6802. // Interpolate alpha threshold from noise at two scales
  6803. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) );
  6804. // Pass into CDF to compute uniformly distrib threshold
  6805. const a = min$1( lerpFactor, lerpFactor.oneMinus() );
  6806. const cases = vec3(
  6807. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  6808. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  6809. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) );
  6810. // Find our final, uniformly distributed alpha threshold (ατ)
  6811. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  6812. // Avoids ατ == 0. Could also do ατ =1-ατ
  6813. return clamp( threshold, 1.0e-6, 1.0 );
  6814. } ).setLayout( {
  6815. name: 'getAlphaHashThreshold',
  6816. type: 'float',
  6817. inputs: [
  6818. { name: 'position', type: 'vec3' }
  6819. ]
  6820. } );
  6821. class NodeMaterial extends Material {
  6822. static get type() {
  6823. return 'NodeMaterial';
  6824. }
  6825. get type() {
  6826. return this.constructor.type;
  6827. }
  6828. set type( _value ) { /* */ }
  6829. constructor() {
  6830. super();
  6831. this.isNodeMaterial = true;
  6832. this.forceSinglePass = false;
  6833. this.fog = true;
  6834. this.lights = false;
  6835. this.hardwareClipping = false;
  6836. this.lightsNode = null;
  6837. this.envNode = null;
  6838. this.aoNode = null;
  6839. this.colorNode = null;
  6840. this.normalNode = null;
  6841. this.opacityNode = null;
  6842. this.backdropNode = null;
  6843. this.backdropAlphaNode = null;
  6844. this.alphaTestNode = null;
  6845. this.positionNode = null;
  6846. this.geometryNode = null;
  6847. this.depthNode = null;
  6848. this.shadowPositionNode = null;
  6849. this.receivedShadowNode = null;
  6850. this.castShadowNode = null;
  6851. this.outputNode = null;
  6852. this.mrtNode = null;
  6853. this.fragmentNode = null;
  6854. this.vertexNode = null;
  6855. }
  6856. customProgramCacheKey() {
  6857. return this.type + getCacheKey$1( this );
  6858. }
  6859. build( builder ) {
  6860. this.setup( builder );
  6861. }
  6862. setupObserver( builder ) {
  6863. return new NodeMaterialObserver( builder );
  6864. }
  6865. setup( builder ) {
  6866. builder.context.setupNormal = () => this.setupNormal( builder );
  6867. const renderer = builder.renderer;
  6868. const renderTarget = renderer.getRenderTarget();
  6869. // < VERTEX STAGE >
  6870. builder.addStack();
  6871. builder.stack.outputNode = this.vertexNode || this.setupPosition( builder );
  6872. if ( this.geometryNode !== null ) {
  6873. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  6874. }
  6875. builder.addFlow( 'vertex', builder.removeStack() );
  6876. // < FRAGMENT STAGE >
  6877. builder.addStack();
  6878. let resultNode;
  6879. const clippingNode = this.setupClipping( builder );
  6880. if ( this.depthWrite === true ) {
  6881. // only write depth if depth buffer is configured
  6882. if ( renderTarget !== null ) {
  6883. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  6884. } else {
  6885. if ( renderer.depth === true ) this.setupDepth( builder );
  6886. }
  6887. }
  6888. if ( this.fragmentNode === null ) {
  6889. this.setupDiffuseColor( builder );
  6890. this.setupVariants( builder );
  6891. const outgoingLightNode = this.setupLighting( builder );
  6892. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  6893. // force unsigned floats - useful for RenderTargets
  6894. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  6895. resultNode = this.setupOutput( builder, basicOutput );
  6896. // OUTPUT NODE
  6897. output.assign( resultNode );
  6898. //
  6899. if ( this.outputNode !== null ) resultNode = this.outputNode;
  6900. // MRT
  6901. if ( renderTarget !== null ) {
  6902. const mrt = renderer.getMRT();
  6903. const materialMRT = this.mrtNode;
  6904. if ( mrt !== null ) {
  6905. resultNode = mrt;
  6906. if ( materialMRT !== null ) {
  6907. resultNode = mrt.merge( materialMRT );
  6908. }
  6909. } else if ( materialMRT !== null ) {
  6910. resultNode = materialMRT;
  6911. }
  6912. }
  6913. } else {
  6914. let fragmentNode = this.fragmentNode;
  6915. if ( fragmentNode.isOutputStructNode !== true ) {
  6916. fragmentNode = vec4( fragmentNode );
  6917. }
  6918. resultNode = this.setupOutput( builder, fragmentNode );
  6919. }
  6920. builder.stack.outputNode = resultNode;
  6921. builder.addFlow( 'fragment', builder.removeStack() );
  6922. // < MONITOR >
  6923. builder.monitor = this.setupObserver( builder );
  6924. }
  6925. setupClipping( builder ) {
  6926. if ( builder.clippingContext === null ) return null;
  6927. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  6928. let result = null;
  6929. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  6930. const samples = builder.renderer.samples;
  6931. if ( this.alphaToCoverage && samples > 1 ) {
  6932. // to be added to flow when the color/alpha value has been determined
  6933. result = clippingAlpha();
  6934. } else {
  6935. builder.stack.add( clipping() );
  6936. }
  6937. }
  6938. return result;
  6939. }
  6940. setupHardwareClipping( builder ) {
  6941. this.hardwareClipping = false;
  6942. if ( builder.clippingContext === null ) return;
  6943. const candidateCount = builder.clippingContext.unionPlanes.length;
  6944. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  6945. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  6946. builder.stack.add( hardwareClipping() );
  6947. this.hardwareClipping = true;
  6948. }
  6949. return;
  6950. }
  6951. setupDepth( builder ) {
  6952. const { renderer, camera } = builder;
  6953. // Depth
  6954. let depthNode = this.depthNode;
  6955. if ( depthNode === null ) {
  6956. const mrt = renderer.getMRT();
  6957. if ( mrt && mrt.has( 'depth' ) ) {
  6958. depthNode = mrt.get( 'depth' );
  6959. } else if ( renderer.logarithmicDepthBuffer === true ) {
  6960. if ( camera.isPerspectiveCamera ) {
  6961. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  6962. } else {
  6963. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  6964. }
  6965. }
  6966. }
  6967. if ( depthNode !== null ) {
  6968. depth.assign( depthNode ).append();
  6969. }
  6970. }
  6971. setupPosition( builder ) {
  6972. const { object } = builder;
  6973. const geometry = object.geometry;
  6974. builder.addStack();
  6975. // Vertex
  6976. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  6977. morphReference( object ).append();
  6978. }
  6979. if ( object.isSkinnedMesh === true ) {
  6980. skinningReference( object ).append();
  6981. }
  6982. if ( this.displacementMap ) {
  6983. const displacementMap = materialReference( 'displacementMap', 'texture' );
  6984. const displacementScale = materialReference( 'displacementScale', 'float' );
  6985. const displacementBias = materialReference( 'displacementBias', 'float' );
  6986. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  6987. }
  6988. if ( object.isBatchedMesh ) {
  6989. batch( object ).append();
  6990. }
  6991. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  6992. instancedMesh( object ).append();
  6993. }
  6994. if ( this.positionNode !== null ) {
  6995. positionLocal.assign( this.positionNode );
  6996. }
  6997. this.setupHardwareClipping( builder );
  6998. const mvp = modelViewProjection();
  6999. builder.context.vertex = builder.removeStack();
  7000. builder.context.mvp = mvp;
  7001. return mvp;
  7002. }
  7003. setupDiffuseColor( { object, geometry } ) {
  7004. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  7005. // VERTEX COLORS
  7006. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  7007. colorNode = vec4( colorNode.xyz.mul( attribute( 'color', 'vec3' ) ), colorNode.a );
  7008. }
  7009. // Instanced colors
  7010. if ( object.instanceColor ) {
  7011. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  7012. colorNode = instanceColor.mul( colorNode );
  7013. }
  7014. if ( object.isBatchedMesh && object._colorsTexture ) {
  7015. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  7016. colorNode = batchColor.mul( colorNode );
  7017. }
  7018. // COLOR
  7019. diffuseColor.assign( colorNode );
  7020. // OPACITY
  7021. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  7022. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  7023. // ALPHA TEST
  7024. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  7025. const alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  7026. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  7027. }
  7028. // ALPHA HASH
  7029. if ( this.alphaHash === true ) {
  7030. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  7031. }
  7032. if ( this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false ) {
  7033. diffuseColor.a.assign( 1.0 );
  7034. }
  7035. }
  7036. setupVariants( /*builder*/ ) {
  7037. // Interface function.
  7038. }
  7039. setupOutgoingLight() {
  7040. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  7041. }
  7042. setupNormal() {
  7043. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  7044. }
  7045. setupEnvironment( /*builder*/ ) {
  7046. let node = null;
  7047. if ( this.envNode ) {
  7048. node = this.envNode;
  7049. } else if ( this.envMap ) {
  7050. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  7051. }
  7052. return node;
  7053. }
  7054. setupLightMap( builder ) {
  7055. let node = null;
  7056. if ( builder.material.lightMap ) {
  7057. node = new IrradianceNode( materialLightMap );
  7058. }
  7059. return node;
  7060. }
  7061. setupLights( builder ) {
  7062. const materialLightsNode = [];
  7063. //
  7064. const envNode = this.setupEnvironment( builder );
  7065. if ( envNode && envNode.isLightingNode ) {
  7066. materialLightsNode.push( envNode );
  7067. }
  7068. const lightMapNode = this.setupLightMap( builder );
  7069. if ( lightMapNode && lightMapNode.isLightingNode ) {
  7070. materialLightsNode.push( lightMapNode );
  7071. }
  7072. if ( this.aoNode !== null || builder.material.aoMap ) {
  7073. const aoNode = this.aoNode !== null ? this.aoNode : materialAOMap;
  7074. materialLightsNode.push( new AONode( aoNode ) );
  7075. }
  7076. let lightsN = this.lightsNode || builder.lightsNode;
  7077. if ( materialLightsNode.length > 0 ) {
  7078. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  7079. }
  7080. return lightsN;
  7081. }
  7082. setupLightingModel( /*builder*/ ) {
  7083. // Interface function.
  7084. }
  7085. setupLighting( builder ) {
  7086. const { material } = builder;
  7087. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  7088. // OUTGOING LIGHT
  7089. const lights = this.lights === true || this.lightsNode !== null;
  7090. const lightsNode = lights ? this.setupLights( builder ) : null;
  7091. let outgoingLightNode = this.setupOutgoingLight( builder );
  7092. if ( lightsNode && lightsNode.getScope().hasLights ) {
  7093. const lightingModel = this.setupLightingModel( builder );
  7094. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  7095. } else if ( backdropNode !== null ) {
  7096. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  7097. }
  7098. // EMISSIVE
  7099. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  7100. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  7101. outgoingLightNode = outgoingLightNode.add( emissive );
  7102. }
  7103. return outgoingLightNode;
  7104. }
  7105. setupOutput( builder, outputNode ) {
  7106. // FOG
  7107. if ( this.fog === true ) {
  7108. const fogNode = builder.fogNode;
  7109. if ( fogNode ) outputNode = vec4( fogNode.mix( outputNode.rgb, fogNode.colorNode ), outputNode.a );
  7110. }
  7111. return outputNode;
  7112. }
  7113. setDefaultValues( material ) {
  7114. // This approach is to reuse the native refreshUniforms*
  7115. // and turn available the use of features like transmission and environment in core
  7116. for ( const property in material ) {
  7117. const value = material[ property ];
  7118. if ( this[ property ] === undefined ) {
  7119. this[ property ] = value;
  7120. if ( value && value.clone ) this[ property ] = value.clone();
  7121. }
  7122. }
  7123. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  7124. for ( const key in descriptors ) {
  7125. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  7126. descriptors[ key ].get !== undefined ) {
  7127. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  7128. }
  7129. }
  7130. }
  7131. toJSON( meta ) {
  7132. const isRoot = ( meta === undefined || typeof meta === 'string' );
  7133. if ( isRoot ) {
  7134. meta = {
  7135. textures: {},
  7136. images: {},
  7137. nodes: {}
  7138. };
  7139. }
  7140. const data = Material.prototype.toJSON.call( this, meta );
  7141. const nodeChildren = getNodeChildren( this );
  7142. data.inputNodes = {};
  7143. for ( const { property, childNode } of nodeChildren ) {
  7144. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  7145. }
  7146. // TODO: Copied from Object3D.toJSON
  7147. function extractFromCache( cache ) {
  7148. const values = [];
  7149. for ( const key in cache ) {
  7150. const data = cache[ key ];
  7151. delete data.metadata;
  7152. values.push( data );
  7153. }
  7154. return values;
  7155. }
  7156. if ( isRoot ) {
  7157. const textures = extractFromCache( meta.textures );
  7158. const images = extractFromCache( meta.images );
  7159. const nodes = extractFromCache( meta.nodes );
  7160. if ( textures.length > 0 ) data.textures = textures;
  7161. if ( images.length > 0 ) data.images = images;
  7162. if ( nodes.length > 0 ) data.nodes = nodes;
  7163. }
  7164. return data;
  7165. }
  7166. copy( source ) {
  7167. this.lightsNode = source.lightsNode;
  7168. this.envNode = source.envNode;
  7169. this.colorNode = source.colorNode;
  7170. this.normalNode = source.normalNode;
  7171. this.opacityNode = source.opacityNode;
  7172. this.backdropNode = source.backdropNode;
  7173. this.backdropAlphaNode = source.backdropAlphaNode;
  7174. this.alphaTestNode = source.alphaTestNode;
  7175. this.positionNode = source.positionNode;
  7176. this.geometryNode = source.geometryNode;
  7177. this.depthNode = source.depthNode;
  7178. this.shadowPositionNode = source.shadowPositionNode;
  7179. this.receivedShadowNode = source.receivedShadowNode;
  7180. this.castShadowNode = source.castShadowNode;
  7181. this.outputNode = source.outputNode;
  7182. this.mrtNode = source.mrtNode;
  7183. this.fragmentNode = source.fragmentNode;
  7184. this.vertexNode = source.vertexNode;
  7185. return super.copy( source );
  7186. }
  7187. }
  7188. const _defaultValues$e = /*@__PURE__*/ new PointsMaterial();
  7189. class InstancedPointsNodeMaterial extends NodeMaterial {
  7190. static get type() {
  7191. return 'InstancedPointsNodeMaterial';
  7192. }
  7193. constructor( params = {} ) {
  7194. super();
  7195. this.lights = false;
  7196. this.useAlphaToCoverage = true;
  7197. this.useColor = params.vertexColors;
  7198. this.pointWidth = 1;
  7199. this.pointColorNode = null;
  7200. this.pointWidthNode = null;
  7201. this.setDefaultValues( _defaultValues$e );
  7202. this.setValues( params );
  7203. }
  7204. setup( builder ) {
  7205. this.setupShaders( builder );
  7206. super.setup( builder );
  7207. }
  7208. setupShaders( { renderer } ) {
  7209. const useAlphaToCoverage = this.alphaToCoverage;
  7210. const useColor = this.useColor;
  7211. this.vertexNode = Fn( () => {
  7212. const instancePosition = attribute( 'instancePosition' ).xyz;
  7213. // camera space
  7214. const mvPos = vec4( modelViewMatrix.mul( vec4( instancePosition, 1.0 ) ) );
  7215. const aspect = viewport.z.div( viewport.w );
  7216. // clip space
  7217. const clipPos = cameraProjectionMatrix.mul( mvPos );
  7218. // offset in ndc space
  7219. const offset = positionGeometry.xy.toVar();
  7220. offset.mulAssign( this.pointWidthNode ? this.pointWidthNode : materialPointWidth );
  7221. offset.assign( offset.div( viewport.z ) );
  7222. offset.y.assign( offset.y.mul( aspect ) );
  7223. // back to clip space
  7224. offset.assign( offset.mul( clipPos.w ) );
  7225. //clipPos.xy += offset;
  7226. clipPos.addAssign( vec4( offset, 0, 0 ) );
  7227. return clipPos;
  7228. } )();
  7229. this.fragmentNode = Fn( () => {
  7230. const alpha = float( 1 ).toVar();
  7231. const len2 = lengthSq( uv().mul( 2 ).sub( 1 ) );
  7232. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  7233. const dlen = float( len2.fwidth() ).toVar();
  7234. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  7235. } else {
  7236. len2.greaterThan( 1.0 ).discard();
  7237. }
  7238. let pointColorNode;
  7239. if ( this.pointColorNode ) {
  7240. pointColorNode = this.pointColorNode;
  7241. } else {
  7242. if ( useColor ) {
  7243. const instanceColor = attribute( 'instanceColor' );
  7244. pointColorNode = instanceColor.mul( materialColor );
  7245. } else {
  7246. pointColorNode = materialColor;
  7247. }
  7248. }
  7249. alpha.mulAssign( materialOpacity );
  7250. return vec4( pointColorNode, alpha );
  7251. } )();
  7252. }
  7253. get alphaToCoverage() {
  7254. return this.useAlphaToCoverage;
  7255. }
  7256. set alphaToCoverage( value ) {
  7257. if ( this.useAlphaToCoverage !== value ) {
  7258. this.useAlphaToCoverage = value;
  7259. this.needsUpdate = true;
  7260. }
  7261. }
  7262. }
  7263. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  7264. class LineBasicNodeMaterial extends NodeMaterial {
  7265. static get type() {
  7266. return 'LineBasicNodeMaterial';
  7267. }
  7268. constructor( parameters ) {
  7269. super();
  7270. this.isLineBasicNodeMaterial = true;
  7271. this.lights = false;
  7272. this.setDefaultValues( _defaultValues$d );
  7273. this.setValues( parameters );
  7274. }
  7275. }
  7276. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  7277. class LineDashedNodeMaterial extends NodeMaterial {
  7278. static get type() {
  7279. return 'LineDashedNodeMaterial';
  7280. }
  7281. constructor( parameters ) {
  7282. super();
  7283. this.isLineDashedNodeMaterial = true;
  7284. this.lights = false;
  7285. this.setDefaultValues( _defaultValues$c );
  7286. this.dashOffset = 0;
  7287. this.offsetNode = null;
  7288. this.dashScaleNode = null;
  7289. this.dashSizeNode = null;
  7290. this.gapSizeNode = null;
  7291. this.setValues( parameters );
  7292. }
  7293. setupVariants() {
  7294. const offsetNode = this.offsetNode ? float( this.offsetNodeNode ) : materialLineDashOffset;
  7295. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  7296. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  7297. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  7298. dashSize.assign( dashSizeNode );
  7299. gapSize.assign( gapSizeNode );
  7300. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  7301. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  7302. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  7303. }
  7304. }
  7305. let _sharedFramebuffer = null;
  7306. /**
  7307. * `ViewportTextureNode` creates an internal texture for each node instance. This module
  7308. * shares a texture across all instances of `ViewportSharedTextureNode`. It should
  7309. * be the first choice when using data of the default/screen framebuffer for performance reasons.
  7310. *
  7311. * @augments ViewportTextureNode
  7312. */
  7313. class ViewportSharedTextureNode extends ViewportTextureNode {
  7314. static get type() {
  7315. return 'ViewportSharedTextureNode';
  7316. }
  7317. /**
  7318. * Constructs a new viewport shared texture node.
  7319. *
  7320. * @param {Node} [uvNode=screenUV] - The uv node.
  7321. * @param {Node?} [levelNode=null] - The level node.
  7322. */
  7323. constructor( uvNode = screenUV, levelNode = null ) {
  7324. if ( _sharedFramebuffer === null ) {
  7325. _sharedFramebuffer = new FramebufferTexture();
  7326. }
  7327. super( uvNode, levelNode, _sharedFramebuffer );
  7328. }
  7329. updateReference() {
  7330. return this;
  7331. }
  7332. }
  7333. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode );
  7334. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  7335. class Line2NodeMaterial extends NodeMaterial {
  7336. static get type() {
  7337. return 'Line2NodeMaterial';
  7338. }
  7339. constructor( params = {} ) {
  7340. super();
  7341. this.lights = false;
  7342. this.setDefaultValues( _defaultValues$b );
  7343. this.useAlphaToCoverage = true;
  7344. this.useColor = params.vertexColors;
  7345. this.useDash = params.dashed;
  7346. this.useWorldUnits = false;
  7347. this.dashOffset = 0;
  7348. this.lineWidth = 1;
  7349. this.lineColorNode = null;
  7350. this.offsetNode = null;
  7351. this.dashScaleNode = null;
  7352. this.dashSizeNode = null;
  7353. this.gapSizeNode = null;
  7354. this.blending = NoBlending;
  7355. this.setValues( params );
  7356. }
  7357. setup( builder ) {
  7358. this.setupShaders( builder );
  7359. super.setup( builder );
  7360. }
  7361. setupShaders( { renderer } ) {
  7362. const useAlphaToCoverage = this.alphaToCoverage;
  7363. const useColor = this.useColor;
  7364. const useDash = this.dashed;
  7365. const useWorldUnits = this.worldUnits;
  7366. const trimSegment = Fn( ( { start, end } ) => {
  7367. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  7368. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  7369. const nearEstimate = b.mul( - 0.5 ).div( a );
  7370. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  7371. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  7372. } ).setLayout( {
  7373. name: 'trimSegment',
  7374. type: 'vec4',
  7375. inputs: [
  7376. { name: 'start', type: 'vec4' },
  7377. { name: 'end', type: 'vec4' }
  7378. ]
  7379. } );
  7380. this.vertexNode = Fn( () => {
  7381. const instanceStart = attribute( 'instanceStart' );
  7382. const instanceEnd = attribute( 'instanceEnd' );
  7383. // camera space
  7384. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  7385. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  7386. if ( useDash ) {
  7387. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  7388. const offsetNode = this.offsetNode ? float( this.offsetNodeNode ) : materialLineDashOffset;
  7389. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  7390. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  7391. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  7392. lineDistance = lineDistance.add( offsetNode );
  7393. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  7394. }
  7395. if ( useWorldUnits ) {
  7396. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  7397. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  7398. }
  7399. const aspect = viewport.z.div( viewport.w );
  7400. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  7401. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  7402. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  7403. // perhaps there is a more elegant solution -- WestLangley
  7404. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( - 1.0 ); // 4th entry in the 3rd column
  7405. If( perspective, () => {
  7406. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  7407. end.assign( trimSegment( { start: start, end: end } ) );
  7408. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  7409. start.assign( trimSegment( { start: end, end: start } ) );
  7410. } );
  7411. } );
  7412. // clip space
  7413. const clipStart = cameraProjectionMatrix.mul( start );
  7414. const clipEnd = cameraProjectionMatrix.mul( end );
  7415. // ndc space
  7416. const ndcStart = clipStart.xyz.div( clipStart.w );
  7417. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  7418. // direction
  7419. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  7420. // account for clip-space aspect ratio
  7421. dir.x.assign( dir.x.mul( aspect ) );
  7422. dir.assign( dir.normalize() );
  7423. const clip = vec4().toVar();
  7424. if ( useWorldUnits ) {
  7425. // get the offset direction as perpendicular to the view vector
  7426. const worldDir = end.xyz.sub( start.xyz ).normalize();
  7427. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  7428. const worldUp = worldDir.cross( tmpFwd ).normalize();
  7429. const worldFwd = worldDir.cross( worldUp );
  7430. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  7431. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  7432. // height offset
  7433. const hw = materialLineWidth.mul( 0.5 );
  7434. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  7435. // don't extend the line if we're rendering dashes because we
  7436. // won't be rendering the endcaps
  7437. if ( ! useDash ) {
  7438. // cap extension
  7439. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  7440. // add width to the box
  7441. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  7442. // endcaps
  7443. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  7444. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  7445. } );
  7446. }
  7447. // project the worldpos
  7448. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  7449. // shift the depth of the projected points so the line
  7450. // segments overlap neatly
  7451. const clipPose = vec3().toVar();
  7452. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  7453. clip.z.assign( clipPose.z.mul( clip.w ) );
  7454. } else {
  7455. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  7456. // undo aspect ratio adjustment
  7457. dir.x.assign( dir.x.div( aspect ) );
  7458. offset.x.assign( offset.x.div( aspect ) );
  7459. // sign flip
  7460. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  7461. // endcaps
  7462. If( positionGeometry.y.lessThan( 0.0 ), () => {
  7463. offset.assign( offset.sub( dir ) );
  7464. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  7465. offset.assign( offset.add( dir ) );
  7466. } );
  7467. // adjust for linewidth
  7468. offset.assign( offset.mul( materialLineWidth ) );
  7469. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  7470. offset.assign( offset.div( viewport.w ) );
  7471. // select end
  7472. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  7473. // back to clip space
  7474. offset.assign( offset.mul( clip.w ) );
  7475. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  7476. }
  7477. return clip;
  7478. } )();
  7479. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  7480. const p13 = p1.sub( p3 );
  7481. const p43 = p4.sub( p3 );
  7482. const p21 = p2.sub( p1 );
  7483. const d1343 = p13.dot( p43 );
  7484. const d4321 = p43.dot( p21 );
  7485. const d1321 = p13.dot( p21 );
  7486. const d4343 = p43.dot( p43 );
  7487. const d2121 = p21.dot( p21 );
  7488. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  7489. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  7490. const mua = numer.div( denom ).clamp();
  7491. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  7492. return vec2( mua, mub );
  7493. } );
  7494. this.colorNode = Fn( () => {
  7495. const vUv = uv();
  7496. if ( useDash ) {
  7497. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  7498. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  7499. dashSize.assign( dashSizeNode );
  7500. gapSize.assign( gapSizeNode );
  7501. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  7502. vUv.y.lessThan( - 1.0 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  7503. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  7504. }
  7505. const alpha = float( 1 ).toVar( 'alpha' );
  7506. if ( useWorldUnits ) {
  7507. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  7508. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  7509. // Find the closest points on the view ray and the line segment
  7510. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  7511. const lineDir = worldEnd.sub( worldStart );
  7512. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  7513. const p1 = worldStart.add( lineDir.mul( params.x ) );
  7514. const p2 = rayEnd.mul( params.y );
  7515. const delta = p1.sub( p2 );
  7516. const len = delta.length();
  7517. const norm = len.div( materialLineWidth );
  7518. if ( ! useDash ) {
  7519. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  7520. const dnorm = norm.fwidth();
  7521. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  7522. } else {
  7523. norm.greaterThan( 0.5 ).discard();
  7524. }
  7525. }
  7526. } else {
  7527. // round endcaps
  7528. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  7529. const a = vUv.x;
  7530. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  7531. const len2 = a.mul( a ).add( b.mul( b ) );
  7532. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  7533. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  7534. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  7535. } );
  7536. } else {
  7537. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  7538. const a = vUv.x;
  7539. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  7540. const len2 = a.mul( a ).add( b.mul( b ) );
  7541. len2.greaterThan( 1.0 ).discard();
  7542. } );
  7543. }
  7544. }
  7545. let lineColorNode;
  7546. if ( this.lineColorNode ) {
  7547. lineColorNode = this.lineColorNode;
  7548. } else {
  7549. if ( useColor ) {
  7550. const instanceColorStart = attribute( 'instanceColorStart' );
  7551. const instanceColorEnd = attribute( 'instanceColorEnd' );
  7552. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  7553. lineColorNode = instanceColor.mul( materialColor );
  7554. } else {
  7555. lineColorNode = materialColor;
  7556. }
  7557. }
  7558. return vec4( lineColorNode, alpha );
  7559. } )();
  7560. if ( this.transparent ) {
  7561. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  7562. this.outputNode = vec4( this.colorNode.rgb.mul( opacityNode ).add( viewportSharedTexture().rgb.mul( opacityNode.oneMinus() ) ), this.colorNode.a );
  7563. }
  7564. }
  7565. get worldUnits() {
  7566. return this.useWorldUnits;
  7567. }
  7568. set worldUnits( value ) {
  7569. if ( this.useWorldUnits !== value ) {
  7570. this.useWorldUnits = value;
  7571. this.needsUpdate = true;
  7572. }
  7573. }
  7574. get dashed() {
  7575. return this.useDash;
  7576. }
  7577. set dashed( value ) {
  7578. if ( this.useDash !== value ) {
  7579. this.useDash = value;
  7580. this.needsUpdate = true;
  7581. }
  7582. }
  7583. get alphaToCoverage() {
  7584. return this.useAlphaToCoverage;
  7585. }
  7586. set alphaToCoverage( value ) {
  7587. if ( this.useAlphaToCoverage !== value ) {
  7588. this.useAlphaToCoverage = value;
  7589. this.needsUpdate = true;
  7590. }
  7591. }
  7592. }
  7593. /** @module Packing **/
  7594. /**
  7595. * Packs a direction vector into a color value.
  7596. *
  7597. * @method
  7598. * @param {Node<vec3>} node - The direction to pack.
  7599. * @return {Node<vec3>} The color.
  7600. */
  7601. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  7602. /**
  7603. * Unpacks a color value into a direction vector.
  7604. *
  7605. * @method
  7606. * @param {Node<vec3>} color - The color to unpack.
  7607. * @return {Node<vec3>} The direction.
  7608. */
  7609. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  7610. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  7611. class MeshNormalNodeMaterial extends NodeMaterial {
  7612. static get type() {
  7613. return 'MeshNormalNodeMaterial';
  7614. }
  7615. constructor( parameters ) {
  7616. super();
  7617. this.lights = false;
  7618. this.isMeshNormalNodeMaterial = true;
  7619. this.setDefaultValues( _defaultValues$a );
  7620. this.setValues( parameters );
  7621. }
  7622. setupDiffuseColor() {
  7623. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  7624. diffuseColor.assign( vec4( directionToColor( transformedNormalView ), opacityNode ) );
  7625. }
  7626. }
  7627. /**
  7628. * Can be used to compute texture coordinates for projecting an
  7629. * equirectangular texture onto a mesh for using it as the scene's
  7630. * background.
  7631. *
  7632. * ```js
  7633. * scene.backgroundNode = texture( equirectTexture, equirectUV() );
  7634. * ```
  7635. *
  7636. * @augments TempNode
  7637. */
  7638. class EquirectUVNode extends TempNode {
  7639. static get type() {
  7640. return 'EquirectUVNode';
  7641. }
  7642. /**
  7643. * Constructs a new equirect uv node.
  7644. *
  7645. * @param {Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling why is by default `positionWorldDirection`.
  7646. */
  7647. constructor( dirNode = positionWorldDirection ) {
  7648. super( 'vec2' );
  7649. /**
  7650. * A direction vector for sampling why is by default `positionWorldDirection`.
  7651. *
  7652. * @type {Node<vec3>}
  7653. */
  7654. this.dirNode = dirNode;
  7655. }
  7656. setup() {
  7657. const dir = this.dirNode;
  7658. const u = dir.z.atan2( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  7659. const v = dir.y.clamp( - 1.0, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  7660. return vec2( u, v );
  7661. }
  7662. }
  7663. const equirectUV = /*@__PURE__*/ nodeProxy( EquirectUVNode );
  7664. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  7665. class CubeRenderTarget extends WebGLCubeRenderTarget {
  7666. constructor( size = 1, options = {} ) {
  7667. super( size, options );
  7668. this.isCubeRenderTarget = true;
  7669. }
  7670. fromEquirectangularTexture( renderer, texture$1 ) {
  7671. const currentMinFilter = texture$1.minFilter;
  7672. const currentGenerateMipmaps = texture$1.generateMipmaps;
  7673. texture$1.generateMipmaps = true;
  7674. this.texture.type = texture$1.type;
  7675. this.texture.colorSpace = texture$1.colorSpace;
  7676. this.texture.generateMipmaps = texture$1.generateMipmaps;
  7677. this.texture.minFilter = texture$1.minFilter;
  7678. this.texture.magFilter = texture$1.magFilter;
  7679. const geometry = new BoxGeometry( 5, 5, 5 );
  7680. const uvNode = equirectUV( positionWorldDirection );
  7681. const material = new NodeMaterial();
  7682. material.colorNode = texture( texture$1, uvNode, 0 );
  7683. material.side = BackSide;
  7684. material.blending = NoBlending;
  7685. const mesh = new Mesh( geometry, material );
  7686. const scene = new Scene();
  7687. scene.add( mesh );
  7688. // Avoid blurred poles
  7689. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  7690. const camera = new CubeCamera( 1, 10, this );
  7691. const currentMRT = renderer.getMRT();
  7692. renderer.setMRT( null );
  7693. camera.update( renderer, scene );
  7694. renderer.setMRT( currentMRT );
  7695. texture$1.minFilter = currentMinFilter;
  7696. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  7697. mesh.geometry.dispose();
  7698. mesh.material.dispose();
  7699. return this;
  7700. }
  7701. }
  7702. const _cache$1 = new WeakMap();
  7703. /**
  7704. * This node can be used to automatically convert environment maps in the
  7705. * equirectangular format into the cube map format.
  7706. *
  7707. * @augments TempNode
  7708. */
  7709. class CubeMapNode extends TempNode {
  7710. static get type() {
  7711. return 'CubeMapNode';
  7712. }
  7713. /**
  7714. * Constructs a new cube map node.
  7715. *
  7716. * @param {Node} envNode - The node representing the environment map.
  7717. */
  7718. constructor( envNode ) {
  7719. super( 'vec3' );
  7720. /**
  7721. * The node representing the environment map.
  7722. *
  7723. * @type {Node}
  7724. */
  7725. this.envNode = envNode;
  7726. /**
  7727. * A reference to the internal cube texture.
  7728. *
  7729. * @private
  7730. * @type {CubeTexture}
  7731. * @default null
  7732. */
  7733. this._cubeTexture = null;
  7734. /**
  7735. * A reference to the internal cube texture node.
  7736. *
  7737. * @private
  7738. * @type {CubeTextureNode}
  7739. */
  7740. this._cubeTextureNode = cubeTexture();
  7741. const defaultTexture = new CubeTexture();
  7742. defaultTexture.isRenderTargetTexture = true;
  7743. /**
  7744. * A default cube texture that acts as a placeholder.
  7745. * It is used when the conversion from equirectangular to cube
  7746. * map has not finished yet for a given texture.
  7747. *
  7748. * @private
  7749. * @type {CubeTexture}
  7750. */
  7751. this._defaultTexture = defaultTexture;
  7752. /**
  7753. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  7754. * the texture once per render in its {@link CubeMapNode#updateBefore} method.
  7755. *
  7756. * @type {String}
  7757. * @default 'render'
  7758. */
  7759. this.updateBeforeType = NodeUpdateType.RENDER;
  7760. }
  7761. updateBefore( frame ) {
  7762. const { renderer, material } = frame;
  7763. const envNode = this.envNode;
  7764. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  7765. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  7766. if ( texture && texture.isTexture ) {
  7767. const mapping = texture.mapping;
  7768. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  7769. // check for converted cubemap map
  7770. if ( _cache$1.has( texture ) ) {
  7771. const cubeMap = _cache$1.get( texture );
  7772. mapTextureMapping( cubeMap, texture.mapping );
  7773. this._cubeTexture = cubeMap;
  7774. } else {
  7775. // create cube map from equirectangular map
  7776. const image = texture.image;
  7777. if ( isEquirectangularMapReady$1( image ) ) {
  7778. const renderTarget = new CubeRenderTarget( image.height );
  7779. renderTarget.fromEquirectangularTexture( renderer, texture );
  7780. mapTextureMapping( renderTarget.texture, texture.mapping );
  7781. this._cubeTexture = renderTarget.texture;
  7782. _cache$1.set( texture, renderTarget.texture );
  7783. texture.addEventListener( 'dispose', onTextureDispose );
  7784. } else {
  7785. // default cube texture as fallback when equirectangular texture is not yet loaded
  7786. this._cubeTexture = this._defaultTexture;
  7787. }
  7788. }
  7789. //
  7790. this._cubeTextureNode.value = this._cubeTexture;
  7791. } else {
  7792. // envNode already refers to a cube map
  7793. this._cubeTextureNode = this.envNode;
  7794. }
  7795. }
  7796. }
  7797. }
  7798. setup( builder ) {
  7799. this.updateBefore( builder );
  7800. return this._cubeTextureNode;
  7801. }
  7802. }
  7803. /**
  7804. * Returns true if the given equirectangular image has been fully loaded
  7805. * and is ready for further processing.
  7806. *
  7807. * @private
  7808. * @param {Image} image - The equirectangular image to check.
  7809. * @return {Boolean} Whether the image is ready or not.
  7810. */
  7811. function isEquirectangularMapReady$1( image ) {
  7812. if ( image === null || image === undefined ) return false;
  7813. return image.height > 0;
  7814. }
  7815. /**
  7816. * This function is executed when `dispose()` is called on the equirectangular
  7817. * texture. In this case, the generated cube map with its render target
  7818. * is deleted as well.
  7819. *
  7820. * @private
  7821. * @param {Object} event - The event object.
  7822. */
  7823. function onTextureDispose( event ) {
  7824. const texture = event.target;
  7825. texture.removeEventListener( 'dispose', onTextureDispose );
  7826. const renderTarget = _cache$1.get( texture );
  7827. if ( renderTarget !== undefined ) {
  7828. _cache$1.delete( texture );
  7829. renderTarget.dispose();
  7830. }
  7831. }
  7832. /**
  7833. * This function makes sure the generated cube map uses the correct
  7834. * texture mapping that corresponds to the equirectangular original.
  7835. *
  7836. * @private
  7837. * @param {Texture} texture - The cube texture.
  7838. * @param {Number} mapping - The original texture mapping.
  7839. */
  7840. function mapTextureMapping( texture, mapping ) {
  7841. if ( mapping === EquirectangularReflectionMapping ) {
  7842. texture.mapping = CubeReflectionMapping;
  7843. } else if ( mapping === EquirectangularRefractionMapping ) {
  7844. texture.mapping = CubeRefractionMapping;
  7845. }
  7846. }
  7847. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode );
  7848. class BasicEnvironmentNode extends LightingNode {
  7849. static get type() {
  7850. return 'BasicEnvironmentNode';
  7851. }
  7852. constructor( envNode = null ) {
  7853. super();
  7854. this.envNode = envNode;
  7855. }
  7856. setup( builder ) {
  7857. // environment property is used in the finish() method of BasicLightingModel
  7858. builder.context.environment = cubeMapNode( this.envNode );
  7859. }
  7860. }
  7861. class BasicLightMapNode extends LightingNode {
  7862. static get type() {
  7863. return 'BasicLightMapNode';
  7864. }
  7865. constructor( lightMapNode = null ) {
  7866. super();
  7867. this.lightMapNode = lightMapNode;
  7868. }
  7869. setup( builder ) {
  7870. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  7871. const RECIPROCAL_PI = float( 1 / Math.PI );
  7872. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  7873. }
  7874. }
  7875. /**
  7876. * Abstract class for implementing lighting models. The module defines
  7877. * multiple methods that concrete lighting models can implement. These
  7878. * methods are executed at different points during the light evaluation
  7879. * process.
  7880. */
  7881. class LightingModel {
  7882. /**
  7883. * This method is intended for setting up lighting model and context data
  7884. * which are later used in the evaluation process.
  7885. *
  7886. * @abstract
  7887. * @param {ContextNode} input - The current node context.
  7888. * @param {StackNode} stack - The current stack.
  7889. * @param {NodeBuilder} builder - The current node builder.
  7890. */
  7891. start( /*input, stack, builder*/ ) { }
  7892. /**
  7893. * This method is intended for executing final tasks like final updates
  7894. * to the outgoing light.
  7895. *
  7896. * @abstract
  7897. * @param {ContextNode} input - The current node context.
  7898. * @param {StackNode} stack - The current stack.
  7899. * @param {NodeBuilder} builder - The current node builder.
  7900. */
  7901. finish( /*input, stack, builder*/ ) { }
  7902. /**
  7903. * This method is intended for implementing the direct light term and
  7904. * executed during the build process of directional, point and spot light nodes.
  7905. *
  7906. * @abstract
  7907. * @param {Object} input - The input data.
  7908. * @param {StackNode} stack - The current stack.
  7909. * @param {NodeBuilder} builder - The current node builder.
  7910. */
  7911. direct( /*input, stack, builder*/ ) { }
  7912. /**
  7913. * This method is intended for implementing the direct light term for
  7914. * rect area light nodes.
  7915. *
  7916. * @abstract
  7917. * @param {Object} input - The input data.
  7918. * @param {StackNode} stack - The current stack.
  7919. * @param {NodeBuilder} builder - The current node builder.
  7920. */
  7921. directRectArea( /*input, stack, builder*/ ) {}
  7922. /**
  7923. * This method is intended for implementing the indirect light term.
  7924. *
  7925. * @abstract
  7926. * @param {ContextNode} input - The current node context.
  7927. * @param {StackNode} stack - The current stack.
  7928. * @param {NodeBuilder} builder - The current node builder.
  7929. */
  7930. indirect( /*input, stack, builder*/ ) { }
  7931. /**
  7932. * This method is intended for implementing the ambient occlusion term.
  7933. * Unlike other methods, this method must be called manually by the lighting
  7934. * model in its indirect term.
  7935. *
  7936. * @abstract
  7937. * @param {ContextNode} input - The current node context.
  7938. * @param {StackNode} stack - The current stack.
  7939. * @param {NodeBuilder} builder - The current node builder.
  7940. */
  7941. ambientOcclusion( /*input, stack, builder*/ ) { }
  7942. }
  7943. /**
  7944. * Represents the lighting model for unlit materials. The only light contribution
  7945. * is baked indirect lighting modulated with ambient occlusion and the material's
  7946. * diffuse color. Environment mapping is supported. Used in {@link MeshBasicNodeMaterial}.
  7947. *
  7948. * @augments LightingModel
  7949. */
  7950. class BasicLightingModel extends LightingModel {
  7951. /**
  7952. * Constructs a new basic lighting model.
  7953. */
  7954. constructor() {
  7955. super();
  7956. }
  7957. /**
  7958. * Implements the baked indirect lighting with its modulation.
  7959. *
  7960. * @param {ContextNode} input - The current node context.
  7961. * @param {StackNode} stack - The current stack.
  7962. * @param {NodeBuilder} builder - The current node builder.
  7963. */
  7964. indirect( context, stack, builder ) {
  7965. const ambientOcclusion = context.ambientOcclusion;
  7966. const reflectedLight = context.reflectedLight;
  7967. const irradianceLightMap = builder.context.irradianceLightMap;
  7968. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  7969. // accumulation (baked indirect lighting only)
  7970. if ( irradianceLightMap ) {
  7971. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  7972. } else {
  7973. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  7974. }
  7975. // modulation
  7976. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  7977. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  7978. }
  7979. /**
  7980. * Implements the environment mapping.
  7981. *
  7982. * @param {ContextNode} input - The current node context.
  7983. * @param {StackNode} stack - The current stack.
  7984. * @param {NodeBuilder} builder - The current node builder.
  7985. */
  7986. finish( context, stack, builder ) {
  7987. const material = builder.material;
  7988. const outgoingLight = context.outgoingLight;
  7989. const envNode = builder.context.environment;
  7990. if ( envNode ) {
  7991. switch ( material.combine ) {
  7992. case MultiplyOperation:
  7993. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  7994. break;
  7995. case MixOperation:
  7996. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  7997. break;
  7998. case AddOperation:
  7999. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  8000. break;
  8001. default:
  8002. console.warn( 'THREE.BasicLightingModel: Unsupported .combine value:', material.combine );
  8003. break;
  8004. }
  8005. }
  8006. }
  8007. }
  8008. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  8009. class MeshBasicNodeMaterial extends NodeMaterial {
  8010. static get type() {
  8011. return 'MeshBasicNodeMaterial';
  8012. }
  8013. constructor( parameters ) {
  8014. super();
  8015. this.isMeshBasicNodeMaterial = true;
  8016. this.lights = true;
  8017. this.setDefaultValues( _defaultValues$9 );
  8018. this.setValues( parameters );
  8019. }
  8020. setupNormal() {
  8021. return normalView; // see #28839
  8022. }
  8023. setupEnvironment( builder ) {
  8024. const envNode = super.setupEnvironment( builder );
  8025. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  8026. }
  8027. setupLightMap( builder ) {
  8028. let node = null;
  8029. if ( builder.material.lightMap ) {
  8030. node = new BasicLightMapNode( materialLightMap );
  8031. }
  8032. return node;
  8033. }
  8034. setupOutgoingLight() {
  8035. return diffuseColor.rgb;
  8036. }
  8037. setupLightingModel() {
  8038. return new BasicLightingModel();
  8039. }
  8040. }
  8041. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  8042. // Original approximation by Christophe Schlick '94
  8043. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  8044. // Optimized variant (presented by Epic at SIGGRAPH '13)
  8045. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  8046. const fresnel = dotVH.mul( - 5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  8047. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  8048. } ); // validated
  8049. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  8050. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  8051. } ); // validated
  8052. const G_BlinnPhong_Implicit = () => float( 0.25 );
  8053. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  8054. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  8055. } );
  8056. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  8057. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  8058. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  8059. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  8060. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  8061. const G = G_BlinnPhong_Implicit();
  8062. const D = D_BlinnPhong( { dotNH } );
  8063. return F.mul( G ).mul( D );
  8064. } );
  8065. /**
  8066. * Represents the lighting model for a phong material. Used in {@link MeshPhongNodeMaterial}.
  8067. *
  8068. * @augments LightingModel
  8069. */
  8070. class PhongLightingModel extends BasicLightingModel {
  8071. /**
  8072. * Constructs a new phong lighting model.
  8073. *
  8074. * @param {Boolean} [specular=true] - Whether specular is supported or not.
  8075. */
  8076. constructor( specular = true ) {
  8077. super();
  8078. /**
  8079. * Whether specular is supported or not. Set this to `false` if you are
  8080. * lookking for a Lambert-like material meaning a material for non-shiny
  8081. * surfaces, without specular highlights.
  8082. *
  8083. * @type {Boolean}
  8084. * @default true
  8085. */
  8086. this.specular = specular;
  8087. }
  8088. /**
  8089. * Implements the direct lighting. The specular portion is optional an can be controlled
  8090. * with the {@link PhongLightingModel#specular} flag.
  8091. *
  8092. * @param {Object} input - The input data.
  8093. * @param {StackNode} stack - The current stack.
  8094. * @param {NodeBuilder} builder - The current node builder.
  8095. */
  8096. direct( { lightDirection, lightColor, reflectedLight } ) {
  8097. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  8098. const irradiance = dotNL.mul( lightColor );
  8099. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  8100. if ( this.specular === true ) {
  8101. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  8102. }
  8103. }
  8104. /**
  8105. * Implements the indirect lighting.
  8106. *
  8107. * @param {ContextNode} input - The current node context.
  8108. * @param {StackNode} stack - The current stack.
  8109. * @param {NodeBuilder} builder - The current node builder.
  8110. */
  8111. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  8112. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  8113. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  8114. }
  8115. }
  8116. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  8117. class MeshLambertNodeMaterial extends NodeMaterial {
  8118. static get type() {
  8119. return 'MeshLambertNodeMaterial';
  8120. }
  8121. constructor( parameters ) {
  8122. super();
  8123. this.isMeshLambertNodeMaterial = true;
  8124. this.lights = true;
  8125. this.setDefaultValues( _defaultValues$8 );
  8126. this.setValues( parameters );
  8127. }
  8128. setupEnvironment( builder ) {
  8129. const envNode = super.setupEnvironment( builder );
  8130. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  8131. }
  8132. setupLightingModel( /*builder*/ ) {
  8133. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  8134. }
  8135. }
  8136. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  8137. class MeshPhongNodeMaterial extends NodeMaterial {
  8138. static get type() {
  8139. return 'MeshPhongNodeMaterial';
  8140. }
  8141. constructor( parameters ) {
  8142. super();
  8143. this.isMeshPhongNodeMaterial = true;
  8144. this.lights = true;
  8145. this.shininessNode = null;
  8146. this.specularNode = null;
  8147. this.setDefaultValues( _defaultValues$7 );
  8148. this.setValues( parameters );
  8149. }
  8150. setupEnvironment( builder ) {
  8151. const envNode = super.setupEnvironment( builder );
  8152. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  8153. }
  8154. setupLightingModel( /*builder*/ ) {
  8155. return new PhongLightingModel();
  8156. }
  8157. setupVariants() {
  8158. // SHININESS
  8159. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  8160. shininess.assign( shininessNode );
  8161. // SPECULAR COLOR
  8162. const specularNode = this.specularNode || materialSpecular;
  8163. specularColor.assign( specularNode );
  8164. }
  8165. copy( source ) {
  8166. this.shininessNode = source.shininessNode;
  8167. this.specularNode = source.specularNode;
  8168. return super.copy( source );
  8169. }
  8170. }
  8171. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  8172. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  8173. return float( 0 );
  8174. }
  8175. const dxy = normalView.dFdx().abs().max( normalView.dFdy().abs() );
  8176. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  8177. return geometryRoughness;
  8178. } );
  8179. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  8180. const { roughness } = inputs;
  8181. const geometryRoughness = getGeometryRoughness();
  8182. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  8183. roughnessFactor = roughnessFactor.add( geometryRoughness );
  8184. roughnessFactor = roughnessFactor.min( 1.0 );
  8185. return roughnessFactor;
  8186. } );
  8187. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  8188. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  8189. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  8190. const a2 = alpha.pow2();
  8191. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  8192. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  8193. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  8194. } ).setLayout( {
  8195. name: 'V_GGX_SmithCorrelated',
  8196. type: 'float',
  8197. inputs: [
  8198. { name: 'alpha', type: 'float' },
  8199. { name: 'dotNL', type: 'float' },
  8200. { name: 'dotNV', type: 'float' }
  8201. ]
  8202. } ); // validated
  8203. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  8204. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  8205. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  8206. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  8207. const v = div( 0.5, gv.add( gl ) );
  8208. return v.saturate();
  8209. } ).setLayout( {
  8210. name: 'V_GGX_SmithCorrelated_Anisotropic',
  8211. type: 'float',
  8212. inputs: [
  8213. { name: 'alphaT', type: 'float', qualifier: 'in' },
  8214. { name: 'alphaB', type: 'float', qualifier: 'in' },
  8215. { name: 'dotTV', type: 'float', qualifier: 'in' },
  8216. { name: 'dotBV', type: 'float', qualifier: 'in' },
  8217. { name: 'dotTL', type: 'float', qualifier: 'in' },
  8218. { name: 'dotBL', type: 'float', qualifier: 'in' },
  8219. { name: 'dotNV', type: 'float', qualifier: 'in' },
  8220. { name: 'dotNL', type: 'float', qualifier: 'in' }
  8221. ]
  8222. } );
  8223. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  8224. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  8225. // alpha is "roughness squared" in Disney’s reparameterization
  8226. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  8227. const a2 = alpha.pow2();
  8228. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  8229. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  8230. } ).setLayout( {
  8231. name: 'D_GGX',
  8232. type: 'float',
  8233. inputs: [
  8234. { name: 'alpha', type: 'float' },
  8235. { name: 'dotNH', type: 'float' }
  8236. ]
  8237. } ); // validated
  8238. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  8239. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  8240. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  8241. const a2 = alphaT.mul( alphaB );
  8242. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  8243. const v2 = v.dot( v );
  8244. const w2 = a2.div( v2 );
  8245. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  8246. } ).setLayout( {
  8247. name: 'D_GGX_Anisotropic',
  8248. type: 'float',
  8249. inputs: [
  8250. { name: 'alphaT', type: 'float', qualifier: 'in' },
  8251. { name: 'alphaB', type: 'float', qualifier: 'in' },
  8252. { name: 'dotNH', type: 'float', qualifier: 'in' },
  8253. { name: 'dotTH', type: 'float', qualifier: 'in' },
  8254. { name: 'dotBH', type: 'float', qualifier: 'in' }
  8255. ]
  8256. } );
  8257. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  8258. const BRDF_GGX = /*@__PURE__*/ Fn( ( inputs ) => {
  8259. const { lightDirection, f0, f90, roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } = inputs;
  8260. const normalView = inputs.normalView || transformedNormalView;
  8261. const alpha = roughness.pow2(); // UE4's roughness
  8262. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  8263. const dotNL = normalView.dot( lightDirection ).clamp();
  8264. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  8265. const dotNH = normalView.dot( halfDir ).clamp();
  8266. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  8267. let F = F_Schlick( { f0, f90, dotVH } );
  8268. let V, D;
  8269. if ( defined( USE_IRIDESCENCE ) ) {
  8270. F = iridescence.mix( F, f );
  8271. }
  8272. if ( defined( USE_ANISOTROPY ) ) {
  8273. const dotTL = anisotropyT.dot( lightDirection );
  8274. const dotTV = anisotropyT.dot( positionViewDirection );
  8275. const dotTH = anisotropyT.dot( halfDir );
  8276. const dotBL = anisotropyB.dot( lightDirection );
  8277. const dotBV = anisotropyB.dot( positionViewDirection );
  8278. const dotBH = anisotropyB.dot( halfDir );
  8279. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  8280. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  8281. } else {
  8282. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  8283. D = D_GGX( { alpha, dotNH } );
  8284. }
  8285. return F.mul( V ).mul( D );
  8286. } ); // validated
  8287. // Analytical approximation of the DFG LUT, one half of the
  8288. // split-sum approximation used in indirect specular lighting.
  8289. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  8290. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  8291. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  8292. const c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );
  8293. const c1 = vec4( 1, 0.0425, 1.04, - 0.04 );
  8294. const r = roughness.mul( c0 ).add( c1 );
  8295. const a004 = r.x.mul( r.x ).min( dotNV.mul( - 9.28 ).exp2() ).mul( r.x ).add( r.y );
  8296. const fab = vec2( - 1.04, 1.04 ).mul( a004 ).add( r.zw );
  8297. return fab;
  8298. } ).setLayout( {
  8299. name: 'DFGApprox',
  8300. type: 'vec2',
  8301. inputs: [
  8302. { name: 'roughness', type: 'float' },
  8303. { name: 'dotNV', type: 'vec3' }
  8304. ]
  8305. } );
  8306. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  8307. const { dotNV, specularColor, specularF90, roughness } = inputs;
  8308. const fab = DFGApprox( { dotNV, roughness } );
  8309. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  8310. } );
  8311. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  8312. const x = dotVH.oneMinus().saturate();
  8313. const x2 = x.mul( x );
  8314. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  8315. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  8316. } ).setLayout( {
  8317. name: 'Schlick_to_F0',
  8318. type: 'vec3',
  8319. inputs: [
  8320. { name: 'f', type: 'vec3' },
  8321. { name: 'f90', type: 'float' },
  8322. { name: 'dotVH', type: 'float' }
  8323. ]
  8324. } );
  8325. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  8326. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  8327. const alpha = roughness.pow2();
  8328. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  8329. const invAlpha = float( 1.0 ).div( alpha );
  8330. const cos2h = dotNH.pow2();
  8331. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  8332. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  8333. } ).setLayout( {
  8334. name: 'D_Charlie',
  8335. type: 'float',
  8336. inputs: [
  8337. { name: 'roughness', type: 'float' },
  8338. { name: 'dotNH', type: 'float' }
  8339. ]
  8340. } );
  8341. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  8342. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  8343. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  8344. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  8345. } ).setLayout( {
  8346. name: 'V_Neubelt',
  8347. type: 'float',
  8348. inputs: [
  8349. { name: 'dotNV', type: 'float' },
  8350. { name: 'dotNL', type: 'float' }
  8351. ]
  8352. } );
  8353. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  8354. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  8355. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  8356. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp();
  8357. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  8358. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  8359. const V = V_Neubelt( { dotNV, dotNL } );
  8360. return sheen.mul( D ).mul( V );
  8361. } );
  8362. // Rect Area Light
  8363. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  8364. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  8365. // code: https://github.com/selfshadow/ltc_code/
  8366. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  8367. const LUT_SIZE = 64.0;
  8368. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  8369. const LUT_BIAS = 0.5 / LUT_SIZE;
  8370. const dotNV = N.dot( V ).saturate();
  8371. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  8372. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  8373. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  8374. return uv;
  8375. } ).setLayout( {
  8376. name: 'LTC_Uv',
  8377. type: 'vec2',
  8378. inputs: [
  8379. { name: 'N', type: 'vec3' },
  8380. { name: 'V', type: 'vec3' },
  8381. { name: 'roughness', type: 'float' }
  8382. ]
  8383. } );
  8384. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  8385. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  8386. // An approximation of the form factor of a horizon-clipped rectangle.
  8387. const l = f.length();
  8388. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  8389. } ).setLayout( {
  8390. name: 'LTC_ClippedSphereFormFactor',
  8391. type: 'float',
  8392. inputs: [
  8393. { name: 'f', type: 'vec3' }
  8394. ]
  8395. } );
  8396. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  8397. const x = v1.dot( v2 );
  8398. const y = x.abs().toVar();
  8399. // rational polynomial approximation to theta / sin( theta ) / 2PI
  8400. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  8401. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  8402. const v = a.div( b );
  8403. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  8404. return v1.cross( v2 ).mul( theta_sintheta );
  8405. } ).setLayout( {
  8406. name: 'LTC_EdgeVectorFormFactor',
  8407. type: 'vec3',
  8408. inputs: [
  8409. { name: 'v1', type: 'vec3' },
  8410. { name: 'v2', type: 'vec3' }
  8411. ]
  8412. } );
  8413. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  8414. // bail if point is on back side of plane of light
  8415. // assumes ccw winding order of light vertices
  8416. const v1 = p1.sub( p0 ).toVar();
  8417. const v2 = p3.sub( p0 ).toVar();
  8418. const lightNormal = v1.cross( v2 );
  8419. const result = vec3().toVar();
  8420. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  8421. // construct orthonormal basis around N
  8422. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  8423. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  8424. // compute transform
  8425. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  8426. // transform rect
  8427. // & project rect onto sphere
  8428. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  8429. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  8430. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  8431. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  8432. // calculate vector form factor
  8433. const vectorFormFactor = vec3( 0 ).toVar();
  8434. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  8435. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  8436. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  8437. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  8438. // adjust for horizon clipping
  8439. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  8440. } );
  8441. return result;
  8442. } ).setLayout( {
  8443. name: 'LTC_Evaluate',
  8444. type: 'vec3',
  8445. inputs: [
  8446. { name: 'N', type: 'vec3' },
  8447. { name: 'V', type: 'vec3' },
  8448. { name: 'P', type: 'vec3' },
  8449. { name: 'mInv', type: 'mat3' },
  8450. { name: 'p0', type: 'vec3' },
  8451. { name: 'p1', type: 'vec3' },
  8452. { name: 'p2', type: 'vec3' },
  8453. { name: 'p3', type: 'vec3' }
  8454. ]
  8455. } );
  8456. // Mipped Bicubic Texture Filtering by N8
  8457. // https://www.shadertoy.com/view/Dl2SDW
  8458. const bC = 1.0 / 6.0;
  8459. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  8460. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  8461. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( - 3.0, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  8462. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  8463. const g0 = ( a ) => w0( a ).add( w1( a ) );
  8464. const g1 = ( a ) => w2( a ).add( w3( a ) );
  8465. // h0 and h1 are the two offset functions
  8466. const h0 = ( a ) => add( - 1.0, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  8467. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  8468. const bicubic = ( textureNode, texelSize, lod ) => {
  8469. const uv = textureNode.uvNode;
  8470. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  8471. const iuv = floor( uvScaled );
  8472. const fuv = fract( uvScaled );
  8473. const g0x = g0( fuv.x );
  8474. const g1x = g1( fuv.x );
  8475. const h0x = h0( fuv.x );
  8476. const h1x = h1( fuv.x );
  8477. const h0y = h0( fuv.y );
  8478. const h1y = h1( fuv.y );
  8479. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  8480. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  8481. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  8482. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  8483. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.sample( p0 ).level( lod ) ), g1x.mul( textureNode.sample( p1 ).level( lod ) ) ) );
  8484. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.sample( p2 ).level( lod ) ), g1x.mul( textureNode.sample( p3 ).level( lod ) ) ) );
  8485. return a.add( b );
  8486. };
  8487. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, lodNode = float( 3 ) ] ) => {
  8488. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  8489. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  8490. const fLodSizeInv = div( 1.0, fLodSize );
  8491. const cLodSizeInv = div( 1.0, cLodSize );
  8492. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  8493. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  8494. return fract( lodNode ).mix( fSample, cSample );
  8495. } );
  8496. //
  8497. // Transmission
  8498. //
  8499. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  8500. // Direction of refracted light.
  8501. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  8502. // Compute rotation-independent scaling of the model matrix.
  8503. const modelScale = vec3(
  8504. length( modelMatrix[ 0 ].xyz ),
  8505. length( modelMatrix[ 1 ].xyz ),
  8506. length( modelMatrix[ 2 ].xyz )
  8507. );
  8508. // The thickness is specified in local space.
  8509. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  8510. } ).setLayout( {
  8511. name: 'getVolumeTransmissionRay',
  8512. type: 'vec3',
  8513. inputs: [
  8514. { name: 'n', type: 'vec3' },
  8515. { name: 'v', type: 'vec3' },
  8516. { name: 'thickness', type: 'float' },
  8517. { name: 'ior', type: 'float' },
  8518. { name: 'modelMatrix', type: 'mat4' }
  8519. ]
  8520. } );
  8521. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  8522. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  8523. // an IOR of 1.5 results in the default amount of microfacet refraction.
  8524. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  8525. } ).setLayout( {
  8526. name: 'applyIorToRoughness',
  8527. type: 'float',
  8528. inputs: [
  8529. { name: 'roughness', type: 'float' },
  8530. { name: 'ior', type: 'float' }
  8531. ]
  8532. } );
  8533. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  8534. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  8535. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  8536. const vTexture = material.side == BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  8537. const transmissionSample = vTexture.sample( fragCoord );
  8538. //const transmissionSample = viewportMipTexture( fragCoord );
  8539. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  8540. return textureBicubic( transmissionSample, lod );
  8541. } );
  8542. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  8543. If( attenuationDistance.notEqual( 0 ), () => {
  8544. // Compute light attenuation using Beer's law.
  8545. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  8546. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  8547. return transmittance;
  8548. } );
  8549. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  8550. return vec3( 1.0 );
  8551. } ).setLayout( {
  8552. name: 'volumeAttenuation',
  8553. type: 'vec3',
  8554. inputs: [
  8555. { name: 'transmissionDistance', type: 'float' },
  8556. { name: 'attenuationColor', type: 'vec3' },
  8557. { name: 'attenuationDistance', type: 'float' }
  8558. ]
  8559. } );
  8560. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  8561. let transmittedLight, transmittance;
  8562. if ( dispersion ) {
  8563. transmittedLight = vec4().toVar();
  8564. transmittance = vec3().toVar();
  8565. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  8566. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  8567. Loop( { start: 0, end: 3 }, ( { i } ) => {
  8568. const ior = iors.element( i );
  8569. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  8570. const refractedRayExit = position.add( transmissionRay );
  8571. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  8572. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  8573. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  8574. refractionCoords.addAssign( 1.0 );
  8575. refractionCoords.divAssign( 2.0 );
  8576. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  8577. // Sample framebuffer to get pixel the refracted ray hits.
  8578. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  8579. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  8580. transmittedLight.a.addAssign( transmissionSample.a );
  8581. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  8582. } );
  8583. transmittedLight.a.divAssign( 3.0 );
  8584. } else {
  8585. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  8586. const refractedRayExit = position.add( transmissionRay );
  8587. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  8588. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  8589. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  8590. refractionCoords.addAssign( 1.0 );
  8591. refractionCoords.divAssign( 2.0 );
  8592. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  8593. // Sample framebuffer to get pixel the refracted ray hits.
  8594. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  8595. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  8596. }
  8597. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  8598. const dotNV = n.dot( v ).clamp();
  8599. // Get the specular component.
  8600. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  8601. dotNV,
  8602. specularColor,
  8603. specularF90,
  8604. roughness
  8605. } ) );
  8606. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  8607. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  8608. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  8609. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  8610. } );
  8611. //
  8612. // Iridescence
  8613. //
  8614. // XYZ to linear-sRGB color space
  8615. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  8616. 3.2404542, - 0.9692660, 0.0556434,
  8617. - 1.5371385, 1.8760108, - 0.2040259,
  8618. - 0.4985314, 0.0415560, 1.0572252
  8619. );
  8620. // Assume air interface for top
  8621. // Note: We don't handle the case fresnel0 == 1
  8622. const Fresnel0ToIor = ( fresnel0 ) => {
  8623. const sqrtF0 = fresnel0.sqrt();
  8624. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  8625. };
  8626. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  8627. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  8628. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  8629. };
  8630. // Fresnel equations for dielectric/dielectric interfaces.
  8631. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  8632. // Evaluation XYZ sensitivity curves in Fourier space
  8633. const evalSensitivity = ( OPD, shift ) => {
  8634. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  8635. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  8636. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  8637. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  8638. 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() );
  8639. 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() );
  8640. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  8641. const rgb = XYZ_TO_REC709.mul( xyz );
  8642. return rgb;
  8643. };
  8644. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  8645. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  8646. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  8647. // Evaluate the cosTheta on the base layer (Snell law)
  8648. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  8649. // Handle TIR:
  8650. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  8651. If( cosTheta2Sq.lessThan( 0 ), () => {
  8652. return vec3( 1.0 );
  8653. } );
  8654. const cosTheta2 = cosTheta2Sq.sqrt();
  8655. // First interface
  8656. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  8657. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  8658. //const R21 = R12;
  8659. const T121 = R12.oneMinus();
  8660. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  8661. const phi21 = float( Math.PI ).sub( phi12 );
  8662. // Second interface
  8663. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  8664. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  8665. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  8666. const phi23 = vec3(
  8667. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  8668. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  8669. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  8670. );
  8671. // Phase shift
  8672. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  8673. const phi = vec3( phi21 ).add( phi23 );
  8674. // Compound terms
  8675. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  8676. const r123 = R123.sqrt();
  8677. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  8678. // Reflectance term for m = 0 (DC term amplitude)
  8679. const C0 = R12.add( Rs );
  8680. const I = C0.toVar();
  8681. // Reflectance term for m > 0 (pairs of diracs)
  8682. const Cm = Rs.sub( T121 ).toVar();
  8683. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  8684. Cm.mulAssign( r123 );
  8685. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  8686. I.addAssign( Cm.mul( Sm ) );
  8687. } );
  8688. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  8689. return I.max( vec3( 0.0 ) );
  8690. } ).setLayout( {
  8691. name: 'evalIridescence',
  8692. type: 'vec3',
  8693. inputs: [
  8694. { name: 'outsideIOR', type: 'float' },
  8695. { name: 'eta2', type: 'float' },
  8696. { name: 'cosTheta1', type: 'float' },
  8697. { name: 'thinFilmThickness', type: 'float' },
  8698. { name: 'baseF0', type: 'vec3' }
  8699. ]
  8700. } );
  8701. //
  8702. // Sheen
  8703. //
  8704. // This is a curve-fit approximation to the "Charlie sheen" BRDF integrated over the hemisphere from
  8705. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  8706. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  8707. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  8708. const dotNV = normal.dot( viewDir ).saturate();
  8709. const r2 = roughness.pow2();
  8710. const a = select(
  8711. roughness.lessThan( 0.25 ),
  8712. float( - 339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  8713. float( - 8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  8714. );
  8715. const b = select(
  8716. roughness.lessThan( 0.25 ),
  8717. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  8718. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  8719. );
  8720. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  8721. return DG.mul( 1.0 / Math.PI ).saturate();
  8722. } );
  8723. const clearcoatF0 = vec3( 0.04 );
  8724. const clearcoatF90 = float( 1 );
  8725. /**
  8726. * Represents the lighting model for a PBR material.
  8727. *
  8728. * @augments LightingModel
  8729. */
  8730. class PhysicalLightingModel extends LightingModel {
  8731. /**
  8732. * Constructs a new physical lighting model.
  8733. *
  8734. * @param {Boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  8735. * @param {Boolean} [sheen=false] - Whether sheen is supported or not.
  8736. * @param {Boolean} [iridescence=false] - Whether iridescence is supported or not.
  8737. * @param {Boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  8738. * @param {Boolean} [transmission=false] - Whether transmission is supported or not.
  8739. * @param {Boolean} [dispersion=false] - Whether dispersion is supported or not.
  8740. */
  8741. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  8742. super();
  8743. /**
  8744. * Whether clearcoat is supported or not.
  8745. *
  8746. * @type {Boolean}
  8747. * @default false
  8748. */
  8749. this.clearcoat = clearcoat;
  8750. /**
  8751. * Whether sheen is supported or not.
  8752. *
  8753. * @type {Boolean}
  8754. * @default false
  8755. */
  8756. this.sheen = sheen;
  8757. /**
  8758. * Whether iridescence is supported or not.
  8759. *
  8760. * @type {Boolean}
  8761. * @default false
  8762. */
  8763. this.iridescence = iridescence;
  8764. /**
  8765. * Whether anisotropy is supported or not.
  8766. *
  8767. * @type {Boolean}
  8768. * @default false
  8769. */
  8770. this.anisotropy = anisotropy;
  8771. /**
  8772. * Whether transmission is supported or not.
  8773. *
  8774. * @type {Boolean}
  8775. * @default false
  8776. */
  8777. this.transmission = transmission;
  8778. /**
  8779. * Whether dispersion is supported or not.
  8780. *
  8781. * @type {Boolean}
  8782. * @default false
  8783. */
  8784. this.dispersion = dispersion;
  8785. /**
  8786. * The clear coat radiance.
  8787. *
  8788. * @type {Node?}
  8789. * @default null
  8790. */
  8791. this.clearcoatRadiance = null;
  8792. /**
  8793. * The clear coat specular direct.
  8794. *
  8795. * @type {Node?}
  8796. * @default null
  8797. */
  8798. this.clearcoatSpecularDirect = null;
  8799. /**
  8800. * The clear coat specular indirect.
  8801. *
  8802. * @type {Node?}
  8803. * @default null
  8804. */
  8805. this.clearcoatSpecularIndirect = null;
  8806. /**
  8807. * The sheen specular direct.
  8808. *
  8809. * @type {Node?}
  8810. * @default null
  8811. */
  8812. this.sheenSpecularDirect = null;
  8813. /**
  8814. * The sheen specular indirect.
  8815. *
  8816. * @type {Node?}
  8817. * @default null
  8818. */
  8819. this.sheenSpecularIndirect = null;
  8820. /**
  8821. * The iridescence Fresnel.
  8822. *
  8823. * @type {Node?}
  8824. * @default null
  8825. */
  8826. this.iridescenceFresnel = null;
  8827. /**
  8828. * The iridescence F0.
  8829. *
  8830. * @type {Node?}
  8831. * @default null
  8832. */
  8833. this.iridescenceF0 = null;
  8834. }
  8835. /**
  8836. * Depending on what features are requested, the method prepares certain node variables
  8837. * which are later used for lighting computations.
  8838. *
  8839. * @param {ContextNode} input - The current node context.
  8840. */
  8841. start( context ) {
  8842. if ( this.clearcoat === true ) {
  8843. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  8844. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  8845. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  8846. }
  8847. if ( this.sheen === true ) {
  8848. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  8849. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  8850. }
  8851. if ( this.iridescence === true ) {
  8852. const dotNVi = transformedNormalView.dot( positionViewDirection ).clamp();
  8853. this.iridescenceFresnel = evalIridescence( {
  8854. outsideIOR: float( 1.0 ),
  8855. eta2: iridescenceIOR,
  8856. cosTheta1: dotNVi,
  8857. thinFilmThickness: iridescenceThickness,
  8858. baseF0: specularColor
  8859. } );
  8860. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  8861. }
  8862. if ( this.transmission === true ) {
  8863. const position = positionWorld;
  8864. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  8865. const n = transformedNormalWorld;
  8866. context.backdrop = getIBLVolumeRefraction(
  8867. n,
  8868. v,
  8869. roughness,
  8870. diffuseColor,
  8871. specularColor,
  8872. specularF90, // specularF90
  8873. position, // positionWorld
  8874. modelWorldMatrix, // modelMatrix
  8875. cameraViewMatrix, // viewMatrix
  8876. cameraProjectionMatrix, // projMatrix
  8877. ior,
  8878. thickness,
  8879. attenuationColor,
  8880. attenuationDistance,
  8881. this.dispersion ? dispersion : null
  8882. );
  8883. context.backdropAlpha = transmission;
  8884. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  8885. }
  8886. }
  8887. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  8888. // Approximates multi-scattering in order to preserve energy.
  8889. // http://www.jcgt.org/published/0008/01/03/
  8890. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  8891. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  8892. const fab = DFGApprox( { roughness, dotNV } );
  8893. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  8894. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  8895. const Ess = fab.x.add( fab.y );
  8896. const Ems = Ess.oneMinus();
  8897. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  8898. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  8899. singleScatter.addAssign( FssEss );
  8900. multiScatter.addAssign( Fms.mul( Ems ) );
  8901. }
  8902. /**
  8903. * Implements the direct light.
  8904. *
  8905. * @param {Object} input - The input data.
  8906. * @param {StackNode} stack - The current stack.
  8907. * @param {NodeBuilder} builder - The current node builder.
  8908. */
  8909. direct( { lightDirection, lightColor, reflectedLight } ) {
  8910. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  8911. const irradiance = dotNL.mul( lightColor );
  8912. if ( this.sheen === true ) {
  8913. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  8914. }
  8915. if ( this.clearcoat === true ) {
  8916. const dotNLcc = transformedClearcoatNormalView.dot( lightDirection ).clamp();
  8917. const ccIrradiance = dotNLcc.mul( lightColor );
  8918. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: transformedClearcoatNormalView } ) ) );
  8919. }
  8920. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  8921. 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 } ) ) );
  8922. }
  8923. /**
  8924. * This method is intended for implementing the direct light term for
  8925. * rect area light nodes.
  8926. *
  8927. * @param {Object} input - The input data.
  8928. * @param {StackNode} stack - The current stack.
  8929. * @param {NodeBuilder} builder - The current node builder.
  8930. */
  8931. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 } ) {
  8932. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  8933. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  8934. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  8935. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  8936. const N = transformedNormalView;
  8937. const V = positionViewDirection;
  8938. const P = positionView.toVar();
  8939. const uv = LTC_Uv( { N, V, roughness } );
  8940. const t1 = ltc_1.sample( uv ).toVar();
  8941. const t2 = ltc_2.sample( uv ).toVar();
  8942. const mInv = mat3(
  8943. vec3( t1.x, 0, t1.y ),
  8944. vec3( 0, 1, 0 ),
  8945. vec3( t1.z, 0, t1.w )
  8946. ).toVar();
  8947. // LTC Fresnel Approximation by Stephen Hill
  8948. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  8949. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  8950. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  8951. 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 } ) ) );
  8952. }
  8953. /**
  8954. * Implements the indirect lighting.
  8955. *
  8956. * @param {ContextNode} input - The current node context.
  8957. * @param {StackNode} stack - The current stack.
  8958. * @param {NodeBuilder} builder - The current node builder.
  8959. */
  8960. indirect( context, stack, builder ) {
  8961. this.indirectDiffuse( context, stack, builder );
  8962. this.indirectSpecular( context, stack, builder );
  8963. this.ambientOcclusion( context, stack, builder );
  8964. }
  8965. /**
  8966. * Implements the indirect diffuse term.
  8967. *
  8968. * @param {ContextNode} input - The current node context.
  8969. * @param {StackNode} stack - The current stack.
  8970. * @param {NodeBuilder} builder - The current node builder.
  8971. */
  8972. indirectDiffuse( { irradiance, reflectedLight } ) {
  8973. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  8974. }
  8975. /**
  8976. * Implements the indirect specular term.
  8977. *
  8978. * @param {ContextNode} input - The current node context.
  8979. * @param {StackNode} stack - The current stack.
  8980. * @param {NodeBuilder} builder - The current node builder.
  8981. */
  8982. indirectSpecular( { radiance, iblIrradiance, reflectedLight } ) {
  8983. if ( this.sheen === true ) {
  8984. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  8985. sheen,
  8986. IBLSheenBRDF( {
  8987. normal: transformedNormalView,
  8988. viewDir: positionViewDirection,
  8989. roughness: sheenRoughness
  8990. } )
  8991. ) );
  8992. }
  8993. if ( this.clearcoat === true ) {
  8994. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  8995. const clearcoatEnv = EnvironmentBRDF( {
  8996. dotNV: dotNVcc,
  8997. specularColor: clearcoatF0,
  8998. specularF90: clearcoatF90,
  8999. roughness: clearcoatRoughness
  9000. } );
  9001. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  9002. }
  9003. // Both indirect specular and indirect diffuse light accumulate here
  9004. const singleScattering = vec3().toVar( 'singleScattering' );
  9005. const multiScattering = vec3().toVar( 'multiScattering' );
  9006. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  9007. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  9008. const totalScattering = singleScattering.add( multiScattering );
  9009. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  9010. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  9011. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  9012. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  9013. }
  9014. /**
  9015. * Implements the ambient occlusion term.
  9016. *
  9017. * @param {ContextNode} input - The current node context.
  9018. * @param {StackNode} stack - The current stack.
  9019. * @param {NodeBuilder} builder - The current node builder.
  9020. */
  9021. ambientOcclusion( { ambientOcclusion, reflectedLight } ) {
  9022. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  9023. const aoNV = dotNV.add( ambientOcclusion );
  9024. const aoExp = roughness.mul( - 16.0 ).oneMinus().negate().exp2();
  9025. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  9026. if ( this.clearcoat === true ) {
  9027. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  9028. }
  9029. if ( this.sheen === true ) {
  9030. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  9031. }
  9032. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  9033. reflectedLight.indirectSpecular.mulAssign( aoNode );
  9034. }
  9035. /**
  9036. * Used for final lighting accumulations depending on the requested features.
  9037. *
  9038. * @param {ContextNode} input - The current node context.
  9039. * @param {StackNode} stack - The current stack.
  9040. * @param {NodeBuilder} builder - The current node builder.
  9041. */
  9042. finish( context ) {
  9043. const { outgoingLight } = context;
  9044. if ( this.clearcoat === true ) {
  9045. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  9046. const Fcc = F_Schlick( {
  9047. dotVH: dotNVcc,
  9048. f0: clearcoatF0,
  9049. f90: clearcoatF90
  9050. } );
  9051. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  9052. outgoingLight.assign( clearcoatLight );
  9053. }
  9054. if ( this.sheen === true ) {
  9055. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  9056. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  9057. outgoingLight.assign( sheenLight );
  9058. }
  9059. }
  9060. }
  9061. // These defines must match with PMREMGenerator
  9062. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  9063. const cubeUV_m0 = /*@__PURE__*/ float( - 2.0 );
  9064. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  9065. const cubeUV_m1 = /*@__PURE__*/ float( - 1.0 );
  9066. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  9067. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  9068. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  9069. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  9070. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  9071. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  9072. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  9073. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  9074. // These shader functions convert between the UV coordinates of a single face of
  9075. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  9076. // sampling a textureCube (not generally normalized ).
  9077. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  9078. const absDirection = vec3( abs( direction ) ).toVar();
  9079. const face = float( - 1.0 ).toVar();
  9080. If( absDirection.x.greaterThan( absDirection.z ), () => {
  9081. If( absDirection.x.greaterThan( absDirection.y ), () => {
  9082. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  9083. } ).Else( () => {
  9084. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  9085. } );
  9086. } ).Else( () => {
  9087. If( absDirection.z.greaterThan( absDirection.y ), () => {
  9088. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  9089. } ).Else( () => {
  9090. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  9091. } );
  9092. } );
  9093. return face;
  9094. } ).setLayout( {
  9095. name: 'getFace',
  9096. type: 'float',
  9097. inputs: [
  9098. { name: 'direction', type: 'vec3' }
  9099. ]
  9100. } );
  9101. // RH coordinate system; PMREM face-indexing convention
  9102. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  9103. const uv = vec2().toVar();
  9104. If( face.equal( 0.0 ), () => {
  9105. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  9106. } ).ElseIf( face.equal( 1.0 ), () => {
  9107. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  9108. } ).ElseIf( face.equal( 2.0 ), () => {
  9109. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  9110. } ).ElseIf( face.equal( 3.0 ), () => {
  9111. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  9112. } ).ElseIf( face.equal( 4.0 ), () => {
  9113. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  9114. } ).Else( () => {
  9115. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  9116. } );
  9117. return mul( 0.5, uv.add( 1.0 ) );
  9118. } ).setLayout( {
  9119. name: 'getUV',
  9120. type: 'vec2',
  9121. inputs: [
  9122. { name: 'direction', type: 'vec3' },
  9123. { name: 'face', type: 'float' }
  9124. ]
  9125. } );
  9126. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  9127. const mip = float( 0.0 ).toVar();
  9128. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  9129. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  9130. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  9131. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  9132. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  9133. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  9134. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  9135. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  9136. } ).Else( () => {
  9137. mip.assign( float( - 2.0 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  9138. } );
  9139. return mip;
  9140. } ).setLayout( {
  9141. name: 'roughnessToMip',
  9142. type: 'float',
  9143. inputs: [
  9144. { name: 'roughness', type: 'float' }
  9145. ]
  9146. } );
  9147. // RH coordinate system; PMREM face-indexing convention
  9148. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  9149. const uv = uv_immutable.toVar();
  9150. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  9151. const direction = vec3( uv, 1.0 ).toVar();
  9152. If( face.equal( 0.0 ), () => {
  9153. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  9154. } ).ElseIf( face.equal( 1.0 ), () => {
  9155. direction.assign( direction.xzy );
  9156. direction.xz.mulAssign( - 1.0 ); // ( -u, 1, -v ) pos y
  9157. } ).ElseIf( face.equal( 2.0 ), () => {
  9158. direction.x.mulAssign( - 1.0 ); // ( -u, v, 1 ) pos z
  9159. } ).ElseIf( face.equal( 3.0 ), () => {
  9160. direction.assign( direction.zyx );
  9161. direction.xz.mulAssign( - 1.0 ); // ( -1, v, -u ) neg x
  9162. } ).ElseIf( face.equal( 4.0 ), () => {
  9163. direction.assign( direction.xzy );
  9164. direction.xy.mulAssign( - 1.0 ); // ( -u, -1, v ) neg y
  9165. } ).ElseIf( face.equal( 5.0 ), () => {
  9166. direction.z.mulAssign( - 1.0 ); // ( u, v, -1 ) neg zS
  9167. } );
  9168. return direction;
  9169. } ).setLayout( {
  9170. name: 'getDirection',
  9171. type: 'vec3',
  9172. inputs: [
  9173. { name: 'uv', type: 'vec2' },
  9174. { name: 'face', type: 'float' }
  9175. ]
  9176. } );
  9177. //
  9178. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  9179. const roughness = float( roughness_immutable );
  9180. const sampleDir = vec3( sampleDir_immutable );
  9181. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  9182. const mipF = fract( mip );
  9183. const mipInt = floor( mip );
  9184. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  9185. If( mipF.notEqual( 0.0 ), () => {
  9186. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  9187. color0.assign( mix( color0, color1, mipF ) );
  9188. } );
  9189. return color0;
  9190. } );
  9191. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  9192. const mipInt = float( mipInt_immutable ).toVar();
  9193. const direction = vec3( direction_immutable );
  9194. const face = float( getFace( direction ) ).toVar();
  9195. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  9196. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  9197. const faceSize = float( exp2( mipInt ) ).toVar();
  9198. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  9199. If( face.greaterThan( 2.0 ), () => {
  9200. uv.y.addAssign( faceSize );
  9201. face.subAssign( 3.0 );
  9202. } );
  9203. uv.x.addAssign( face.mul( faceSize ) );
  9204. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  9205. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  9206. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  9207. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  9208. return envMap.sample( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  9209. } );
  9210. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  9211. const cosTheta = cos( theta );
  9212. // Rodrigues' axis-angle rotation
  9213. const sampleDirection = outputDirection.mul( cosTheta )
  9214. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  9215. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  9216. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  9217. } );
  9218. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  9219. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  9220. If( all( axis.equals( vec3( 0.0 ) ) ), () => {
  9221. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  9222. } );
  9223. axis.assign( normalize( axis ) );
  9224. const gl_FragColor = vec3().toVar();
  9225. 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 } ) ) );
  9226. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  9227. If( i.greaterThanEqual( samples ), () => {
  9228. Break();
  9229. } );
  9230. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  9231. 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 } ) ) );
  9232. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  9233. } );
  9234. return vec4( gl_FragColor, 1 );
  9235. } );
  9236. let _generator = null;
  9237. const _cache = new WeakMap();
  9238. function _generateCubeUVSize( imageHeight ) {
  9239. const maxMip = Math.log2( imageHeight ) - 2;
  9240. const texelHeight = 1.0 / imageHeight;
  9241. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  9242. return { texelWidth, texelHeight, maxMip };
  9243. }
  9244. function _getPMREMFromTexture( texture ) {
  9245. let cacheTexture = _cache.get( texture );
  9246. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : - 1;
  9247. if ( pmremVersion !== texture.pmremVersion ) {
  9248. const image = texture.image;
  9249. if ( texture.isCubeTexture ) {
  9250. if ( isCubeMapReady( image ) ) {
  9251. cacheTexture = _generator.fromCubemap( texture, cacheTexture );
  9252. } else {
  9253. return null;
  9254. }
  9255. } else {
  9256. if ( isEquirectangularMapReady( image ) ) {
  9257. cacheTexture = _generator.fromEquirectangular( texture, cacheTexture );
  9258. } else {
  9259. return null;
  9260. }
  9261. }
  9262. cacheTexture.pmremVersion = texture.pmremVersion;
  9263. _cache.set( texture, cacheTexture );
  9264. }
  9265. return cacheTexture.texture;
  9266. }
  9267. class PMREMNode extends TempNode {
  9268. static get type() {
  9269. return 'PMREMNode';
  9270. }
  9271. constructor( value, uvNode = null, levelNode = null ) {
  9272. super( 'vec3' );
  9273. this._value = value;
  9274. this._pmrem = null;
  9275. this.uvNode = uvNode;
  9276. this.levelNode = levelNode;
  9277. this._generator = null;
  9278. const defaultTexture = new Texture();
  9279. defaultTexture.isRenderTargetTexture = true;
  9280. this._texture = texture( defaultTexture );
  9281. this._width = uniform( 0 );
  9282. this._height = uniform( 0 );
  9283. this._maxMip = uniform( 0 );
  9284. this.updateBeforeType = NodeUpdateType.RENDER;
  9285. }
  9286. set value( value ) {
  9287. this._value = value;
  9288. this._pmrem = null;
  9289. }
  9290. get value() {
  9291. return this._value;
  9292. }
  9293. updateFromTexture( texture ) {
  9294. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  9295. this._texture.value = texture;
  9296. this._width.value = cubeUVSize.texelWidth;
  9297. this._height.value = cubeUVSize.texelHeight;
  9298. this._maxMip.value = cubeUVSize.maxMip;
  9299. }
  9300. updateBefore() {
  9301. let pmrem = this._pmrem;
  9302. const pmremVersion = pmrem ? pmrem.pmremVersion : - 1;
  9303. const texture = this._value;
  9304. if ( pmremVersion !== texture.pmremVersion ) {
  9305. if ( texture.isPMREMTexture === true ) {
  9306. pmrem = texture;
  9307. } else {
  9308. pmrem = _getPMREMFromTexture( texture );
  9309. }
  9310. if ( pmrem !== null ) {
  9311. this._pmrem = pmrem;
  9312. this.updateFromTexture( pmrem );
  9313. }
  9314. }
  9315. }
  9316. setup( builder ) {
  9317. if ( _generator === null ) {
  9318. _generator = builder.createPMREMGenerator();
  9319. }
  9320. //
  9321. this.updateBefore( builder );
  9322. //
  9323. let uvNode = this.uvNode;
  9324. if ( uvNode === null && builder.context.getUV ) {
  9325. uvNode = builder.context.getUV( this );
  9326. }
  9327. //
  9328. const texture = this.value;
  9329. if ( builder.renderer.coordinateSystem === WebGLCoordinateSystem && texture.isPMREMTexture !== true && texture.isRenderTargetTexture === true ) {
  9330. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  9331. }
  9332. //
  9333. let levelNode = this.levelNode;
  9334. if ( levelNode === null && builder.context.getTextureLevel ) {
  9335. levelNode = builder.context.getTextureLevel( this );
  9336. }
  9337. //
  9338. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  9339. }
  9340. }
  9341. function isCubeMapReady( image ) {
  9342. if ( image === null || image === undefined ) return false;
  9343. let count = 0;
  9344. const length = 6;
  9345. for ( let i = 0; i < length; i ++ ) {
  9346. if ( image[ i ] !== undefined ) count ++;
  9347. }
  9348. return count === length;
  9349. }
  9350. function isEquirectangularMapReady( image ) {
  9351. if ( image === null || image === undefined ) return false;
  9352. return image.height > 0;
  9353. }
  9354. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode );
  9355. const _envNodeCache = new WeakMap();
  9356. class EnvironmentNode extends LightingNode {
  9357. static get type() {
  9358. return 'EnvironmentNode';
  9359. }
  9360. constructor( envNode = null ) {
  9361. super();
  9362. this.envNode = envNode;
  9363. }
  9364. setup( builder ) {
  9365. const { material } = builder;
  9366. let envNode = this.envNode;
  9367. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  9368. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  9369. let cacheEnvNode = _envNodeCache.get( value );
  9370. if ( cacheEnvNode === undefined ) {
  9371. cacheEnvNode = pmremTexture( value );
  9372. _envNodeCache.set( value, cacheEnvNode );
  9373. }
  9374. envNode = cacheEnvNode;
  9375. }
  9376. //
  9377. const envMap = material.envMap;
  9378. const intensity = envMap ? reference( 'envMapIntensity', 'float', builder.material ) : reference( 'environmentIntensity', 'float', builder.scene ); // @TODO: Add materialEnvIntensity in MaterialNode
  9379. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  9380. const radianceNormalView = useAnisotropy ? transformedBentNormalView : transformedNormalView;
  9381. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( intensity );
  9382. const irradiance = envNode.context( createIrradianceContext( transformedNormalWorld ) ).mul( Math.PI ).mul( intensity );
  9383. const isolateRadiance = cache( radiance );
  9384. const isolateIrradiance = cache( irradiance );
  9385. //
  9386. builder.context.radiance.addAssign( isolateRadiance );
  9387. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  9388. //
  9389. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  9390. if ( clearcoatRadiance ) {
  9391. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, transformedClearcoatNormalView ) ).mul( intensity );
  9392. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  9393. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  9394. }
  9395. }
  9396. }
  9397. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  9398. let reflectVec = null;
  9399. return {
  9400. getUV: () => {
  9401. if ( reflectVec === null ) {
  9402. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  9403. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  9404. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  9405. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  9406. }
  9407. return reflectVec;
  9408. },
  9409. getTextureLevel: () => {
  9410. return roughnessNode;
  9411. }
  9412. };
  9413. };
  9414. const createIrradianceContext = ( normalWorldNode ) => {
  9415. return {
  9416. getUV: () => {
  9417. return normalWorldNode;
  9418. },
  9419. getTextureLevel: () => {
  9420. return float( 1.0 );
  9421. }
  9422. };
  9423. };
  9424. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  9425. class MeshStandardNodeMaterial extends NodeMaterial {
  9426. static get type() {
  9427. return 'MeshStandardNodeMaterial';
  9428. }
  9429. constructor( parameters ) {
  9430. super();
  9431. this.isMeshStandardNodeMaterial = true;
  9432. this.lights = true;
  9433. this.emissiveNode = null;
  9434. this.metalnessNode = null;
  9435. this.roughnessNode = null;
  9436. this.setDefaultValues( _defaultValues$6 );
  9437. this.setValues( parameters );
  9438. }
  9439. setupEnvironment( builder ) {
  9440. let envNode = super.setupEnvironment( builder );
  9441. if ( envNode === null && builder.environmentNode ) {
  9442. envNode = builder.environmentNode;
  9443. }
  9444. return envNode ? new EnvironmentNode( envNode ) : null;
  9445. }
  9446. setupLightingModel( /*builder*/ ) {
  9447. return new PhysicalLightingModel();
  9448. }
  9449. setupSpecular() {
  9450. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  9451. specularColor.assign( specularColorNode );
  9452. specularF90.assign( 1.0 );
  9453. }
  9454. setupVariants() {
  9455. // METALNESS
  9456. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  9457. metalness.assign( metalnessNode );
  9458. // ROUGHNESS
  9459. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  9460. roughnessNode = getRoughness( { roughness: roughnessNode } );
  9461. roughness.assign( roughnessNode );
  9462. // SPECULAR COLOR
  9463. this.setupSpecular();
  9464. // DIFFUSE COLOR
  9465. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  9466. }
  9467. copy( source ) {
  9468. this.emissiveNode = source.emissiveNode;
  9469. this.metalnessNode = source.metalnessNode;
  9470. this.roughnessNode = source.roughnessNode;
  9471. return super.copy( source );
  9472. }
  9473. }
  9474. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  9475. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  9476. static get type() {
  9477. return 'MeshPhysicalNodeMaterial';
  9478. }
  9479. constructor( parameters ) {
  9480. super();
  9481. this.isMeshPhysicalNodeMaterial = true;
  9482. this.clearcoatNode = null;
  9483. this.clearcoatRoughnessNode = null;
  9484. this.clearcoatNormalNode = null;
  9485. this.sheenNode = null;
  9486. this.sheenRoughnessNode = null;
  9487. this.iridescenceNode = null;
  9488. this.iridescenceIORNode = null;
  9489. this.iridescenceThicknessNode = null;
  9490. this.specularIntensityNode = null;
  9491. this.specularColorNode = null;
  9492. this.iorNode = null;
  9493. this.transmissionNode = null;
  9494. this.thicknessNode = null;
  9495. this.attenuationDistanceNode = null;
  9496. this.attenuationColorNode = null;
  9497. this.dispersionNode = null;
  9498. this.anisotropyNode = null;
  9499. this.setDefaultValues( _defaultValues$5 );
  9500. this.setValues( parameters );
  9501. }
  9502. get useClearcoat() {
  9503. return this.clearcoat > 0 || this.clearcoatNode !== null;
  9504. }
  9505. get useIridescence() {
  9506. return this.iridescence > 0 || this.iridescenceNode !== null;
  9507. }
  9508. get useSheen() {
  9509. return this.sheen > 0 || this.sheenNode !== null;
  9510. }
  9511. get useAnisotropy() {
  9512. return this.anisotropy > 0 || this.anisotropyNode !== null;
  9513. }
  9514. get useTransmission() {
  9515. return this.transmission > 0 || this.transmissionNode !== null;
  9516. }
  9517. get useDispersion() {
  9518. return this.dispersion > 0 || this.dispersionNode !== null;
  9519. }
  9520. setupSpecular() {
  9521. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  9522. ior.assign( iorNode );
  9523. 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 ) );
  9524. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  9525. }
  9526. setupLightingModel( /*builder*/ ) {
  9527. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  9528. }
  9529. setupVariants( builder ) {
  9530. super.setupVariants( builder );
  9531. // CLEARCOAT
  9532. if ( this.useClearcoat ) {
  9533. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  9534. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  9535. clearcoat.assign( clearcoatNode );
  9536. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  9537. }
  9538. // SHEEN
  9539. if ( this.useSheen ) {
  9540. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  9541. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  9542. sheen.assign( sheenNode );
  9543. sheenRoughness.assign( sheenRoughnessNode );
  9544. }
  9545. // IRIDESCENCE
  9546. if ( this.useIridescence ) {
  9547. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  9548. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  9549. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  9550. iridescence.assign( iridescenceNode );
  9551. iridescenceIOR.assign( iridescenceIORNode );
  9552. iridescenceThickness.assign( iridescenceThicknessNode );
  9553. }
  9554. // ANISOTROPY
  9555. if ( this.useAnisotropy ) {
  9556. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  9557. anisotropy.assign( anisotropyV.length() );
  9558. If( anisotropy.equal( 0.0 ), () => {
  9559. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  9560. } ).Else( () => {
  9561. anisotropyV.divAssign( vec2( anisotropy ) );
  9562. anisotropy.assign( anisotropy.saturate() );
  9563. } );
  9564. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  9565. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  9566. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  9567. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  9568. }
  9569. // TRANSMISSION
  9570. if ( this.useTransmission ) {
  9571. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  9572. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  9573. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  9574. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  9575. transmission.assign( transmissionNode );
  9576. thickness.assign( thicknessNode );
  9577. attenuationDistance.assign( attenuationDistanceNode );
  9578. attenuationColor.assign( attenuationColorNode );
  9579. if ( this.useDispersion ) {
  9580. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  9581. dispersion.assign( dispersionNode );
  9582. }
  9583. }
  9584. }
  9585. setupClearcoatNormal() {
  9586. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  9587. }
  9588. setup( builder ) {
  9589. builder.context.setupClearcoatNormal = () => this.setupClearcoatNormal( builder );
  9590. super.setup( builder );
  9591. }
  9592. copy( source ) {
  9593. this.clearcoatNode = source.clearcoatNode;
  9594. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  9595. this.clearcoatNormalNode = source.clearcoatNormalNode;
  9596. this.sheenNode = source.sheenNode;
  9597. this.sheenRoughnessNode = source.sheenRoughnessNode;
  9598. this.iridescenceNode = source.iridescenceNode;
  9599. this.iridescenceIORNode = source.iridescenceIORNode;
  9600. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  9601. this.specularIntensityNode = source.specularIntensityNode;
  9602. this.specularColorNode = source.specularColorNode;
  9603. this.transmissionNode = source.transmissionNode;
  9604. this.thicknessNode = source.thicknessNode;
  9605. this.attenuationDistanceNode = source.attenuationDistanceNode;
  9606. this.attenuationColorNode = source.attenuationColorNode;
  9607. this.dispersionNode = source.dispersionNode;
  9608. this.anisotropyNode = source.anisotropyNode;
  9609. return super.copy( source );
  9610. }
  9611. }
  9612. class SSSLightingModel extends PhysicalLightingModel {
  9613. constructor( useClearcoat, useSheen, useIridescence, useSSS ) {
  9614. super( useClearcoat, useSheen, useIridescence );
  9615. this.useSSS = useSSS;
  9616. }
  9617. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  9618. if ( this.useSSS === true ) {
  9619. const material = builder.material;
  9620. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  9621. const scatteringHalf = lightDirection.add( transformedNormalView.mul( thicknessDistortionNode ) ).normalize();
  9622. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  9623. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  9624. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  9625. }
  9626. super.direct( { lightDirection, lightColor, reflectedLight }, stack, builder );
  9627. }
  9628. }
  9629. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  9630. static get type() {
  9631. return 'MeshSSSNodeMaterial';
  9632. }
  9633. constructor( parameters ) {
  9634. super( parameters );
  9635. this.thicknessColorNode = null;
  9636. this.thicknessDistortionNode = float( 0.1 );
  9637. this.thicknessAmbientNode = float( 0.0 );
  9638. this.thicknessAttenuationNode = float( .1 );
  9639. this.thicknessPowerNode = float( 2.0 );
  9640. this.thicknessScaleNode = float( 10.0 );
  9641. }
  9642. get useSSS() {
  9643. return this.thicknessColorNode !== null;
  9644. }
  9645. setupLightingModel( /*builder*/ ) {
  9646. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useSSS );
  9647. }
  9648. copy( source ) {
  9649. this.thicknessColorNode = source.thicknessColorNode;
  9650. this.thicknessDistortionNode = source.thicknessDistortionNode;
  9651. this.thicknessAmbientNode = source.thicknessAmbientNode;
  9652. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  9653. this.thicknessPowerNode = source.thicknessPowerNode;
  9654. this.thicknessScaleNode = source.thicknessScaleNode;
  9655. return super.copy( source );
  9656. }
  9657. }
  9658. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  9659. // dotNL will be from -1.0 to 1.0
  9660. const dotNL = normal.dot( lightDirection );
  9661. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  9662. if ( builder.material.gradientMap ) {
  9663. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  9664. return vec3( gradientMap.r );
  9665. } else {
  9666. const fw = coord.fwidth().mul( 0.5 );
  9667. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  9668. }
  9669. } );
  9670. /**
  9671. * Represents the lighting model for a toon material. Used in {@link MeshToonNodeMaterial}.
  9672. *
  9673. * @augments LightingModel
  9674. */
  9675. class ToonLightingModel extends LightingModel {
  9676. /**
  9677. * Implements the direct lighting. Instead of using a conventional smooth irradiance, the irradiance is
  9678. * reduced to a small number of discrete shades to create a comic-like, flat look.
  9679. *
  9680. * @param {Object} input - The input data.
  9681. * @param {StackNode} stack - The current stack.
  9682. * @param {NodeBuilder} builder - The current node builder.
  9683. */
  9684. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  9685. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  9686. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  9687. }
  9688. /**
  9689. * Implements the indirect lighting.
  9690. *
  9691. * @param {ContextNode} input - The current node context.
  9692. * @param {StackNode} stack - The current stack.
  9693. * @param {NodeBuilder} builder - The current node builder.
  9694. */
  9695. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  9696. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  9697. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  9698. }
  9699. }
  9700. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  9701. class MeshToonNodeMaterial extends NodeMaterial {
  9702. static get type() {
  9703. return 'MeshToonNodeMaterial';
  9704. }
  9705. constructor( parameters ) {
  9706. super();
  9707. this.isMeshToonNodeMaterial = true;
  9708. this.lights = true;
  9709. this.setDefaultValues( _defaultValues$4 );
  9710. this.setValues( parameters );
  9711. }
  9712. setupLightingModel( /*builder*/ ) {
  9713. return new ToonLightingModel();
  9714. }
  9715. }
  9716. /**
  9717. * Can be used to compute texture coordinates for projecting a
  9718. * matcap onto a mesh. Used by {@link MeshMatcapNodeMaterial}.
  9719. *
  9720. * @augments TempNode
  9721. */
  9722. class MatcapUVNode extends TempNode {
  9723. static get type() {
  9724. return 'MatcapUVNode';
  9725. }
  9726. /**
  9727. * Constructs a new matcap uv node.
  9728. */
  9729. constructor() {
  9730. super( 'vec2' );
  9731. }
  9732. setup() {
  9733. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  9734. const y = positionViewDirection.cross( x );
  9735. return vec2( x.dot( transformedNormalView ), y.dot( transformedNormalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  9736. }
  9737. }
  9738. const matcapUV = /*@__PURE__*/ nodeImmutable( MatcapUVNode );
  9739. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  9740. class MeshMatcapNodeMaterial extends NodeMaterial {
  9741. static get type() {
  9742. return 'MeshMatcapNodeMaterial';
  9743. }
  9744. constructor( parameters ) {
  9745. super();
  9746. this.lights = false;
  9747. this.isMeshMatcapNodeMaterial = true;
  9748. this.setDefaultValues( _defaultValues$3 );
  9749. this.setValues( parameters );
  9750. }
  9751. setupVariants( builder ) {
  9752. const uv = matcapUV;
  9753. let matcapColor;
  9754. if ( builder.material.matcap ) {
  9755. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  9756. } else {
  9757. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  9758. }
  9759. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  9760. }
  9761. }
  9762. const _defaultValues$2 = /*@__PURE__*/ new PointsMaterial();
  9763. class PointsNodeMaterial extends NodeMaterial {
  9764. static get type() {
  9765. return 'PointsNodeMaterial';
  9766. }
  9767. constructor( parameters ) {
  9768. super();
  9769. this.isPointsNodeMaterial = true;
  9770. this.lights = false;
  9771. this.transparent = true;
  9772. this.sizeNode = null;
  9773. this.setDefaultValues( _defaultValues$2 );
  9774. this.setValues( parameters );
  9775. }
  9776. copy( source ) {
  9777. this.sizeNode = source.sizeNode;
  9778. return super.copy( source );
  9779. }
  9780. }
  9781. /**
  9782. * Applies a rotation to the given position node.
  9783. *
  9784. * @augments TempNode
  9785. */
  9786. class RotateNode extends TempNode {
  9787. static get type() {
  9788. return 'RotateNode';
  9789. }
  9790. /**
  9791. * Constructs a new rotate node.
  9792. *
  9793. * @param {Node} positionNode - The position node.
  9794. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  9795. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  9796. */
  9797. constructor( positionNode, rotationNode ) {
  9798. super();
  9799. /**
  9800. * The position node.
  9801. *
  9802. * @type {Node}
  9803. */
  9804. this.positionNode = positionNode;
  9805. /**
  9806. * Represents the rotation that is applied to the position node.
  9807. * Depending on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  9808. *
  9809. * @type {Node}
  9810. */
  9811. this.rotationNode = rotationNode;
  9812. }
  9813. /**
  9814. * The type of the {@link RotateNode#positionNode} defines the node's type.
  9815. *
  9816. * @param {NodeBuilder} builder - The current node builder.
  9817. * @return {String} The node's type.
  9818. */
  9819. getNodeType( builder ) {
  9820. return this.positionNode.getNodeType( builder );
  9821. }
  9822. setup( builder ) {
  9823. const { rotationNode, positionNode } = this;
  9824. const nodeType = this.getNodeType( builder );
  9825. if ( nodeType === 'vec2' ) {
  9826. const cosAngle = rotationNode.cos();
  9827. const sinAngle = rotationNode.sin();
  9828. const rotationMatrix = mat2(
  9829. cosAngle, sinAngle,
  9830. sinAngle.negate(), cosAngle
  9831. );
  9832. return rotationMatrix.mul( positionNode );
  9833. } else {
  9834. const rotation = rotationNode;
  9835. 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 ) );
  9836. 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 ) );
  9837. 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 ) );
  9838. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  9839. }
  9840. }
  9841. }
  9842. const rotate = /*@__PURE__*/ nodeProxy( RotateNode );
  9843. const _defaultValues$1 = /*@__PURE__*/ new SpriteMaterial();
  9844. class SpriteNodeMaterial extends NodeMaterial {
  9845. static get type() {
  9846. return 'SpriteNodeMaterial';
  9847. }
  9848. constructor( parameters ) {
  9849. super();
  9850. this.isSpriteNodeMaterial = true;
  9851. this.lights = false;
  9852. this._useSizeAttenuation = true;
  9853. this.positionNode = null;
  9854. this.rotationNode = null;
  9855. this.scaleNode = null;
  9856. this.setDefaultValues( _defaultValues$1 );
  9857. this.setValues( parameters );
  9858. }
  9859. setupPosition( { object, camera, context } ) {
  9860. const sizeAttenuation = this.sizeAttenuation;
  9861. // < VERTEX STAGE >
  9862. const { positionNode, rotationNode, scaleNode } = this;
  9863. const vertex = positionLocal;
  9864. let mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  9865. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  9866. if ( scaleNode !== null ) {
  9867. scale = scale.mul( scaleNode );
  9868. }
  9869. if ( ! sizeAttenuation ) {
  9870. if ( camera.isPerspectiveCamera ) {
  9871. scale = scale.mul( mvPosition.z.negate() );
  9872. } else {
  9873. const orthoScale = float( 2.0 ).div( cameraProjectionMatrix.element( 1 ).element( 1 ) );
  9874. scale = scale.mul( orthoScale.mul( 2 ) );
  9875. }
  9876. }
  9877. let alignedPosition = vertex.xy;
  9878. if ( object.center && object.center.isVector2 === true ) {
  9879. const center = reference$1( 'center', 'vec2' );
  9880. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  9881. }
  9882. alignedPosition = alignedPosition.mul( scale );
  9883. const rotation = float( rotationNode || materialRotation );
  9884. const rotatedPosition = rotate( alignedPosition, rotation );
  9885. mvPosition = vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  9886. const modelViewProjection = cameraProjectionMatrix.mul( mvPosition );
  9887. context.vertex = vertex;
  9888. return modelViewProjection;
  9889. }
  9890. copy( source ) {
  9891. this.positionNode = source.positionNode;
  9892. this.rotationNode = source.rotationNode;
  9893. this.scaleNode = source.scaleNode;
  9894. return super.copy( source );
  9895. }
  9896. get sizeAttenuation() {
  9897. return this._useSizeAttenuation;
  9898. }
  9899. set sizeAttenuation( value ) {
  9900. if ( this._useSizeAttenuation !== value ) {
  9901. this._useSizeAttenuation = value;
  9902. this.needsUpdate = true;
  9903. }
  9904. }
  9905. }
  9906. /**
  9907. * Represents lighting model for a shadow material. Used in {@link ShadowNodeMaterial}.
  9908. *
  9909. * @augments LightingModel
  9910. */
  9911. class ShadowMaskModel extends LightingModel {
  9912. /**
  9913. * Constructs a new shadow mask model.
  9914. */
  9915. constructor() {
  9916. super();
  9917. /**
  9918. * The shadow mask node.
  9919. *
  9920. * @type {Node}
  9921. */
  9922. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  9923. }
  9924. /**
  9925. * Only used to save the shadow mask.
  9926. *
  9927. * @param {Object} input - The input data.
  9928. */
  9929. direct( { shadowMask } ) {
  9930. this.shadowNode.mulAssign( shadowMask );
  9931. }
  9932. /**
  9933. * Uses the shadow mask to produce the final color.
  9934. *
  9935. * @param {ContextNode} input - The current node context.
  9936. */
  9937. finish( context ) {
  9938. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  9939. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  9940. }
  9941. }
  9942. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  9943. class ShadowNodeMaterial extends NodeMaterial {
  9944. static get type() {
  9945. return 'ShadowNodeMaterial';
  9946. }
  9947. constructor( parameters ) {
  9948. super();
  9949. this.isShadowNodeMaterial = true;
  9950. this.lights = true;
  9951. this.setDefaultValues( _defaultValues );
  9952. this.setValues( parameters );
  9953. }
  9954. setupLightingModel( /*builder*/ ) {
  9955. return new ShadowMaskModel();
  9956. }
  9957. }
  9958. const normal = Fn( ( { texture, uv } ) => {
  9959. const epsilon = 0.0001;
  9960. const ret = vec3().toVar();
  9961. If( uv.x.lessThan( epsilon ), () => {
  9962. ret.assign( vec3( 1, 0, 0 ) );
  9963. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  9964. ret.assign( vec3( 0, 1, 0 ) );
  9965. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  9966. ret.assign( vec3( 0, 0, 1 ) );
  9967. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  9968. ret.assign( vec3( - 1, 0, 0 ) );
  9969. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  9970. ret.assign( vec3( 0, - 1, 0 ) );
  9971. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  9972. ret.assign( vec3( 0, 0, - 1 ) );
  9973. } ).Else( () => {
  9974. const step = 0.01;
  9975. 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 );
  9976. 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 );
  9977. 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 );
  9978. ret.assign( vec3( x, y, z ) );
  9979. } );
  9980. return ret.normalize();
  9981. } );
  9982. class Texture3DNode extends TextureNode {
  9983. static get type() {
  9984. return 'Texture3DNode';
  9985. }
  9986. constructor( value, uvNode = null, levelNode = null ) {
  9987. super( value, uvNode, levelNode );
  9988. this.isTexture3DNode = true;
  9989. }
  9990. getInputType( /*builder*/ ) {
  9991. return 'texture3D';
  9992. }
  9993. getDefaultUV() {
  9994. return vec3( 0.5, 0.5, 0.5 );
  9995. }
  9996. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  9997. setupUV( builder, uvNode ) {
  9998. return uvNode;
  9999. }
  10000. generateUV( builder, uvNode ) {
  10001. return uvNode.build( builder, 'vec3' );
  10002. }
  10003. normal( uvNode ) {
  10004. return normal( { texture: this, uv: uvNode } );
  10005. }
  10006. }
  10007. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode );
  10008. class VolumeNodeMaterial extends NodeMaterial {
  10009. static get type() {
  10010. return 'VolumeNodeMaterial';
  10011. }
  10012. constructor( params = {} ) {
  10013. super();
  10014. this.lights = false;
  10015. this.isVolumeNodeMaterial = true;
  10016. this.testNode = null;
  10017. this.setValues( params );
  10018. }
  10019. setup( builder ) {
  10020. const map = texture3D( this.map, null, 0 );
  10021. const hitBox = Fn( ( { orig, dir } ) => {
  10022. const box_min = vec3( - 0.5 );
  10023. const box_max = vec3( 0.5 );
  10024. const inv_dir = dir.reciprocal();
  10025. const tmin_tmp = box_min.sub( orig ).mul( inv_dir );
  10026. const tmax_tmp = box_max.sub( orig ).mul( inv_dir );
  10027. const tmin = min$1( tmin_tmp, tmax_tmp );
  10028. const tmax = max$1( tmin_tmp, tmax_tmp );
  10029. const t0 = max$1( tmin.x, max$1( tmin.y, tmin.z ) );
  10030. const t1 = min$1( tmax.x, min$1( tmax.y, tmax.z ) );
  10031. return vec2( t0, t1 );
  10032. } );
  10033. this.fragmentNode = Fn( () => {
  10034. const vOrigin = varying( vec3( modelWorldMatrixInverse.mul( vec4( cameraPosition, 1.0 ) ) ) );
  10035. const vDirection = varying( positionGeometry.sub( vOrigin ) );
  10036. const rayDir = vDirection.normalize();
  10037. const bounds = vec2( hitBox( { orig: vOrigin, dir: rayDir } ) ).toVar();
  10038. bounds.x.greaterThan( bounds.y ).discard();
  10039. bounds.assign( vec2( max$1( bounds.x, 0.0 ), bounds.y ) );
  10040. const p = vec3( vOrigin.add( bounds.x.mul( rayDir ) ) ).toVar();
  10041. const inc = vec3( rayDir.abs().reciprocal() ).toVar();
  10042. const delta = float( min$1( inc.x, min$1( inc.y, inc.z ) ) ).toVar( 'delta' ); // used 'delta' name in loop
  10043. delta.divAssign( materialReference( 'steps', 'float' ) );
  10044. const ac = vec4( materialReference( 'base', 'color' ), 0.0 ).toVar();
  10045. Loop( { type: 'float', start: bounds.x, end: bounds.y, update: '+= delta' }, () => {
  10046. const d = property( 'float', 'd' ).assign( map.sample( p.add( 0.5 ) ).r );
  10047. if ( this.testNode !== null ) {
  10048. this.testNode( { map: map, mapValue: d, probe: p, finalColor: ac } ).append();
  10049. } else {
  10050. // default to show surface of mesh
  10051. ac.a.assign( 1 );
  10052. Break();
  10053. }
  10054. p.addAssign( rayDir.mul( delta ) );
  10055. } );
  10056. ac.a.equal( 0 ).discard();
  10057. return vec4( ac );
  10058. } )();
  10059. super.setup( builder );
  10060. }
  10061. }
  10062. class Animation {
  10063. constructor( nodes, info ) {
  10064. this.nodes = nodes;
  10065. this.info = info;
  10066. this._context = self;
  10067. this._animationLoop = null;
  10068. this._requestId = null;
  10069. }
  10070. start() {
  10071. const update = ( time, frame ) => {
  10072. this._requestId = this._context.requestAnimationFrame( update );
  10073. if ( this.info.autoReset === true ) this.info.reset();
  10074. this.nodes.nodeFrame.update();
  10075. this.info.frame = this.nodes.nodeFrame.frameId;
  10076. if ( this._animationLoop !== null ) this._animationLoop( time, frame );
  10077. };
  10078. update();
  10079. }
  10080. stop() {
  10081. this._context.cancelAnimationFrame( this._requestId );
  10082. this._requestId = null;
  10083. }
  10084. setAnimationLoop( callback ) {
  10085. this._animationLoop = callback;
  10086. }
  10087. setContext( context ) {
  10088. this._context = context;
  10089. }
  10090. dispose() {
  10091. this.stop();
  10092. }
  10093. }
  10094. class ChainMap {
  10095. constructor() {
  10096. this.weakMap = new WeakMap();
  10097. }
  10098. get( keys ) {
  10099. let map = this.weakMap;
  10100. for ( let i = 0; i < keys.length; i ++ ) {
  10101. map = map.get( keys[ i ] );
  10102. if ( map === undefined ) return undefined;
  10103. }
  10104. return map.get( keys[ keys.length - 1 ] );
  10105. }
  10106. set( keys, value ) {
  10107. let map = this.weakMap;
  10108. for ( let i = 0; i < keys.length; i ++ ) {
  10109. const key = keys[ i ];
  10110. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  10111. map = map.get( key );
  10112. }
  10113. return map.set( keys[ keys.length - 1 ], value );
  10114. }
  10115. delete( keys ) {
  10116. let map = this.weakMap;
  10117. for ( let i = 0; i < keys.length; i ++ ) {
  10118. map = map.get( keys[ i ] );
  10119. if ( map === undefined ) return false;
  10120. }
  10121. return map.delete( keys[ keys.length - 1 ] );
  10122. }
  10123. }
  10124. let _id$8 = 0;
  10125. function getKeys( obj ) {
  10126. const keys = Object.keys( obj );
  10127. let proto = Object.getPrototypeOf( obj );
  10128. while ( proto ) {
  10129. const descriptors = Object.getOwnPropertyDescriptors( proto );
  10130. for ( const key in descriptors ) {
  10131. if ( descriptors[ key ] !== undefined ) {
  10132. const descriptor = descriptors[ key ];
  10133. if ( descriptor && typeof descriptor.get === 'function' ) {
  10134. keys.push( key );
  10135. }
  10136. }
  10137. }
  10138. proto = Object.getPrototypeOf( proto );
  10139. }
  10140. return keys;
  10141. }
  10142. class RenderObject {
  10143. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  10144. this._nodes = nodes;
  10145. this._geometries = geometries;
  10146. this.id = _id$8 ++;
  10147. this.renderer = renderer;
  10148. this.object = object;
  10149. this.material = material;
  10150. this.scene = scene;
  10151. this.camera = camera;
  10152. this.lightsNode = lightsNode;
  10153. this.context = renderContext;
  10154. this.geometry = object.geometry;
  10155. this.version = material.version;
  10156. this.drawRange = null;
  10157. this.attributes = null;
  10158. this.pipeline = null;
  10159. this.vertexBuffers = null;
  10160. this.drawParams = null;
  10161. this.bundle = null;
  10162. this.clippingContext = clippingContext;
  10163. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  10164. this.initialNodesCacheKey = this.getDynamicCacheKey();
  10165. this.initialCacheKey = this.getCacheKey();
  10166. this._nodeBuilderState = null;
  10167. this._bindings = null;
  10168. this._monitor = null;
  10169. this.onDispose = null;
  10170. this.isRenderObject = true;
  10171. this.onMaterialDispose = () => {
  10172. this.dispose();
  10173. };
  10174. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  10175. }
  10176. updateClipping( parent ) {
  10177. this.clippingContext = parent;
  10178. }
  10179. get clippingNeedsUpdate() {
  10180. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  10181. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  10182. return true;
  10183. }
  10184. get hardwareClippingPlanes() {
  10185. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  10186. }
  10187. getNodeBuilderState() {
  10188. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  10189. }
  10190. getMonitor() {
  10191. return this._monitor || ( this._monitor = this.getNodeBuilderState().monitor );
  10192. }
  10193. getBindings() {
  10194. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  10195. }
  10196. getIndex() {
  10197. return this._geometries.getIndex( this );
  10198. }
  10199. getIndirect() {
  10200. return this._geometries.getIndirect( this );
  10201. }
  10202. getChainArray() {
  10203. return [ this.object, this.material, this.context, this.lightsNode ];
  10204. }
  10205. setGeometry( geometry ) {
  10206. this.geometry = geometry;
  10207. this.attributes = null;
  10208. }
  10209. getAttributes() {
  10210. if ( this.attributes !== null ) return this.attributes;
  10211. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  10212. const geometry = this.geometry;
  10213. const attributes = [];
  10214. const vertexBuffers = new Set();
  10215. for ( const nodeAttribute of nodeAttributes ) {
  10216. const attribute = nodeAttribute.node && nodeAttribute.node.attribute ? nodeAttribute.node.attribute : geometry.getAttribute( nodeAttribute.name );
  10217. if ( attribute === undefined ) continue;
  10218. attributes.push( attribute );
  10219. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  10220. vertexBuffers.add( bufferAttribute );
  10221. }
  10222. this.attributes = attributes;
  10223. this.vertexBuffers = Array.from( vertexBuffers.values() );
  10224. return attributes;
  10225. }
  10226. getVertexBuffers() {
  10227. if ( this.vertexBuffers === null ) this.getAttributes();
  10228. return this.vertexBuffers;
  10229. }
  10230. getDrawParameters() {
  10231. const { object, material, geometry, group, drawRange } = this;
  10232. const drawParams = this.drawParams || ( this.drawParams = {
  10233. vertexCount: 0,
  10234. firstVertex: 0,
  10235. instanceCount: 0,
  10236. firstInstance: 0
  10237. } );
  10238. const index = this.getIndex();
  10239. const hasIndex = ( index !== null );
  10240. const instanceCount = geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  10241. if ( instanceCount === 0 ) return null;
  10242. drawParams.instanceCount = instanceCount;
  10243. if ( object.isBatchedMesh === true ) return drawParams;
  10244. let rangeFactor = 1;
  10245. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  10246. rangeFactor = 2;
  10247. }
  10248. let firstVertex = drawRange.start * rangeFactor;
  10249. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  10250. if ( group !== null ) {
  10251. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  10252. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  10253. }
  10254. const position = geometry.attributes.position;
  10255. let itemCount = Infinity;
  10256. if ( hasIndex ) {
  10257. itemCount = index.count;
  10258. } else if ( position !== undefined && position !== null ) {
  10259. itemCount = position.count;
  10260. }
  10261. firstVertex = Math.max( firstVertex, 0 );
  10262. lastVertex = Math.min( lastVertex, itemCount );
  10263. const count = lastVertex - firstVertex;
  10264. if ( count < 0 || count === Infinity ) return null;
  10265. drawParams.vertexCount = count;
  10266. drawParams.firstVertex = firstVertex;
  10267. return drawParams;
  10268. }
  10269. getGeometryCacheKey() {
  10270. const { geometry } = this;
  10271. let cacheKey = '';
  10272. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  10273. const attribute = geometry.attributes[ name ];
  10274. cacheKey += name + ',';
  10275. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  10276. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  10277. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  10278. if ( attribute.normalized ) cacheKey += 'n,';
  10279. }
  10280. if ( geometry.index ) {
  10281. cacheKey += 'index,';
  10282. }
  10283. return cacheKey;
  10284. }
  10285. getMaterialCacheKey() {
  10286. const { object, material } = this;
  10287. let cacheKey = material.customProgramCacheKey();
  10288. for ( const property of getKeys( material ) ) {
  10289. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  10290. const value = material[ property ];
  10291. let valueKey;
  10292. if ( value !== null ) {
  10293. // some material values require a formatting
  10294. const type = typeof value;
  10295. if ( type === 'number' ) {
  10296. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  10297. } else if ( type === 'object' ) {
  10298. valueKey = '{';
  10299. if ( value.isTexture ) {
  10300. valueKey += value.mapping;
  10301. }
  10302. valueKey += '}';
  10303. } else {
  10304. valueKey = String( value );
  10305. }
  10306. } else {
  10307. valueKey = String( value );
  10308. }
  10309. cacheKey += /*property + ':' +*/ valueKey + ',';
  10310. }
  10311. cacheKey += this.clippingContextCacheKey + ',';
  10312. if ( object.geometry ) {
  10313. cacheKey += this.getGeometryCacheKey();
  10314. }
  10315. if ( object.skeleton ) {
  10316. cacheKey += object.skeleton.bones.length + ',';
  10317. }
  10318. if ( object.morphTargetInfluences ) {
  10319. cacheKey += object.morphTargetInfluences.length + ',';
  10320. }
  10321. if ( object.isBatchedMesh ) {
  10322. cacheKey += object._matricesTexture.uuid + ',';
  10323. if ( object._colorsTexture !== null ) {
  10324. cacheKey += object._colorsTexture.uuid + ',';
  10325. }
  10326. }
  10327. if ( object.count > 1 ) {
  10328. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  10329. cacheKey += object.uuid + ',';
  10330. }
  10331. cacheKey += object.receiveShadow + ',';
  10332. return hashString( cacheKey );
  10333. }
  10334. get needsGeometryUpdate() {
  10335. return this.geometry.id !== this.object.geometry.id;
  10336. }
  10337. get needsUpdate() {
  10338. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  10339. }
  10340. getDynamicCacheKey() {
  10341. // Environment Nodes Cache Key
  10342. let cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  10343. if ( this.object.receiveShadow ) {
  10344. cacheKey += 1;
  10345. }
  10346. return cacheKey;
  10347. }
  10348. getCacheKey() {
  10349. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  10350. }
  10351. dispose() {
  10352. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  10353. this.onDispose();
  10354. }
  10355. }
  10356. const chainArray = [];
  10357. class RenderObjects {
  10358. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  10359. this.renderer = renderer;
  10360. this.nodes = nodes;
  10361. this.geometries = geometries;
  10362. this.pipelines = pipelines;
  10363. this.bindings = bindings;
  10364. this.info = info;
  10365. this.chainMaps = {};
  10366. }
  10367. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  10368. const chainMap = this.getChainMap( passId );
  10369. // reuse chainArray
  10370. chainArray[ 0 ] = object;
  10371. chainArray[ 1 ] = material;
  10372. chainArray[ 2 ] = renderContext;
  10373. chainArray[ 3 ] = lightsNode;
  10374. let renderObject = chainMap.get( chainArray );
  10375. if ( renderObject === undefined ) {
  10376. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  10377. chainMap.set( chainArray, renderObject );
  10378. } else {
  10379. renderObject.updateClipping( clippingContext );
  10380. if ( renderObject.needsGeometryUpdate ) {
  10381. renderObject.setGeometry( object.geometry );
  10382. }
  10383. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  10384. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  10385. renderObject.dispose();
  10386. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  10387. } else {
  10388. renderObject.version = material.version;
  10389. }
  10390. }
  10391. }
  10392. return renderObject;
  10393. }
  10394. getChainMap( passId = 'default' ) {
  10395. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  10396. }
  10397. dispose() {
  10398. this.chainMaps = {};
  10399. }
  10400. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  10401. const chainMap = this.getChainMap( passId );
  10402. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  10403. renderObject.onDispose = () => {
  10404. this.pipelines.delete( renderObject );
  10405. this.bindings.delete( renderObject );
  10406. this.nodes.delete( renderObject );
  10407. chainMap.delete( renderObject.getChainArray() );
  10408. };
  10409. return renderObject;
  10410. }
  10411. }
  10412. class DataMap {
  10413. constructor() {
  10414. this.data = new WeakMap();
  10415. }
  10416. get( object ) {
  10417. let map = this.data.get( object );
  10418. if ( map === undefined ) {
  10419. map = {};
  10420. this.data.set( object, map );
  10421. }
  10422. return map;
  10423. }
  10424. delete( object ) {
  10425. let map;
  10426. if ( this.data.has( object ) ) {
  10427. map = this.data.get( object );
  10428. this.data.delete( object );
  10429. }
  10430. return map;
  10431. }
  10432. has( object ) {
  10433. return this.data.has( object );
  10434. }
  10435. dispose() {
  10436. this.data = new WeakMap();
  10437. }
  10438. }
  10439. const AttributeType = {
  10440. VERTEX: 1,
  10441. INDEX: 2,
  10442. STORAGE: 3,
  10443. INDIRECT: 4
  10444. };
  10445. // size of a chunk in bytes (STD140 layout)
  10446. const GPU_CHUNK_BYTES = 16;
  10447. // @TODO: Move to src/constants.js
  10448. const BlendColorFactor = 211;
  10449. const OneMinusBlendColorFactor = 212;
  10450. class Attributes extends DataMap {
  10451. constructor( backend ) {
  10452. super();
  10453. this.backend = backend;
  10454. }
  10455. delete( attribute ) {
  10456. const attributeData = super.delete( attribute );
  10457. if ( attributeData !== undefined ) {
  10458. this.backend.destroyAttribute( attribute );
  10459. }
  10460. return attributeData;
  10461. }
  10462. update( attribute, type ) {
  10463. const data = this.get( attribute );
  10464. if ( data.version === undefined ) {
  10465. if ( type === AttributeType.VERTEX ) {
  10466. this.backend.createAttribute( attribute );
  10467. } else if ( type === AttributeType.INDEX ) {
  10468. this.backend.createIndexAttribute( attribute );
  10469. } else if ( type === AttributeType.STORAGE ) {
  10470. this.backend.createStorageAttribute( attribute );
  10471. } else if ( type === AttributeType.INDIRECT ) {
  10472. this.backend.createIndirectStorageAttribute( attribute );
  10473. }
  10474. data.version = this._getBufferAttribute( attribute ).version;
  10475. } else {
  10476. const bufferAttribute = this._getBufferAttribute( attribute );
  10477. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  10478. this.backend.updateAttribute( attribute );
  10479. data.version = bufferAttribute.version;
  10480. }
  10481. }
  10482. }
  10483. _getBufferAttribute( attribute ) {
  10484. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  10485. return attribute;
  10486. }
  10487. }
  10488. function arrayNeedsUint32( array ) {
  10489. // assumes larger values usually on last
  10490. for ( let i = array.length - 1; i >= 0; -- i ) {
  10491. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  10492. }
  10493. return false;
  10494. }
  10495. function getWireframeVersion( geometry ) {
  10496. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  10497. }
  10498. function getWireframeIndex( geometry ) {
  10499. const indices = [];
  10500. const geometryIndex = geometry.index;
  10501. const geometryPosition = geometry.attributes.position;
  10502. if ( geometryIndex !== null ) {
  10503. const array = geometryIndex.array;
  10504. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  10505. const a = array[ i + 0 ];
  10506. const b = array[ i + 1 ];
  10507. const c = array[ i + 2 ];
  10508. indices.push( a, b, b, c, c, a );
  10509. }
  10510. } else {
  10511. const array = geometryPosition.array;
  10512. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  10513. const a = i + 0;
  10514. const b = i + 1;
  10515. const c = i + 2;
  10516. indices.push( a, b, b, c, c, a );
  10517. }
  10518. }
  10519. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  10520. attribute.version = getWireframeVersion( geometry );
  10521. return attribute;
  10522. }
  10523. class Geometries extends DataMap {
  10524. constructor( attributes, info ) {
  10525. super();
  10526. this.attributes = attributes;
  10527. this.info = info;
  10528. this.wireframes = new WeakMap();
  10529. this.attributeCall = new WeakMap();
  10530. }
  10531. has( renderObject ) {
  10532. const geometry = renderObject.geometry;
  10533. return super.has( geometry ) && this.get( geometry ).initialized === true;
  10534. }
  10535. updateForRender( renderObject ) {
  10536. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  10537. this.updateAttributes( renderObject );
  10538. }
  10539. initGeometry( renderObject ) {
  10540. const geometry = renderObject.geometry;
  10541. const geometryData = this.get( geometry );
  10542. geometryData.initialized = true;
  10543. this.info.memory.geometries ++;
  10544. const onDispose = () => {
  10545. this.info.memory.geometries --;
  10546. const index = geometry.index;
  10547. const geometryAttributes = renderObject.getAttributes();
  10548. if ( index !== null ) {
  10549. this.attributes.delete( index );
  10550. }
  10551. for ( const geometryAttribute of geometryAttributes ) {
  10552. this.attributes.delete( geometryAttribute );
  10553. }
  10554. const wireframeAttribute = this.wireframes.get( geometry );
  10555. if ( wireframeAttribute !== undefined ) {
  10556. this.attributes.delete( wireframeAttribute );
  10557. }
  10558. geometry.removeEventListener( 'dispose', onDispose );
  10559. };
  10560. geometry.addEventListener( 'dispose', onDispose );
  10561. }
  10562. updateAttributes( renderObject ) {
  10563. // attributes
  10564. const attributes = renderObject.getAttributes();
  10565. for ( const attribute of attributes ) {
  10566. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  10567. this.updateAttribute( attribute, AttributeType.STORAGE );
  10568. } else {
  10569. this.updateAttribute( attribute, AttributeType.VERTEX );
  10570. }
  10571. }
  10572. // indexes
  10573. const index = this.getIndex( renderObject );
  10574. if ( index !== null ) {
  10575. this.updateAttribute( index, AttributeType.INDEX );
  10576. }
  10577. // indirect
  10578. const indirect = renderObject.geometry.indirect;
  10579. if ( indirect !== null ) {
  10580. this.updateAttribute( indirect, AttributeType.INDIRECT );
  10581. }
  10582. }
  10583. updateAttribute( attribute, type ) {
  10584. const callId = this.info.render.calls;
  10585. if ( ! attribute.isInterleavedBufferAttribute ) {
  10586. if ( this.attributeCall.get( attribute ) !== callId ) {
  10587. this.attributes.update( attribute, type );
  10588. this.attributeCall.set( attribute, callId );
  10589. }
  10590. } else {
  10591. if ( this.attributeCall.get( attribute ) === undefined ) {
  10592. this.attributes.update( attribute, type );
  10593. this.attributeCall.set( attribute, callId );
  10594. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  10595. this.attributes.update( attribute, type );
  10596. this.attributeCall.set( attribute.data, callId );
  10597. this.attributeCall.set( attribute, callId );
  10598. }
  10599. }
  10600. }
  10601. getIndirect( renderObject ) {
  10602. return renderObject.geometry.indirect;
  10603. }
  10604. getIndex( renderObject ) {
  10605. const { geometry, material } = renderObject;
  10606. let index = geometry.index;
  10607. if ( material.wireframe === true ) {
  10608. const wireframes = this.wireframes;
  10609. let wireframeAttribute = wireframes.get( geometry );
  10610. if ( wireframeAttribute === undefined ) {
  10611. wireframeAttribute = getWireframeIndex( geometry );
  10612. wireframes.set( geometry, wireframeAttribute );
  10613. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  10614. this.attributes.delete( wireframeAttribute );
  10615. wireframeAttribute = getWireframeIndex( geometry );
  10616. wireframes.set( geometry, wireframeAttribute );
  10617. }
  10618. index = wireframeAttribute;
  10619. }
  10620. return index;
  10621. }
  10622. }
  10623. class Info {
  10624. constructor() {
  10625. this.autoReset = true;
  10626. this.frame = 0;
  10627. this.calls = 0;
  10628. this.render = {
  10629. calls: 0,
  10630. frameCalls: 0,
  10631. drawCalls: 0,
  10632. triangles: 0,
  10633. points: 0,
  10634. lines: 0,
  10635. timestamp: 0,
  10636. previousFrameCalls: 0,
  10637. timestampCalls: 0
  10638. };
  10639. this.compute = {
  10640. calls: 0,
  10641. frameCalls: 0,
  10642. timestamp: 0,
  10643. previousFrameCalls: 0,
  10644. timestampCalls: 0
  10645. };
  10646. this.memory = {
  10647. geometries: 0,
  10648. textures: 0
  10649. };
  10650. }
  10651. update( object, count, instanceCount ) {
  10652. this.render.drawCalls ++;
  10653. if ( object.isMesh || object.isSprite ) {
  10654. this.render.triangles += instanceCount * ( count / 3 );
  10655. } else if ( object.isPoints ) {
  10656. this.render.points += instanceCount * count;
  10657. } else if ( object.isLineSegments ) {
  10658. this.render.lines += instanceCount * ( count / 2 );
  10659. } else if ( object.isLine ) {
  10660. this.render.lines += instanceCount * ( count - 1 );
  10661. } else {
  10662. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  10663. }
  10664. }
  10665. updateTimestamp( type, time ) {
  10666. if ( this[ type ].timestampCalls === 0 ) {
  10667. this[ type ].timestamp = 0;
  10668. }
  10669. this[ type ].timestamp += time;
  10670. this[ type ].timestampCalls ++;
  10671. if ( this[ type ].timestampCalls >= this[ type ].previousFrameCalls ) {
  10672. this[ type ].timestampCalls = 0;
  10673. }
  10674. }
  10675. reset() {
  10676. const previousRenderFrameCalls = this.render.frameCalls;
  10677. this.render.previousFrameCalls = previousRenderFrameCalls;
  10678. const previousComputeFrameCalls = this.compute.frameCalls;
  10679. this.compute.previousFrameCalls = previousComputeFrameCalls;
  10680. this.render.drawCalls = 0;
  10681. this.render.frameCalls = 0;
  10682. this.compute.frameCalls = 0;
  10683. this.render.triangles = 0;
  10684. this.render.points = 0;
  10685. this.render.lines = 0;
  10686. }
  10687. dispose() {
  10688. this.reset();
  10689. this.calls = 0;
  10690. this.render.calls = 0;
  10691. this.compute.calls = 0;
  10692. this.render.timestamp = 0;
  10693. this.compute.timestamp = 0;
  10694. this.memory.geometries = 0;
  10695. this.memory.textures = 0;
  10696. }
  10697. }
  10698. class Pipeline {
  10699. constructor( cacheKey ) {
  10700. this.cacheKey = cacheKey;
  10701. this.usedTimes = 0;
  10702. }
  10703. }
  10704. class RenderPipeline extends Pipeline {
  10705. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  10706. super( cacheKey );
  10707. this.vertexProgram = vertexProgram;
  10708. this.fragmentProgram = fragmentProgram;
  10709. }
  10710. }
  10711. class ComputePipeline extends Pipeline {
  10712. constructor( cacheKey, computeProgram ) {
  10713. super( cacheKey );
  10714. this.computeProgram = computeProgram;
  10715. this.isComputePipeline = true;
  10716. }
  10717. }
  10718. let _id$7 = 0;
  10719. class ProgrammableStage {
  10720. constructor( code, type, transforms = null, attributes = null ) {
  10721. this.id = _id$7 ++;
  10722. this.code = code;
  10723. this.stage = type;
  10724. this.transforms = transforms;
  10725. this.attributes = attributes;
  10726. this.usedTimes = 0;
  10727. }
  10728. }
  10729. class Pipelines extends DataMap {
  10730. constructor( backend, nodes ) {
  10731. super();
  10732. this.backend = backend;
  10733. this.nodes = nodes;
  10734. this.bindings = null; // set by the bindings
  10735. this.caches = new Map();
  10736. this.programs = {
  10737. vertex: new Map(),
  10738. fragment: new Map(),
  10739. compute: new Map()
  10740. };
  10741. }
  10742. getForCompute( computeNode, bindings ) {
  10743. const { backend } = this;
  10744. const data = this.get( computeNode );
  10745. if ( this._needsComputeUpdate( computeNode ) ) {
  10746. const previousPipeline = data.pipeline;
  10747. if ( previousPipeline ) {
  10748. previousPipeline.usedTimes --;
  10749. previousPipeline.computeProgram.usedTimes --;
  10750. }
  10751. // get shader
  10752. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  10753. // programmable stage
  10754. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  10755. if ( stageCompute === undefined ) {
  10756. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  10757. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  10758. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  10759. backend.createProgram( stageCompute );
  10760. }
  10761. // determine compute pipeline
  10762. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  10763. let pipeline = this.caches.get( cacheKey );
  10764. if ( pipeline === undefined ) {
  10765. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  10766. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  10767. }
  10768. // keep track of all used times
  10769. pipeline.usedTimes ++;
  10770. stageCompute.usedTimes ++;
  10771. //
  10772. data.version = computeNode.version;
  10773. data.pipeline = pipeline;
  10774. }
  10775. return data.pipeline;
  10776. }
  10777. getForRender( renderObject, promises = null ) {
  10778. const { backend } = this;
  10779. const data = this.get( renderObject );
  10780. if ( this._needsRenderUpdate( renderObject ) ) {
  10781. const previousPipeline = data.pipeline;
  10782. if ( previousPipeline ) {
  10783. previousPipeline.usedTimes --;
  10784. previousPipeline.vertexProgram.usedTimes --;
  10785. previousPipeline.fragmentProgram.usedTimes --;
  10786. }
  10787. // get shader
  10788. const nodeBuilderState = renderObject.getNodeBuilderState();
  10789. // programmable stages
  10790. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  10791. if ( stageVertex === undefined ) {
  10792. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  10793. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex' );
  10794. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  10795. backend.createProgram( stageVertex );
  10796. }
  10797. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  10798. if ( stageFragment === undefined ) {
  10799. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  10800. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment' );
  10801. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  10802. backend.createProgram( stageFragment );
  10803. }
  10804. // determine render pipeline
  10805. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  10806. let pipeline = this.caches.get( cacheKey );
  10807. if ( pipeline === undefined ) {
  10808. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  10809. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  10810. } else {
  10811. renderObject.pipeline = pipeline;
  10812. }
  10813. // keep track of all used times
  10814. pipeline.usedTimes ++;
  10815. stageVertex.usedTimes ++;
  10816. stageFragment.usedTimes ++;
  10817. //
  10818. data.pipeline = pipeline;
  10819. }
  10820. return data.pipeline;
  10821. }
  10822. delete( object ) {
  10823. const pipeline = this.get( object ).pipeline;
  10824. if ( pipeline ) {
  10825. // pipeline
  10826. pipeline.usedTimes --;
  10827. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  10828. // programs
  10829. if ( pipeline.isComputePipeline ) {
  10830. pipeline.computeProgram.usedTimes --;
  10831. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  10832. } else {
  10833. pipeline.fragmentProgram.usedTimes --;
  10834. pipeline.vertexProgram.usedTimes --;
  10835. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  10836. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  10837. }
  10838. }
  10839. return super.delete( object );
  10840. }
  10841. dispose() {
  10842. super.dispose();
  10843. this.caches = new Map();
  10844. this.programs = {
  10845. vertex: new Map(),
  10846. fragment: new Map(),
  10847. compute: new Map()
  10848. };
  10849. }
  10850. updateForRender( renderObject ) {
  10851. this.getForRender( renderObject );
  10852. }
  10853. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  10854. // check for existing pipeline
  10855. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  10856. let pipeline = this.caches.get( cacheKey );
  10857. if ( pipeline === undefined ) {
  10858. pipeline = new ComputePipeline( cacheKey, stageCompute );
  10859. this.caches.set( cacheKey, pipeline );
  10860. this.backend.createComputePipeline( pipeline, bindings );
  10861. }
  10862. return pipeline;
  10863. }
  10864. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  10865. // check for existing pipeline
  10866. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  10867. let pipeline = this.caches.get( cacheKey );
  10868. if ( pipeline === undefined ) {
  10869. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  10870. this.caches.set( cacheKey, pipeline );
  10871. renderObject.pipeline = pipeline;
  10872. this.backend.createRenderPipeline( renderObject, promises );
  10873. }
  10874. return pipeline;
  10875. }
  10876. _getComputeCacheKey( computeNode, stageCompute ) {
  10877. return computeNode.id + ',' + stageCompute.id;
  10878. }
  10879. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  10880. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  10881. }
  10882. _releasePipeline( pipeline ) {
  10883. this.caches.delete( pipeline.cacheKey );
  10884. }
  10885. _releaseProgram( program ) {
  10886. const code = program.code;
  10887. const stage = program.stage;
  10888. this.programs[ stage ].delete( code );
  10889. }
  10890. _needsComputeUpdate( computeNode ) {
  10891. const data = this.get( computeNode );
  10892. return data.pipeline === undefined || data.version !== computeNode.version;
  10893. }
  10894. _needsRenderUpdate( renderObject ) {
  10895. const data = this.get( renderObject );
  10896. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  10897. }
  10898. }
  10899. class Bindings extends DataMap {
  10900. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  10901. super();
  10902. this.backend = backend;
  10903. this.textures = textures;
  10904. this.pipelines = pipelines;
  10905. this.attributes = attributes;
  10906. this.nodes = nodes;
  10907. this.info = info;
  10908. this.pipelines.bindings = this; // assign bindings to pipelines
  10909. }
  10910. getForRender( renderObject ) {
  10911. const bindings = renderObject.getBindings();
  10912. for ( const bindGroup of bindings ) {
  10913. const groupData = this.get( bindGroup );
  10914. if ( groupData.bindGroup === undefined ) {
  10915. // each object defines an array of bindings (ubos, textures, samplers etc.)
  10916. this._init( bindGroup );
  10917. this.backend.createBindings( bindGroup, bindings, 0 );
  10918. groupData.bindGroup = bindGroup;
  10919. }
  10920. }
  10921. return bindings;
  10922. }
  10923. getForCompute( computeNode ) {
  10924. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  10925. for ( const bindGroup of bindings ) {
  10926. const groupData = this.get( bindGroup );
  10927. if ( groupData.bindGroup === undefined ) {
  10928. this._init( bindGroup );
  10929. this.backend.createBindings( bindGroup, bindings, 0 );
  10930. groupData.bindGroup = bindGroup;
  10931. }
  10932. }
  10933. return bindings;
  10934. }
  10935. updateForCompute( computeNode ) {
  10936. this._updateBindings( this.getForCompute( computeNode ) );
  10937. }
  10938. updateForRender( renderObject ) {
  10939. this._updateBindings( this.getForRender( renderObject ) );
  10940. }
  10941. _updateBindings( bindings ) {
  10942. for ( const bindGroup of bindings ) {
  10943. this._update( bindGroup, bindings );
  10944. }
  10945. }
  10946. _init( bindGroup ) {
  10947. for ( const binding of bindGroup.bindings ) {
  10948. if ( binding.isSampledTexture ) {
  10949. this.textures.updateTexture( binding.texture );
  10950. } else if ( binding.isStorageBuffer ) {
  10951. const attribute = binding.attribute;
  10952. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  10953. this.attributes.update( attribute, attributeType );
  10954. }
  10955. }
  10956. }
  10957. _update( bindGroup, bindings ) {
  10958. const { backend } = this;
  10959. let needsBindingsUpdate = false;
  10960. let cacheBindings = true;
  10961. let cacheIndex = 0;
  10962. let version = 0;
  10963. // iterate over all bindings and check if buffer updates or a new binding group is required
  10964. for ( const binding of bindGroup.bindings ) {
  10965. if ( binding.isNodeUniformsGroup ) {
  10966. const updated = this.nodes.updateGroup( binding );
  10967. if ( ! updated ) continue;
  10968. }
  10969. if ( binding.isUniformBuffer ) {
  10970. const updated = binding.update();
  10971. if ( updated ) {
  10972. backend.updateBinding( binding );
  10973. }
  10974. } else if ( binding.isSampler ) {
  10975. binding.update();
  10976. } else if ( binding.isSampledTexture ) {
  10977. const texturesTextureData = this.textures.get( binding.texture );
  10978. if ( binding.needsBindingsUpdate( texturesTextureData.generation ) ) needsBindingsUpdate = true;
  10979. const updated = binding.update();
  10980. const texture = binding.texture;
  10981. if ( updated ) {
  10982. this.textures.updateTexture( texture );
  10983. }
  10984. const textureData = backend.get( texture );
  10985. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  10986. cacheBindings = false;
  10987. } else {
  10988. cacheIndex = cacheIndex * 10 + texture.id;
  10989. version += texture.version;
  10990. }
  10991. if ( backend.isWebGPUBackend === true && textureData.texture === undefined && textureData.externalTexture === undefined ) {
  10992. // TODO: Remove this once we found why updated === false isn't bound to a texture in the WebGPU backend
  10993. console.error( 'Bindings._update: binding should be available:', binding, updated, texture, binding.textureNode.value, needsBindingsUpdate );
  10994. this.textures.updateTexture( texture );
  10995. needsBindingsUpdate = true;
  10996. }
  10997. if ( texture.isStorageTexture === true ) {
  10998. const textureData = this.get( texture );
  10999. if ( binding.store === true ) {
  11000. textureData.needsMipmap = true;
  11001. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  11002. this.backend.generateMipmaps( texture );
  11003. textureData.needsMipmap = false;
  11004. }
  11005. }
  11006. }
  11007. }
  11008. if ( needsBindingsUpdate === true ) {
  11009. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  11010. }
  11011. }
  11012. }
  11013. function painterSortStable( a, b ) {
  11014. if ( a.groupOrder !== b.groupOrder ) {
  11015. return a.groupOrder - b.groupOrder;
  11016. } else if ( a.renderOrder !== b.renderOrder ) {
  11017. return a.renderOrder - b.renderOrder;
  11018. } else if ( a.material.id !== b.material.id ) {
  11019. return a.material.id - b.material.id;
  11020. } else if ( a.z !== b.z ) {
  11021. return a.z - b.z;
  11022. } else {
  11023. return a.id - b.id;
  11024. }
  11025. }
  11026. function reversePainterSortStable( a, b ) {
  11027. if ( a.groupOrder !== b.groupOrder ) {
  11028. return a.groupOrder - b.groupOrder;
  11029. } else if ( a.renderOrder !== b.renderOrder ) {
  11030. return a.renderOrder - b.renderOrder;
  11031. } else if ( a.z !== b.z ) {
  11032. return b.z - a.z;
  11033. } else {
  11034. return a.id - b.id;
  11035. }
  11036. }
  11037. function needsDoublePass( material ) {
  11038. const hasTransmission = material.transmission > 0 || material.transmissionNode;
  11039. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  11040. }
  11041. class RenderList {
  11042. constructor( lighting, scene, camera ) {
  11043. this.renderItems = [];
  11044. this.renderItemsIndex = 0;
  11045. this.opaque = [];
  11046. this.transparentDoublePass = [];
  11047. this.transparent = [];
  11048. this.bundles = [];
  11049. this.lightsNode = lighting.getNode( scene, camera );
  11050. this.lightsArray = [];
  11051. this.scene = scene;
  11052. this.camera = camera;
  11053. this.occlusionQueryCount = 0;
  11054. }
  11055. begin() {
  11056. this.renderItemsIndex = 0;
  11057. this.opaque.length = 0;
  11058. this.transparentDoublePass.length = 0;
  11059. this.transparent.length = 0;
  11060. this.bundles.length = 0;
  11061. this.lightsArray.length = 0;
  11062. this.occlusionQueryCount = 0;
  11063. return this;
  11064. }
  11065. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  11066. let renderItem = this.renderItems[ this.renderItemsIndex ];
  11067. if ( renderItem === undefined ) {
  11068. renderItem = {
  11069. id: object.id,
  11070. object: object,
  11071. geometry: geometry,
  11072. material: material,
  11073. groupOrder: groupOrder,
  11074. renderOrder: object.renderOrder,
  11075. z: z,
  11076. group: group,
  11077. clippingContext: clippingContext
  11078. };
  11079. this.renderItems[ this.renderItemsIndex ] = renderItem;
  11080. } else {
  11081. renderItem.id = object.id;
  11082. renderItem.object = object;
  11083. renderItem.geometry = geometry;
  11084. renderItem.material = material;
  11085. renderItem.groupOrder = groupOrder;
  11086. renderItem.renderOrder = object.renderOrder;
  11087. renderItem.z = z;
  11088. renderItem.group = group;
  11089. renderItem.clippingContext = clippingContext;
  11090. }
  11091. this.renderItemsIndex ++;
  11092. return renderItem;
  11093. }
  11094. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  11095. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  11096. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  11097. if ( material.transparent === true || material.transmission > 0 ) {
  11098. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  11099. this.transparent.push( renderItem );
  11100. } else {
  11101. this.opaque.push( renderItem );
  11102. }
  11103. }
  11104. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  11105. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  11106. if ( material.transparent === true || material.transmission > 0 ) {
  11107. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  11108. this.transparent.unshift( renderItem );
  11109. } else {
  11110. this.opaque.unshift( renderItem );
  11111. }
  11112. }
  11113. pushBundle( group ) {
  11114. this.bundles.push( group );
  11115. }
  11116. pushLight( light ) {
  11117. this.lightsArray.push( light );
  11118. }
  11119. sort( customOpaqueSort, customTransparentSort ) {
  11120. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  11121. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  11122. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  11123. }
  11124. finish() {
  11125. // update lights
  11126. this.lightsNode.setLights( this.lightsArray );
  11127. // Clear references from inactive renderItems in the list
  11128. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  11129. const renderItem = this.renderItems[ i ];
  11130. if ( renderItem.id === null ) break;
  11131. renderItem.id = null;
  11132. renderItem.object = null;
  11133. renderItem.geometry = null;
  11134. renderItem.material = null;
  11135. renderItem.groupOrder = null;
  11136. renderItem.renderOrder = null;
  11137. renderItem.z = null;
  11138. renderItem.group = null;
  11139. renderItem.clippingContext = null;
  11140. }
  11141. }
  11142. }
  11143. class RenderLists {
  11144. constructor( lighting ) {
  11145. this.lighting = lighting;
  11146. this.lists = new ChainMap();
  11147. }
  11148. get( scene, camera ) {
  11149. const lists = this.lists;
  11150. const keys = [ scene, camera ];
  11151. let list = lists.get( keys );
  11152. if ( list === undefined ) {
  11153. list = new RenderList( this.lighting, scene, camera );
  11154. lists.set( keys, list );
  11155. }
  11156. return list;
  11157. }
  11158. dispose() {
  11159. this.lists = new ChainMap();
  11160. }
  11161. }
  11162. let id = 0;
  11163. class RenderContext {
  11164. constructor() {
  11165. this.id = id ++;
  11166. this.color = true;
  11167. this.clearColor = true;
  11168. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  11169. this.depth = true;
  11170. this.clearDepth = true;
  11171. this.clearDepthValue = 1;
  11172. this.stencil = false;
  11173. this.clearStencil = true;
  11174. this.clearStencilValue = 1;
  11175. this.viewport = false;
  11176. this.viewportValue = new Vector4();
  11177. this.scissor = false;
  11178. this.scissorValue = new Vector4();
  11179. this.textures = null;
  11180. this.depthTexture = null;
  11181. this.activeCubeFace = 0;
  11182. this.sampleCount = 1;
  11183. this.width = 0;
  11184. this.height = 0;
  11185. this.isRenderContext = true;
  11186. }
  11187. getCacheKey() {
  11188. return getCacheKey( this );
  11189. }
  11190. }
  11191. function getCacheKey( renderContext ) {
  11192. const { textures, activeCubeFace } = renderContext;
  11193. const values = [ activeCubeFace ];
  11194. for ( const texture of textures ) {
  11195. values.push( texture.id );
  11196. }
  11197. return hashArray( values );
  11198. }
  11199. class RenderContexts {
  11200. constructor() {
  11201. this.chainMaps = {};
  11202. }
  11203. get( scene, camera, renderTarget = null ) {
  11204. const chainKey = [ scene, camera ];
  11205. let attachmentState;
  11206. if ( renderTarget === null ) {
  11207. attachmentState = 'default';
  11208. } else {
  11209. const format = renderTarget.texture.format;
  11210. const count = renderTarget.textures.length;
  11211. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  11212. }
  11213. const chainMap = this.getChainMap( attachmentState );
  11214. let renderState = chainMap.get( chainKey );
  11215. if ( renderState === undefined ) {
  11216. renderState = new RenderContext();
  11217. chainMap.set( chainKey, renderState );
  11218. }
  11219. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  11220. return renderState;
  11221. }
  11222. getChainMap( attachmentState ) {
  11223. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  11224. }
  11225. dispose() {
  11226. this.chainMaps = {};
  11227. }
  11228. }
  11229. const _size$3 = /*@__PURE__*/ new Vector3();
  11230. class Textures extends DataMap {
  11231. constructor( renderer, backend, info ) {
  11232. super();
  11233. this.renderer = renderer;
  11234. this.backend = backend;
  11235. this.info = info;
  11236. }
  11237. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  11238. const renderTargetData = this.get( renderTarget );
  11239. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  11240. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  11241. const textures = renderTarget.textures;
  11242. const size = this.getSize( textures[ 0 ] );
  11243. const mipWidth = size.width >> activeMipmapLevel;
  11244. const mipHeight = size.height >> activeMipmapLevel;
  11245. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  11246. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  11247. let textureNeedsUpdate = false;
  11248. if ( depthTexture === undefined && useDepthTexture ) {
  11249. depthTexture = new DepthTexture();
  11250. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  11251. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  11252. depthTexture.image.width = mipWidth;
  11253. depthTexture.image.height = mipHeight;
  11254. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  11255. }
  11256. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  11257. textureNeedsUpdate = true;
  11258. if ( depthTexture ) {
  11259. depthTexture.needsUpdate = true;
  11260. depthTexture.image.width = mipWidth;
  11261. depthTexture.image.height = mipHeight;
  11262. }
  11263. }
  11264. renderTargetData.width = size.width;
  11265. renderTargetData.height = size.height;
  11266. renderTargetData.textures = textures;
  11267. renderTargetData.depthTexture = depthTexture || null;
  11268. renderTargetData.depth = renderTarget.depthBuffer;
  11269. renderTargetData.stencil = renderTarget.stencilBuffer;
  11270. renderTargetData.renderTarget = renderTarget;
  11271. if ( renderTargetData.sampleCount !== sampleCount ) {
  11272. textureNeedsUpdate = true;
  11273. if ( depthTexture ) {
  11274. depthTexture.needsUpdate = true;
  11275. }
  11276. renderTargetData.sampleCount = sampleCount;
  11277. }
  11278. //
  11279. const options = { sampleCount };
  11280. for ( let i = 0; i < textures.length; i ++ ) {
  11281. const texture = textures[ i ];
  11282. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  11283. this.updateTexture( texture, options );
  11284. }
  11285. if ( depthTexture ) {
  11286. this.updateTexture( depthTexture, options );
  11287. }
  11288. // dispose handler
  11289. if ( renderTargetData.initialized !== true ) {
  11290. renderTargetData.initialized = true;
  11291. // dispose
  11292. const onDispose = () => {
  11293. renderTarget.removeEventListener( 'dispose', onDispose );
  11294. for ( let i = 0; i < textures.length; i ++ ) {
  11295. this._destroyTexture( textures[ i ] );
  11296. }
  11297. if ( depthTexture ) {
  11298. this._destroyTexture( depthTexture );
  11299. }
  11300. this.delete( renderTarget );
  11301. };
  11302. renderTarget.addEventListener( 'dispose', onDispose );
  11303. }
  11304. }
  11305. updateTexture( texture, options = {} ) {
  11306. const textureData = this.get( texture );
  11307. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  11308. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  11309. const backend = this.backend;
  11310. if ( isRenderTarget && textureData.initialized === true ) {
  11311. // it's an update
  11312. backend.destroySampler( texture );
  11313. backend.destroyTexture( texture );
  11314. }
  11315. //
  11316. if ( texture.isFramebufferTexture ) {
  11317. const renderTarget = this.renderer.getRenderTarget();
  11318. if ( renderTarget ) {
  11319. texture.type = renderTarget.texture.type;
  11320. } else {
  11321. texture.type = UnsignedByteType;
  11322. }
  11323. }
  11324. //
  11325. const { width, height, depth } = this.getSize( texture );
  11326. options.width = width;
  11327. options.height = height;
  11328. options.depth = depth;
  11329. options.needsMipmaps = this.needsMipmaps( texture );
  11330. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  11331. //
  11332. if ( isRenderTarget || texture.isStorageTexture === true ) {
  11333. backend.createSampler( texture );
  11334. backend.createTexture( texture, options );
  11335. textureData.generation = texture.version;
  11336. } else {
  11337. const needsCreate = textureData.initialized !== true;
  11338. if ( needsCreate ) backend.createSampler( texture );
  11339. if ( texture.version > 0 ) {
  11340. const image = texture.image;
  11341. if ( image === undefined ) {
  11342. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  11343. } else if ( image.complete === false ) {
  11344. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  11345. } else {
  11346. if ( texture.images ) {
  11347. const images = [];
  11348. for ( const image of texture.images ) {
  11349. images.push( image );
  11350. }
  11351. options.images = images;
  11352. } else {
  11353. options.image = image;
  11354. }
  11355. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  11356. backend.createTexture( texture, options );
  11357. textureData.isDefaultTexture = false;
  11358. textureData.generation = texture.version;
  11359. }
  11360. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  11361. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  11362. }
  11363. } else {
  11364. // async update
  11365. backend.createDefaultTexture( texture );
  11366. textureData.isDefaultTexture = true;
  11367. textureData.generation = texture.version;
  11368. }
  11369. }
  11370. // dispose handler
  11371. if ( textureData.initialized !== true ) {
  11372. textureData.initialized = true;
  11373. textureData.generation = texture.version;
  11374. //
  11375. this.info.memory.textures ++;
  11376. // dispose
  11377. const onDispose = () => {
  11378. texture.removeEventListener( 'dispose', onDispose );
  11379. this._destroyTexture( texture );
  11380. this.info.memory.textures --;
  11381. };
  11382. texture.addEventListener( 'dispose', onDispose );
  11383. }
  11384. //
  11385. textureData.version = texture.version;
  11386. }
  11387. getSize( texture, target = _size$3 ) {
  11388. let image = texture.images ? texture.images[ 0 ] : texture.image;
  11389. if ( image ) {
  11390. if ( image.image !== undefined ) image = image.image;
  11391. target.width = image.width || 1;
  11392. target.height = image.height || 1;
  11393. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  11394. } else {
  11395. target.width = target.height = target.depth = 1;
  11396. }
  11397. return target;
  11398. }
  11399. getMipLevels( texture, width, height ) {
  11400. let mipLevelCount;
  11401. if ( texture.isCompressedTexture ) {
  11402. if ( texture.mipmaps ) {
  11403. mipLevelCount = texture.mipmaps.length;
  11404. } else {
  11405. mipLevelCount = 1;
  11406. }
  11407. } else {
  11408. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  11409. }
  11410. return mipLevelCount;
  11411. }
  11412. needsMipmaps( texture ) {
  11413. return this.isEnvironmentTexture( texture ) || texture.isCompressedTexture === true || texture.generateMipmaps;
  11414. }
  11415. isEnvironmentTexture( texture ) {
  11416. const mapping = texture.mapping;
  11417. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  11418. }
  11419. _destroyTexture( texture ) {
  11420. this.backend.destroySampler( texture );
  11421. this.backend.destroyTexture( texture );
  11422. this.delete( texture );
  11423. }
  11424. }
  11425. class Color4 extends Color {
  11426. constructor( r, g, b, a = 1 ) {
  11427. super( r, g, b );
  11428. this.a = a;
  11429. }
  11430. set( r, g, b, a = 1 ) {
  11431. this.a = a;
  11432. return super.set( r, g, b );
  11433. }
  11434. copy( color ) {
  11435. if ( color.a !== undefined ) this.a = color.a;
  11436. return super.copy( color );
  11437. }
  11438. clone() {
  11439. return new this.constructor( this.r, this.g, this.b, this.a );
  11440. }
  11441. }
  11442. /**
  11443. * Special version of {@link PropertyNode} which is used for parameters.
  11444. *
  11445. * @augments PropertyNode
  11446. */
  11447. class ParameterNode extends PropertyNode {
  11448. static get type() {
  11449. return 'ParameterNode';
  11450. }
  11451. /**
  11452. * Constructs a new parameter node.
  11453. *
  11454. * @param {String} nodeType - The type of the node.
  11455. * @param {String?} [name=null] - The name of the parameter in the shader.
  11456. */
  11457. constructor( nodeType, name = null ) {
  11458. super( nodeType, name );
  11459. /**
  11460. * This flag can be used for type testing.
  11461. *
  11462. * @type {Boolean}
  11463. * @readonly
  11464. * @default true
  11465. */
  11466. this.isParameterNode = true;
  11467. }
  11468. getHash() {
  11469. return this.uuid;
  11470. }
  11471. generate() {
  11472. return this.name;
  11473. }
  11474. }
  11475. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  11476. /**
  11477. * Stack is a helper for Nodes that need to produce stack-based code instead of continuous flow.
  11478. * They are usually needed in cases like `If`, `Else`.
  11479. *
  11480. * @augments Node
  11481. */
  11482. class StackNode extends Node {
  11483. static get type() {
  11484. return 'StackNode';
  11485. }
  11486. /**
  11487. * Constructs a new stack node.
  11488. *
  11489. * @param {StackNode?} [parent=null] - The parent stack node.
  11490. */
  11491. constructor( parent = null ) {
  11492. super();
  11493. /**
  11494. * List of nodes.
  11495. *
  11496. * @type {Array<Node>}
  11497. */
  11498. this.nodes = [];
  11499. /**
  11500. * The output node.
  11501. *
  11502. * @type {Node?}
  11503. * @default null
  11504. */
  11505. this.outputNode = null;
  11506. /**
  11507. * The parent stack node.
  11508. *
  11509. * @type {StackNode}
  11510. * @default null
  11511. */
  11512. this.parent = parent;
  11513. /**
  11514. * The current conditional node.
  11515. *
  11516. * @private
  11517. * @type {ConditionalNode}
  11518. * @default null
  11519. */
  11520. this._currentCond = null;
  11521. /**
  11522. * This flag can be used for type testing.
  11523. *
  11524. * @type {Boolean}
  11525. * @readonly
  11526. * @default true
  11527. */
  11528. this.isStackNode = true;
  11529. }
  11530. getNodeType( builder ) {
  11531. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  11532. }
  11533. /**
  11534. * Adds a node to this stack.
  11535. *
  11536. * @param {Node} node - The node to add.
  11537. * @return {StackNode} A reference to this stack node.
  11538. */
  11539. add( node ) {
  11540. this.nodes.push( node );
  11541. return this;
  11542. }
  11543. /**
  11544. * Represent an `if` statement in TSL.
  11545. *
  11546. * @param {Node} boolNode - Represents the condition.
  11547. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  11548. * @return {StackNode} A reference to this stack node.
  11549. */
  11550. If( boolNode, method ) {
  11551. const methodNode = new ShaderNode( method );
  11552. this._currentCond = select( boolNode, methodNode );
  11553. return this.add( this._currentCond );
  11554. }
  11555. /**
  11556. * Represent an `elseif` statement in TSL.
  11557. *
  11558. * @param {Node} boolNode - Represents the condition.
  11559. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  11560. * @return {StackNode} A reference to this stack node.
  11561. */
  11562. ElseIf( boolNode, method ) {
  11563. const methodNode = new ShaderNode( method );
  11564. const ifNode = select( boolNode, methodNode );
  11565. this._currentCond.elseNode = ifNode;
  11566. this._currentCond = ifNode;
  11567. return this;
  11568. }
  11569. /**
  11570. * Represent an `else` statement in TSL.
  11571. *
  11572. * @param {Function} method - TSL code which is executed in the `else` case.
  11573. * @return {StackNode} A reference to this stack node.
  11574. */
  11575. Else( method ) {
  11576. this._currentCond.elseNode = new ShaderNode( method );
  11577. return this;
  11578. }
  11579. build( builder, ...params ) {
  11580. const previousStack = getCurrentStack();
  11581. setCurrentStack( this );
  11582. for ( const node of this.nodes ) {
  11583. node.build( builder, 'void' );
  11584. }
  11585. setCurrentStack( previousStack );
  11586. return this.outputNode ? this.outputNode.build( builder, ...params ) : super.build( builder, ...params );
  11587. }
  11588. //
  11589. else( ...params ) { // @deprecated, r168
  11590. console.warn( 'TSL.StackNode: .else() has been renamed to .Else().' );
  11591. return this.Else( ...params );
  11592. }
  11593. elseif( ...params ) { // @deprecated, r168
  11594. console.warn( 'TSL.StackNode: .elseif() has been renamed to .ElseIf().' );
  11595. return this.ElseIf( ...params );
  11596. }
  11597. }
  11598. const stack = /*@__PURE__*/ nodeProxy( StackNode );
  11599. /**
  11600. * This node can be used to define multiple outputs in a shader programs.
  11601. *
  11602. * @augments Node
  11603. */
  11604. class OutputStructNode extends Node {
  11605. static get type() {
  11606. return 'OutputStructNode';
  11607. }
  11608. /**
  11609. * Constructs a new output struct node. The constructor can be invoked with an
  11610. * arbitrary number of nodes representing the members.
  11611. *
  11612. * @param {...Node} members - A parameter list of nodes.
  11613. */
  11614. constructor( ...members ) {
  11615. super();
  11616. /**
  11617. * An array of nodes which defines the output.
  11618. *
  11619. * @type {Array<Node>}
  11620. */
  11621. this.members = members;
  11622. /**
  11623. * This flag can be used for type testing.
  11624. *
  11625. * @type {Boolean}
  11626. * @readonly
  11627. * @default true
  11628. */
  11629. this.isOutputStructNode = true;
  11630. }
  11631. setup( builder ) {
  11632. super.setup( builder );
  11633. const members = this.members;
  11634. const types = [];
  11635. for ( let i = 0; i < members.length; i ++ ) {
  11636. types.push( members[ i ].getNodeType( builder ) );
  11637. }
  11638. this.nodeType = builder.getStructTypeFromNode( this, types ).name;
  11639. }
  11640. generate( builder, output ) {
  11641. const propertyName = builder.getOutputStructName();
  11642. const members = this.members;
  11643. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  11644. for ( let i = 0; i < members.length; i ++ ) {
  11645. const snippet = members[ i ].build( builder, output );
  11646. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  11647. }
  11648. return propertyName;
  11649. }
  11650. }
  11651. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  11652. /**
  11653. * Returns the MRT texture index for the given name.
  11654. *
  11655. * @param {Array<Texture>} textures - The textures of a MRT-configured render target.
  11656. * @param {String} name - The name of the MRT texture which index is requested.
  11657. * @return {Number} The texture index.
  11658. */
  11659. function getTextureIndex( textures, name ) {
  11660. for ( let i = 0; i < textures.length; i ++ ) {
  11661. if ( textures[ i ].name === name ) {
  11662. return i;
  11663. }
  11664. }
  11665. return - 1;
  11666. }
  11667. /**
  11668. * This node can be used setup a MRT context for rendering. A typical MRT setup for
  11669. * post-processing is shown below:
  11670. * ```js
  11671. * const mrtNode = mrt( {
  11672. * output: output,
  11673. * normal: normalView
  11674. * } ) );
  11675. * ```
  11676. * The MRT output is defined as a dictionary.
  11677. *
  11678. * @augments OutputStructNode
  11679. */
  11680. class MRTNode extends OutputStructNode {
  11681. static get type() {
  11682. return 'MRTNode';
  11683. }
  11684. /**
  11685. * Constructs a new output struct node.
  11686. *
  11687. * @param {Object<String, Node>} outputNodes - The MRT outputs.
  11688. */
  11689. constructor( outputNodes ) {
  11690. super();
  11691. /**
  11692. * A dictionary representing the MRT outputs. The key
  11693. * is the name of the output, the value the node which produces
  11694. * the output result.
  11695. *
  11696. * @type {Object<String, Node>}
  11697. */
  11698. this.outputNodes = outputNodes;
  11699. /**
  11700. * This flag can be used for type testing.
  11701. *
  11702. * @type {Boolean}
  11703. * @readonly
  11704. * @default true
  11705. */
  11706. this.isMRTNode = true;
  11707. }
  11708. /**
  11709. * Returns `true` if the MRT node has an output with the given name.
  11710. *
  11711. * @param {String} name - The name of the output.
  11712. * @return {NodeBuilder} Whether the MRT node has an output for the given name or not.
  11713. */
  11714. has( name ) {
  11715. return this.outputNodes[ name ] !== undefined;
  11716. }
  11717. /**
  11718. * Returns the output node for the given name.
  11719. *
  11720. * @param {String} name - The name of the output.
  11721. * @return {Node} The output node.
  11722. */
  11723. get( name ) {
  11724. return this.outputNodes[ name ];
  11725. }
  11726. /**
  11727. * Merges the outputs of the given MRT node with the outputs of this node.
  11728. *
  11729. * @param {MRTNode} mrtNode - The MRT to merge.
  11730. * @return {MRTNode} A new MRT node with merged outputs..
  11731. */
  11732. merge( mrtNode ) {
  11733. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  11734. return mrt( outputs );
  11735. }
  11736. setup( builder ) {
  11737. const outputNodes = this.outputNodes;
  11738. const mrt = builder.renderer.getRenderTarget();
  11739. const members = [];
  11740. const textures = mrt.textures;
  11741. for ( const name in outputNodes ) {
  11742. const index = getTextureIndex( textures, name );
  11743. members[ index ] = vec4( outputNodes[ name ] );
  11744. }
  11745. this.members = members;
  11746. return super.setup( builder );
  11747. }
  11748. }
  11749. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  11750. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  11751. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  11752. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  11753. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  11754. const result = word.shiftRight( 22 ).bitXor( word );
  11755. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  11756. } );
  11757. // remapping functions https://iquilezles.org/articles/functions/
  11758. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  11759. 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 ) );
  11760. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  11761. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  11762. // https://github.com/cabbibo/glsl-tri-noise-3d
  11763. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  11764. return x.fract().sub( .5 ).abs();
  11765. } ).setLayout( {
  11766. name: 'tri',
  11767. type: 'float',
  11768. inputs: [
  11769. { name: 'x', type: 'float' }
  11770. ]
  11771. } );
  11772. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  11773. 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. ) ) ) ) );
  11774. } ).setLayout( {
  11775. name: 'tri3',
  11776. type: 'vec3',
  11777. inputs: [
  11778. { name: 'p', type: 'vec3' }
  11779. ]
  11780. } );
  11781. const triNoise3D = /*@__PURE__*/ Fn( ( [ p_immutable, spd, time ] ) => {
  11782. const p = vec3( p_immutable ).toVar();
  11783. const z = float( 1.4 ).toVar();
  11784. const rz = float( 0.0 ).toVar();
  11785. const bp = vec3( p ).toVar();
  11786. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  11787. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  11788. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( spd ) ) ) );
  11789. bp.mulAssign( 1.8 );
  11790. z.mulAssign( 1.5 );
  11791. p.mulAssign( 1.2 );
  11792. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  11793. rz.addAssign( t.div( z ) );
  11794. bp.addAssign( 0.14 );
  11795. } );
  11796. return rz;
  11797. } ).setLayout( {
  11798. name: 'triNoise3D',
  11799. type: 'float',
  11800. inputs: [
  11801. { name: 'p', type: 'vec3' },
  11802. { name: 'spd', type: 'float' },
  11803. { name: 'time', type: 'float' }
  11804. ]
  11805. } );
  11806. class FunctionOverloadingNode extends Node {
  11807. static get type() {
  11808. return 'FunctionOverloadingNode';
  11809. }
  11810. constructor( functionNodes = [], ...parametersNodes ) {
  11811. super();
  11812. this.functionNodes = functionNodes;
  11813. this.parametersNodes = parametersNodes;
  11814. this._candidateFnCall = null;
  11815. this.global = true;
  11816. }
  11817. getNodeType() {
  11818. return this.functionNodes[ 0 ].shaderNode.layout.type;
  11819. }
  11820. setup( builder ) {
  11821. const params = this.parametersNodes;
  11822. let candidateFnCall = this._candidateFnCall;
  11823. if ( candidateFnCall === null ) {
  11824. let candidateFn = null;
  11825. let candidateScore = - 1;
  11826. for ( const functionNode of this.functionNodes ) {
  11827. const shaderNode = functionNode.shaderNode;
  11828. const layout = shaderNode.layout;
  11829. if ( layout === null ) {
  11830. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  11831. }
  11832. const inputs = layout.inputs;
  11833. if ( params.length === inputs.length ) {
  11834. let score = 0;
  11835. for ( let i = 0; i < params.length; i ++ ) {
  11836. const param = params[ i ];
  11837. const input = inputs[ i ];
  11838. if ( param.getNodeType( builder ) === input.type ) {
  11839. score ++;
  11840. } else {
  11841. score = 0;
  11842. }
  11843. }
  11844. if ( score > candidateScore ) {
  11845. candidateFn = functionNode;
  11846. candidateScore = score;
  11847. }
  11848. }
  11849. }
  11850. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  11851. }
  11852. return candidateFnCall;
  11853. }
  11854. }
  11855. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  11856. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  11857. /** @module Timer **/
  11858. /**
  11859. * Represents the elapsed time in seconds.
  11860. *
  11861. * @type {UniformNode<float>}
  11862. */
  11863. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  11864. /**
  11865. * Represents the delta time in seconds.
  11866. *
  11867. * @type {UniformNode<float>}
  11868. */
  11869. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  11870. /**
  11871. * Represents the current frame ID.
  11872. *
  11873. * @type {UniformNode<uint>}
  11874. */
  11875. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  11876. // Deprecated
  11877. const timerLocal = ( timeScale = 1 ) => { // @deprecated, r170
  11878. console.warn( 'TSL: timerLocal() is deprecated. Use "time" instead.' );
  11879. return time.mul( timeScale );
  11880. };
  11881. const timerGlobal = ( timeScale = 1 ) => { // @deprecated, r170
  11882. console.warn( 'TSL: timerGlobal() is deprecated. Use "time" instead.' );
  11883. return time.mul( timeScale );
  11884. };
  11885. const timerDelta = ( timeScale = 1 ) => { // @deprecated, r170
  11886. console.warn( 'TSL: timerDelta() is deprecated. Use "deltaTime" instead.' );
  11887. return deltaTime.mul( timeScale );
  11888. };
  11889. /** @module Oscillators **/
  11890. /**
  11891. * Generates a sine wave oscillation based on a timer.
  11892. *
  11893. * @method
  11894. * @param {Node<float>} time - The timer to generate the oscillation with.
  11895. * @return {Node<float>} The oscillation node.
  11896. */
  11897. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  11898. /**
  11899. * Generates a square wave oscillation based on a timer.
  11900. *
  11901. * @method
  11902. * @param {Node<float>} time - The timer to generate the oscillation with.
  11903. * @return {Node<float>} The oscillation node.
  11904. */
  11905. const oscSquare = ( t = time ) => t.fract().round();
  11906. /**
  11907. * Generates a triangle wave oscillation based on a timer.
  11908. *
  11909. * @method
  11910. * @param {Node<float>} time - The timer to generate the oscillation with.
  11911. * @return {Node<float>} The oscillation node.
  11912. */
  11913. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  11914. /**
  11915. * Generates a sawtooth wave oscillation based on a timer.
  11916. *
  11917. * @method
  11918. * @param {Node<float>} time - The timer to generate the oscillation with.
  11919. * @return {Node<float>} The oscillation node.
  11920. */
  11921. const oscSawtooth = ( t = time ) => t.fract();
  11922. /** @module UVUtils **/
  11923. /**
  11924. * Rotates the given uv coordinates around a center point
  11925. *
  11926. * @method
  11927. * @param {Node<vec2>} uv - The uv coordinates.
  11928. * @param {Node<float>} rotation - The rotation defined in radians.
  11929. * @param {Node<vec2>} center - The center of rotation
  11930. * @return {Node<vec2>} The rotated uv coordinates.
  11931. */
  11932. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  11933. return rotate( uv.sub( center ), rotation ).add( center );
  11934. } );
  11935. /**
  11936. * Applies a spherical warping effect to the given uv coordinates.
  11937. *
  11938. * @method
  11939. * @param {Node<vec2>} uv - The uv coordinates.
  11940. * @param {Node<float>} strength - The strength of the effect.
  11941. * @param {Node<vec2>} center - The center point
  11942. * @return {Node<vec2>} The updated uv coordinates.
  11943. */
  11944. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  11945. const delta = uv.sub( center );
  11946. const delta2 = delta.dot( delta );
  11947. const delta4 = delta2.mul( delta2 );
  11948. const deltaOffset = delta4.mul( strength );
  11949. return uv.add( delta.mul( deltaOffset ) );
  11950. } );
  11951. /** @module SpriteUtils **/
  11952. /**
  11953. * This can be used to achieve a billboarding behavior for flat meshes. That means they are
  11954. * oriented always towards the camera.
  11955. *
  11956. * ```js
  11957. * material.vertexNode = billboarding();
  11958. * ```
  11959. *
  11960. * @method
  11961. * @param {Object} config - The configuration object.
  11962. * @param {Node<vec3>?} [config.position=null] - Can be used to define the vertex positions in world space.
  11963. * @param {Boolean} [config.horizontal=true] - Whether to follow the camera rotation horizontally or not.
  11964. * @param {Boolean} [config.vertical=false] - Whether to follow the camera rotation vertically or not.
  11965. * @return {Node<vec3>} The updated vertex position in clip space.
  11966. */
  11967. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  11968. let worldMatrix;
  11969. if ( position !== null ) {
  11970. worldMatrix = modelWorldMatrix.toVar();
  11971. worldMatrix[ 3 ][ 0 ] = position.x;
  11972. worldMatrix[ 3 ][ 1 ] = position.y;
  11973. worldMatrix[ 3 ][ 2 ] = position.z;
  11974. } else {
  11975. worldMatrix = modelWorldMatrix;
  11976. }
  11977. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  11978. if ( defined( horizontal ) ) {
  11979. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  11980. modelViewMatrix[ 0 ][ 1 ] = 0;
  11981. modelViewMatrix[ 0 ][ 2 ] = 0;
  11982. }
  11983. if ( defined( vertical ) ) {
  11984. modelViewMatrix[ 1 ][ 0 ] = 0;
  11985. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  11986. modelViewMatrix[ 1 ][ 2 ] = 0;
  11987. }
  11988. modelViewMatrix[ 2 ][ 0 ] = 0;
  11989. modelViewMatrix[ 2 ][ 1 ] = 0;
  11990. modelViewMatrix[ 2 ][ 2 ] = 1;
  11991. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  11992. } );
  11993. /** @module ViewportUtils **/
  11994. /**
  11995. * A special version of a screen uv function that involves a depth comparison
  11996. * when computing the final uvs. The function mitigates visual erros when
  11997. * using viewport texture nodes for refraction purposes. Without this function
  11998. * objects in front of a refractive surface might appear on the refractive surface
  11999. * which is incorrect.
  12000. *
  12001. * @method
  12002. * @param {Node<vec2>?} uv - Optional uv coordinates. By default `screenUV` is used.
  12003. * @return {Node<vec2>} The update uv coordinates.
  12004. */
  12005. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  12006. const depth = linearDepth();
  12007. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  12008. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  12009. return finalUV;
  12010. } );
  12011. /**
  12012. * Can be used to compute texture coordinates for animated sprite sheets.
  12013. *
  12014. * ```js
  12015. * const uvNode = spritesheetUV( vec2( 6, 6 ), uv(), time.mul( animationSpeed ) );
  12016. *
  12017. * material.colorNode = texture( spriteSheet, uvNode );
  12018. * ```
  12019. *
  12020. * @augments Node
  12021. */
  12022. class SpriteSheetUVNode extends Node {
  12023. static get type() {
  12024. return 'SpriteSheetUVNode';
  12025. }
  12026. /**
  12027. * Constructs a new sprite sheet uv node.
  12028. *
  12029. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  12030. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  12031. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  12032. */
  12033. constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) {
  12034. super( 'vec2' );
  12035. /**
  12036. * The node that defines the number of sprites in the x and y direction (e.g 6x6).
  12037. *
  12038. * @type {Node<vec2>}
  12039. */
  12040. this.countNode = countNode;
  12041. /**
  12042. * The uv node.
  12043. *
  12044. * @type {Node<vec2>}
  12045. */
  12046. this.uvNode = uvNode;
  12047. /**
  12048. * The node that defines the current frame/sprite.
  12049. *
  12050. * @type {Node<float>}
  12051. */
  12052. this.frameNode = frameNode;
  12053. }
  12054. setup() {
  12055. const { frameNode, uvNode, countNode } = this;
  12056. const { width, height } = countNode;
  12057. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  12058. const column = frameNum.mod( width );
  12059. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  12060. const scale = countNode.reciprocal();
  12061. const uvFrameOffset = vec2( column, row );
  12062. return uvNode.add( uvFrameOffset ).mul( scale );
  12063. }
  12064. }
  12065. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode );
  12066. /**
  12067. * Can be used for triplanar texture mapping.
  12068. *
  12069. * ```js
  12070. * material.colorNode = triplanarTexture( texture( diffuseMap ) );
  12071. * ```
  12072. *
  12073. * @augments Node
  12074. */
  12075. class TriplanarTexturesNode extends Node {
  12076. static get type() {
  12077. return 'TriplanarTexturesNode';
  12078. }
  12079. /**
  12080. * Constructs a new triplanar textures node.
  12081. *
  12082. * @param {Node} textureXNode - First texture node.
  12083. * @param {Node?} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  12084. * @param {Node?} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  12085. * @param {Node<float>?} [scaleNode=float(1)] - The scale node.
  12086. * @param {Node<vec3>?} [positionNode=positionLocal] - Vertex positions in local space.
  12087. * @param {Node<vec3>?} [normalNode=normalLocal] - Normals in local space.
  12088. */
  12089. constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) {
  12090. super( 'vec4' );
  12091. /**
  12092. * First texture node.
  12093. *
  12094. * @type {Node}
  12095. */
  12096. this.textureXNode = textureXNode;
  12097. /**
  12098. * Second texture node. When not set, the shader will sample from `textureXNode` instead.
  12099. *
  12100. * @type {Node}
  12101. * @default null
  12102. */
  12103. this.textureYNode = textureYNode;
  12104. /**
  12105. * Third texture node. When not set, the shader will sample from `textureXNode` instead.
  12106. *
  12107. * @type {Node}
  12108. * @default null
  12109. */
  12110. this.textureZNode = textureZNode;
  12111. /**
  12112. * The scale node.
  12113. *
  12114. * @type {Node<float>}
  12115. * @default float(1)
  12116. */
  12117. this.scaleNode = scaleNode;
  12118. /**
  12119. * Vertex positions in local space.
  12120. *
  12121. * @type {Node<vec3>}
  12122. * @default positionLocal
  12123. */
  12124. this.positionNode = positionNode;
  12125. /**
  12126. * Normals in local space.
  12127. *
  12128. * @type {Node<vec3>}
  12129. * @default normalLocal
  12130. */
  12131. this.normalNode = normalNode;
  12132. }
  12133. setup() {
  12134. const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this;
  12135. // Ref: https://github.com/keijiro/StandardTriplanar
  12136. // Blending factor of triplanar mapping
  12137. let bf = normalNode.abs().normalize();
  12138. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  12139. // Triplanar mapping
  12140. const tx = positionNode.yz.mul( scaleNode );
  12141. const ty = positionNode.zx.mul( scaleNode );
  12142. const tz = positionNode.xy.mul( scaleNode );
  12143. // Base color
  12144. const textureX = textureXNode.value;
  12145. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  12146. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  12147. const cx = texture( textureX, tx ).mul( bf.x );
  12148. const cy = texture( textureY, ty ).mul( bf.y );
  12149. const cz = texture( textureZ, tz ).mul( bf.z );
  12150. return add( cx, cy, cz );
  12151. }
  12152. }
  12153. const triplanarTextures = /*@__PURE__*/ nodeProxy( TriplanarTexturesNode );
  12154. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  12155. const _reflectorPlane = new Plane();
  12156. const _normal = new Vector3();
  12157. const _reflectorWorldPosition = new Vector3();
  12158. const _cameraWorldPosition = new Vector3();
  12159. const _rotationMatrix = new Matrix4();
  12160. const _lookAtPosition = new Vector3( 0, 0, - 1 );
  12161. const clipPlane = new Vector4();
  12162. const _view = new Vector3();
  12163. const _target = new Vector3();
  12164. const _q = new Vector4();
  12165. const _size$2 = new Vector2();
  12166. const _defaultRT = new RenderTarget();
  12167. const _defaultUV = screenUV.flipX();
  12168. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  12169. let _inReflector = false;
  12170. /**
  12171. * This node can be used to implement mirror-like flat reflective surfaces.
  12172. *
  12173. * ```js
  12174. * const groundReflector = reflector();
  12175. * material.colorNode = groundReflector;
  12176. *
  12177. * const plane = new Mesh( geometry, material );
  12178. * plane.add( groundReflector.target );
  12179. * ```
  12180. *
  12181. * @augments TextureNode
  12182. */
  12183. class ReflectorNode extends TextureNode {
  12184. static get type() {
  12185. return 'ReflectorNode';
  12186. }
  12187. /**
  12188. * Constructs a new reflector node.
  12189. *
  12190. * @param {Object} [parameters={}] - An object holding configuration parameters.
  12191. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  12192. * @param {Number} [parameters.resolution=1] - The resolution scale.
  12193. * @param {Boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  12194. * @param {Boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  12195. * @param {Boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  12196. */
  12197. constructor( parameters = {} ) {
  12198. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  12199. /**
  12200. * A reference to the internal reflector base node which holds the actual implementation.
  12201. *
  12202. * @private
  12203. * @type {Node?}
  12204. * @default null
  12205. */
  12206. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  12207. /**
  12208. * A reference to the internal depth node.
  12209. *
  12210. * @private
  12211. * @type {Node?}
  12212. * @default null
  12213. */
  12214. this._depthNode = null;
  12215. this.setUpdateMatrix( false );
  12216. }
  12217. /**
  12218. * A reference to the internal reflector node.
  12219. *
  12220. * @type {Node}
  12221. */
  12222. get reflector() {
  12223. return this._reflectorBaseNode;
  12224. }
  12225. /**
  12226. * A reference to 3D object the reflector is linked to.
  12227. *
  12228. * @type {Object3D}
  12229. */
  12230. get target() {
  12231. return this._reflectorBaseNode.target;
  12232. }
  12233. /**
  12234. * Returns a node representing the mirror's depth. That can be used
  12235. * to implement more advanced reflection effects like distance attenuation.
  12236. *
  12237. * @return {Node} The depth node.
  12238. */
  12239. getDepthNode() {
  12240. if ( this._depthNode === null ) {
  12241. if ( this._reflectorBaseNode.depth !== true ) {
  12242. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  12243. }
  12244. this._depthNode = nodeObject( new ReflectorNode( {
  12245. defaultTexture: _defaultRT.depthTexture,
  12246. reflector: this._reflectorBaseNode
  12247. } ) );
  12248. }
  12249. return this._depthNode;
  12250. }
  12251. setup( builder ) {
  12252. // ignore if used in post-processing
  12253. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  12254. return super.setup( builder );
  12255. }
  12256. clone() {
  12257. const texture = new this.constructor( this.reflectorNode );
  12258. texture._reflectorBaseNode = this._reflectorBaseNode;
  12259. return texture;
  12260. }
  12261. }
  12262. /**
  12263. * Holds the actual implementation of the reflector.
  12264. *
  12265. * TOOD: Explain why `ReflectorBaseNode`. Originally the entire logic was implemented
  12266. * in `ReflectorNode`, see #29619.
  12267. *
  12268. * @private
  12269. * @augments Node
  12270. */
  12271. class ReflectorBaseNode extends Node {
  12272. static get type() {
  12273. return 'ReflectorBaseNode';
  12274. }
  12275. /**
  12276. * Constructs a new reflector base node.
  12277. *
  12278. * @param {TextureNode} textureNode - Represents the rendered reflections as a texture node.
  12279. * @param {Object} [parameters={}] - An object holding configuration parameters.
  12280. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  12281. * @param {Number} [parameters.resolution=1] - The resolution scale.
  12282. * @param {Boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  12283. * @param {Boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  12284. * @param {Boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  12285. */
  12286. constructor( textureNode, parameters = {} ) {
  12287. super();
  12288. const {
  12289. target = new Object3D(),
  12290. resolution = 1,
  12291. generateMipmaps = false,
  12292. bounces = true,
  12293. depth = false
  12294. } = parameters;
  12295. /**
  12296. * Represents the rendered reflections as a texture node.
  12297. *
  12298. * @type {TextureNode}
  12299. */
  12300. this.textureNode = textureNode;
  12301. /**
  12302. * The 3D object the reflector is linked to.
  12303. *
  12304. * @type {Object3D}
  12305. * @default {new Object3D()}
  12306. */
  12307. this.target = target;
  12308. /**
  12309. * The resolution scale.
  12310. *
  12311. * @type {Number}
  12312. * @default {1}
  12313. */
  12314. this.resolution = resolution;
  12315. /**
  12316. * Whether mipmaps should be generated or not.
  12317. *
  12318. * @type {Boolean}
  12319. * @default {false}
  12320. */
  12321. this.generateMipmaps = generateMipmaps;
  12322. /**
  12323. * Whether reflectors can render other reflector nodes or not.
  12324. *
  12325. * @type {Boolean}
  12326. * @default {true}
  12327. */
  12328. this.bounces = bounces;
  12329. /**
  12330. * Whether depth data should be generated or not.
  12331. *
  12332. * @type {Boolean}
  12333. * @default {false}
  12334. */
  12335. this.depth = depth;
  12336. /**
  12337. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` when {@link ReflectorBaseNode#bounces}
  12338. * is `true`. Otherwise it's `NodeUpdateType.FRAME`.
  12339. *
  12340. * @type {String}
  12341. * @default 'render'
  12342. */
  12343. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  12344. /**
  12345. * Weak map for managing virtual cameras.
  12346. *
  12347. * @type {WeakMap<Camera,Camera>}
  12348. */
  12349. this.virtualCameras = new WeakMap();
  12350. /**
  12351. * Weak map for managing render targets.
  12352. *
  12353. * @type {WeakMap}
  12354. */
  12355. this.renderTargets = new WeakMap();
  12356. }
  12357. /**
  12358. * Updates the resolution of the internal render target.
  12359. *
  12360. * @private
  12361. * @param {RenderTarget} renderTarget - The render target to resize.
  12362. * @param {Renderer} renderer - The renderer that is used to determine the new size.
  12363. */
  12364. _updateResolution( renderTarget, renderer ) {
  12365. const resolution = this.resolution;
  12366. renderer.getDrawingBufferSize( _size$2 );
  12367. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  12368. }
  12369. setup( builder ) {
  12370. this._updateResolution( _defaultRT, builder.renderer );
  12371. return super.setup( builder );
  12372. }
  12373. /**
  12374. * Returns a virtual camera for the given camera. The virutal camera is used to
  12375. * render the scene from the reflector's view so correct reflections can be produced.
  12376. *
  12377. * @param {Camera} camera - The scene's camera.
  12378. * @return {Camera} The corresponding virtual camera.
  12379. */
  12380. getVirtualCamera( camera ) {
  12381. let virtualCamera = this.virtualCameras.get( camera );
  12382. if ( virtualCamera === undefined ) {
  12383. virtualCamera = camera.clone();
  12384. this.virtualCameras.set( camera, virtualCamera );
  12385. }
  12386. return virtualCamera;
  12387. }
  12388. /**
  12389. * Returns a render target for the given camera. The reflections are rendered
  12390. * into this render target.
  12391. *
  12392. * @param {Camera} camera - The scene's camera.
  12393. * @return {RenderTarget} The render target.
  12394. */
  12395. getRenderTarget( camera ) {
  12396. let renderTarget = this.renderTargets.get( camera );
  12397. if ( renderTarget === undefined ) {
  12398. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } );
  12399. if ( this.generateMipmaps === true ) {
  12400. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  12401. renderTarget.texture.generateMipmaps = true;
  12402. }
  12403. if ( this.depth === true ) {
  12404. renderTarget.depthTexture = new DepthTexture();
  12405. }
  12406. this.renderTargets.set( camera, renderTarget );
  12407. }
  12408. return renderTarget;
  12409. }
  12410. updateBefore( frame ) {
  12411. if ( this.bounces === false && _inReflector ) return;
  12412. _inReflector = true;
  12413. const { scene, camera, renderer, material } = frame;
  12414. const { target } = this;
  12415. const virtualCamera = this.getVirtualCamera( camera );
  12416. const renderTarget = this.getRenderTarget( virtualCamera );
  12417. renderer.getDrawingBufferSize( _size$2 );
  12418. this._updateResolution( renderTarget, renderer );
  12419. //
  12420. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  12421. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  12422. _rotationMatrix.extractRotation( target.matrixWorld );
  12423. _normal.set( 0, 0, 1 );
  12424. _normal.applyMatrix4( _rotationMatrix );
  12425. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  12426. // Avoid rendering when reflector is facing away
  12427. if ( _view.dot( _normal ) > 0 ) return;
  12428. _view.reflect( _normal ).negate();
  12429. _view.add( _reflectorWorldPosition );
  12430. _rotationMatrix.extractRotation( camera.matrixWorld );
  12431. _lookAtPosition.set( 0, 0, - 1 );
  12432. _lookAtPosition.applyMatrix4( _rotationMatrix );
  12433. _lookAtPosition.add( _cameraWorldPosition );
  12434. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  12435. _target.reflect( _normal ).negate();
  12436. _target.add( _reflectorWorldPosition );
  12437. //
  12438. virtualCamera.coordinateSystem = camera.coordinateSystem;
  12439. virtualCamera.position.copy( _view );
  12440. virtualCamera.up.set( 0, 1, 0 );
  12441. virtualCamera.up.applyMatrix4( _rotationMatrix );
  12442. virtualCamera.up.reflect( _normal );
  12443. virtualCamera.lookAt( _target );
  12444. virtualCamera.near = camera.near;
  12445. virtualCamera.far = camera.far;
  12446. virtualCamera.updateMatrixWorld();
  12447. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  12448. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  12449. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  12450. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  12451. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  12452. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  12453. const projectionMatrix = virtualCamera.projectionMatrix;
  12454. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  12455. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  12456. _q.z = - 1.0;
  12457. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  12458. // Calculate the scaled plane vector
  12459. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  12460. const clipBias = 0;
  12461. // Replacing the third row of the projection matrix
  12462. projectionMatrix.elements[ 2 ] = clipPlane.x;
  12463. projectionMatrix.elements[ 6 ] = clipPlane.y;
  12464. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  12465. projectionMatrix.elements[ 14 ] = clipPlane.w;
  12466. //
  12467. this.textureNode.value = renderTarget.texture;
  12468. if ( this.depth === true ) {
  12469. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  12470. }
  12471. material.visible = false;
  12472. const currentRenderTarget = renderer.getRenderTarget();
  12473. const currentMRT = renderer.getMRT();
  12474. renderer.setMRT( null );
  12475. renderer.setRenderTarget( renderTarget );
  12476. renderer.render( scene, virtualCamera );
  12477. renderer.setMRT( currentMRT );
  12478. renderer.setRenderTarget( currentRenderTarget );
  12479. material.visible = true;
  12480. _inReflector = false;
  12481. }
  12482. }
  12483. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  12484. // Helper for passes that need to fill the viewport with a single quad.
  12485. const _camera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  12486. // https://github.com/mrdoob/three.js/pull/21358
  12487. class QuadGeometry extends BufferGeometry {
  12488. constructor( flipY = false ) {
  12489. super();
  12490. const uv = flipY === false ? [ 0, - 1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  12491. this.setAttribute( 'position', new Float32BufferAttribute( [ - 1, 3, 0, - 1, - 1, 0, 3, - 1, 0 ], 3 ) );
  12492. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  12493. }
  12494. }
  12495. const _geometry = /*@__PURE__*/ new QuadGeometry();
  12496. class QuadMesh extends Mesh {
  12497. constructor( material = null ) {
  12498. super( _geometry, material );
  12499. this.camera = _camera;
  12500. this.isQuadMesh = true;
  12501. }
  12502. renderAsync( renderer ) {
  12503. return renderer.renderAsync( this, _camera );
  12504. }
  12505. render( renderer ) {
  12506. renderer.render( this, _camera );
  12507. }
  12508. }
  12509. const _size$1 = /*@__PURE__*/ new Vector2();
  12510. /**
  12511. * `RTTNode` takes another node and uses it with a `QuadMesh` to render into a texture (RTT).
  12512. * This module is especially relevant in context of post processing where certain nodes require
  12513. * texture input for their effects. With the helper function `convertToTexture()` which is based
  12514. * on this module, the node system can automatically ensure texture input if required.
  12515. *
  12516. * @augments Node
  12517. */
  12518. class RTTNode extends TextureNode {
  12519. static get type() {
  12520. return 'RTTNode';
  12521. }
  12522. /**
  12523. * Constructs a new RTT node.
  12524. *
  12525. * @param {Node} node - The node to render a texture with.
  12526. * @param {Number?} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  12527. * @param {Number?} [height=null] - The height of the internal render target.
  12528. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  12529. */
  12530. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  12531. const renderTarget = new RenderTarget( width, height, options );
  12532. super( renderTarget.texture, uv() );
  12533. /**
  12534. * The node to render a texture with.
  12535. *
  12536. * @type {Node}
  12537. */
  12538. this.node = node;
  12539. /**
  12540. * The width of the internal render target.
  12541. * If not width is applied, the render target is automatically resized.
  12542. *
  12543. * @type {Number?}
  12544. * @default null
  12545. */
  12546. this.width = width;
  12547. /**
  12548. * The height of the internal render target.
  12549. *
  12550. * @type {Number?}
  12551. * @default null
  12552. */
  12553. this.height = height;
  12554. /**
  12555. * The pixel ratio
  12556. *
  12557. * @type {Number}
  12558. * @default 1
  12559. */
  12560. this.pixelRatio = 1;
  12561. /**
  12562. * The render target
  12563. *
  12564. * @type {RenderTarget}
  12565. */
  12566. this.renderTarget = renderTarget;
  12567. /**
  12568. * Whether the texture requires an update or not.
  12569. *
  12570. * @type {Boolean}
  12571. * @default true
  12572. */
  12573. this.textureNeedsUpdate = true;
  12574. /**
  12575. * Whether the texture should automatically be updated or not.
  12576. *
  12577. * @type {Boolean}
  12578. * @default true
  12579. */
  12580. this.autoUpdate = true;
  12581. /**
  12582. * The node which is used with the quad mesh for RTT.
  12583. *
  12584. * @private
  12585. * @type {Node}
  12586. * @default null
  12587. */
  12588. this._rttNode = null;
  12589. /**
  12590. * The internal quad mesh for RTT.
  12591. *
  12592. * @private
  12593. * @type {QuadMesh}
  12594. */
  12595. this._quadMesh = new QuadMesh( new NodeMaterial() );
  12596. /**
  12597. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  12598. * the texture once per render in its {@link RTTNode#updateBefore} method.
  12599. *
  12600. * @type {String}
  12601. * @default 'render'
  12602. */
  12603. this.updateBeforeType = NodeUpdateType.RENDER;
  12604. }
  12605. /**
  12606. * Whether the internal render target should automatically be resized or not.
  12607. *
  12608. * @type {Boolean}
  12609. * @readonly
  12610. * @default true
  12611. */
  12612. get autoSize() {
  12613. return this.width === null;
  12614. }
  12615. setup( builder ) {
  12616. this._rttNode = this.node.context( builder.getSharedContext() );
  12617. this._quadMesh.material.name = 'RTT';
  12618. this._quadMesh.material.needsUpdate = true;
  12619. return super.setup( builder );
  12620. }
  12621. /**
  12622. * Sets the size of the internal render target
  12623. *
  12624. * @param {Number} width - The width to set.
  12625. * @param {Number} height - The width to set.
  12626. */
  12627. setSize( width, height ) {
  12628. this.width = width;
  12629. this.height = height;
  12630. const effectiveWidth = width * this.pixelRatio;
  12631. const effectiveHeight = height * this.pixelRatio;
  12632. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  12633. this.textureNeedsUpdate = true;
  12634. }
  12635. /**
  12636. * Sets the pixel ratio. This will also resize the render target.
  12637. *
  12638. * @param {Number} pixelRatio - The pixel ratio to set.
  12639. */
  12640. setPixelRatio( pixelRatio ) {
  12641. this.pixelRatio = pixelRatio;
  12642. this.setSize( this.width, this.height );
  12643. }
  12644. updateBefore( { renderer } ) {
  12645. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  12646. this.textureNeedsUpdate = false;
  12647. //
  12648. if ( this.autoSize === true ) {
  12649. this.pixelRatio = renderer.getPixelRatio();
  12650. const size = renderer.getSize( _size$1 );
  12651. this.setSize( size.width, size.height );
  12652. }
  12653. //
  12654. this._quadMesh.material.fragmentNode = this._rttNode;
  12655. //
  12656. const currentRenderTarget = renderer.getRenderTarget();
  12657. renderer.setRenderTarget( this.renderTarget );
  12658. this._quadMesh.render( renderer );
  12659. renderer.setRenderTarget( currentRenderTarget );
  12660. }
  12661. clone() {
  12662. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  12663. newNode.sampler = this.sampler;
  12664. newNode.referenceNode = this;
  12665. return newNode;
  12666. }
  12667. }
  12668. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  12669. const convertToTexture = ( node, ...params ) => {
  12670. if ( node.isTextureNode ) return node;
  12671. if ( node.isPassNode ) return node.getTextureNode();
  12672. return rtt( node, ...params );
  12673. };
  12674. /** @module PostProcessingUtils **/
  12675. /**
  12676. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  12677. * depth value and the camera's inverse projection matrix.
  12678. *
  12679. * @method
  12680. * @param {Node<vec2>} screenPosition - The fragment's screen position expressed as uv coordinates.
  12681. * @param {Node<float>} depth - The fragment's depth value.
  12682. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  12683. * @return {Node<vec3>} The fragments position in view space.
  12684. */
  12685. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  12686. let clipSpacePosition;
  12687. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  12688. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  12689. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  12690. } else {
  12691. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  12692. }
  12693. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  12694. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  12695. } );
  12696. /**
  12697. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  12698. * and the camera's projection matrix
  12699. *
  12700. * @method
  12701. * @param {Node<vec3>} viewPosition - The fragments position in view space.
  12702. * @param {Node<mat4>} projectionMatrix - The camera's projection matrix.
  12703. * @return {Node<vec2>} The fragment's screen position expressed as uv coordinates.
  12704. */
  12705. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  12706. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  12707. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  12708. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  12709. } );
  12710. /**
  12711. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  12712. * target is available or if flat surface normals are required.
  12713. *
  12714. * @method
  12715. * @param {Node<vec2>} uv - The texture coordinate.
  12716. * @param {DepthTexture} depthTexture - The depth texture.
  12717. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  12718. * @return {Node<vec3>} The computed normal vector.
  12719. */
  12720. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  12721. const size = textureSize( textureLoad( depthTexture ) );
  12722. const p = ivec2( uv.mul( size ) ).toVar();
  12723. const c0 = textureLoad( depthTexture, p ).toVar();
  12724. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  12725. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  12726. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  12727. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  12728. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  12729. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  12730. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  12731. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  12732. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  12733. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  12734. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  12735. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  12736. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  12737. 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 ) ) );
  12738. 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 ) ) );
  12739. return normalize( cross( dpdx, dpdy ) );
  12740. } );
  12741. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  12742. constructor( array, itemSize, typeClass = Float32Array ) {
  12743. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  12744. super( array, itemSize );
  12745. this.isStorageInstancedBufferAttribute = true;
  12746. }
  12747. }
  12748. class StorageBufferAttribute extends BufferAttribute {
  12749. constructor( array, itemSize, typeClass = Float32Array ) {
  12750. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  12751. super( array, itemSize );
  12752. this.isStorageBufferAttribute = true;
  12753. }
  12754. }
  12755. /**
  12756. * This class enables element access on instances of {@link StorageBufferNode}.
  12757. * In most cases, it is indirectly used when accessing elements with the
  12758. * {@link StorageBufferNode#element} method.
  12759. *
  12760. * ```js
  12761. * const position = positionStorage.element( instanceIndex );
  12762. * ```
  12763. *
  12764. * @augments ArrayElementNode
  12765. */
  12766. class StorageArrayElementNode extends ArrayElementNode {
  12767. static get type() {
  12768. return 'StorageArrayElementNode';
  12769. }
  12770. /**
  12771. * Constructs storage buffer element node.
  12772. *
  12773. * @param {StorageBufferNode} node - The storage buffer node.
  12774. * @param {Node} indexNode - The index node that defines the element access.
  12775. */
  12776. constructor( storageBufferNode, indexNode ) {
  12777. super( storageBufferNode, indexNode );
  12778. /**
  12779. * This flag can be used for type testing.
  12780. *
  12781. * @type {Boolean}
  12782. * @readonly
  12783. * @default true
  12784. */
  12785. this.isStorageArrayElementNode = true;
  12786. }
  12787. /**
  12788. * The storage buffer node.
  12789. *
  12790. * @type {StorageBufferNode}
  12791. */
  12792. set storageBufferNode( value ) {
  12793. this.node = value;
  12794. }
  12795. get storageBufferNode() {
  12796. return this.node;
  12797. }
  12798. setup( builder ) {
  12799. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  12800. if ( this.node.isPBO === true ) {
  12801. builder.setupPBO( this.node );
  12802. }
  12803. }
  12804. return super.setup( builder );
  12805. }
  12806. generate( builder, output ) {
  12807. let snippet;
  12808. const isAssignContext = builder.context.assign;
  12809. //
  12810. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  12811. if ( this.node.isPBO === true && isAssignContext !== true && ( this.node.value.isInstancedBufferAttribute || builder.shaderStage !== 'compute' ) ) {
  12812. snippet = builder.generatePBO( this );
  12813. } else {
  12814. snippet = this.node.build( builder );
  12815. }
  12816. } else {
  12817. snippet = super.generate( builder );
  12818. }
  12819. if ( isAssignContext !== true ) {
  12820. const type = this.getNodeType( builder );
  12821. snippet = builder.format( snippet, type, output );
  12822. }
  12823. return snippet;
  12824. }
  12825. }
  12826. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode );
  12827. class StorageBufferNode extends BufferNode {
  12828. static get type() {
  12829. return 'StorageBufferNode';
  12830. }
  12831. constructor( value, bufferType = null, bufferCount = 0 ) {
  12832. if ( bufferType === null && ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) ) {
  12833. bufferType = getTypeFromLength( value.itemSize );
  12834. bufferCount = value.count;
  12835. }
  12836. super( value, bufferType, bufferCount );
  12837. this.isStorageBufferNode = true;
  12838. this.access = NodeAccess.READ_WRITE;
  12839. this.isAtomic = false;
  12840. this.isPBO = false;
  12841. this.bufferCount = bufferCount;
  12842. this._attribute = null;
  12843. this._varying = null;
  12844. this.global = true;
  12845. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  12846. // TOOD: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  12847. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  12848. else value.isStorageBufferAttribute = true;
  12849. }
  12850. }
  12851. getHash( builder ) {
  12852. if ( this.bufferCount === 0 ) {
  12853. let bufferData = builder.globalCache.getData( this.value );
  12854. if ( bufferData === undefined ) {
  12855. bufferData = {
  12856. node: this
  12857. };
  12858. builder.globalCache.setData( this.value, bufferData );
  12859. }
  12860. return bufferData.node.uuid;
  12861. }
  12862. return this.uuid;
  12863. }
  12864. getInputType( /*builder*/ ) {
  12865. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  12866. }
  12867. element( indexNode ) {
  12868. return storageElement( this, indexNode );
  12869. }
  12870. setPBO( value ) {
  12871. this.isPBO = value;
  12872. return this;
  12873. }
  12874. getPBO() {
  12875. return this.isPBO;
  12876. }
  12877. setAccess( value ) {
  12878. this.access = value;
  12879. return this;
  12880. }
  12881. toReadOnly() {
  12882. return this.setAccess( NodeAccess.READ_ONLY );
  12883. }
  12884. setAtomic( value ) {
  12885. this.isAtomic = value;
  12886. return this;
  12887. }
  12888. toAtomic() {
  12889. return this.setAtomic( true );
  12890. }
  12891. getAttributeData() {
  12892. if ( this._attribute === null ) {
  12893. this._attribute = bufferAttribute( this.value );
  12894. this._varying = varying( this._attribute );
  12895. }
  12896. return {
  12897. attribute: this._attribute,
  12898. varying: this._varying
  12899. };
  12900. }
  12901. getNodeType( builder ) {
  12902. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  12903. return super.getNodeType( builder );
  12904. }
  12905. const { attribute } = this.getAttributeData();
  12906. return attribute.getNodeType( builder );
  12907. }
  12908. generate( builder ) {
  12909. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  12910. return super.generate( builder );
  12911. }
  12912. const { attribute, varying } = this.getAttributeData();
  12913. const output = varying.build( builder );
  12914. builder.registerTransform( output, attribute );
  12915. return output;
  12916. }
  12917. }
  12918. const storage = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ) );
  12919. const storageObject = ( value, type, count ) => { // @deprecated, r171
  12920. console.warn( 'THREE.TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.' );
  12921. return storage( value, type, count ).setPBO( true );
  12922. };
  12923. const attributeArray = ( count, type = 'float' ) => {
  12924. const itemSize = getLengthFromType( type );
  12925. const buffer = new StorageBufferAttribute( count, itemSize );
  12926. const node = storage( buffer, type, count );
  12927. return node;
  12928. };
  12929. const instancedArray = ( count, type = 'float' ) => {
  12930. const itemSize = getLengthFromType( type );
  12931. const buffer = new StorageInstancedBufferAttribute( count, itemSize );
  12932. const node = storage( buffer, type, count );
  12933. return node;
  12934. };
  12935. class VertexColorNode extends AttributeNode {
  12936. static get type() {
  12937. return 'VertexColorNode';
  12938. }
  12939. constructor( index = 0 ) {
  12940. super( null, 'vec4' );
  12941. this.isVertexColorNode = true;
  12942. this.index = index;
  12943. }
  12944. getAttributeName( /*builder*/ ) {
  12945. const index = this.index;
  12946. return 'color' + ( index > 0 ? index : '' );
  12947. }
  12948. generate( builder ) {
  12949. const attributeName = this.getAttributeName( builder );
  12950. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  12951. let result;
  12952. if ( geometryAttribute === true ) {
  12953. result = super.generate( builder );
  12954. } else {
  12955. // Vertex color fallback should be white
  12956. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  12957. }
  12958. return result;
  12959. }
  12960. serialize( data ) {
  12961. super.serialize( data );
  12962. data.index = this.index;
  12963. }
  12964. deserialize( data ) {
  12965. super.deserialize( data );
  12966. this.index = data.index;
  12967. }
  12968. }
  12969. const vertexColor = ( ...params ) => nodeObject( new VertexColorNode( ...params ) );
  12970. class PointUVNode extends Node {
  12971. static get type() {
  12972. return 'PointUVNode';
  12973. }
  12974. constructor() {
  12975. super( 'vec2' );
  12976. this.isPointUVNode = true;
  12977. }
  12978. generate( /*builder*/ ) {
  12979. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  12980. }
  12981. }
  12982. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  12983. const _e1 = /*@__PURE__*/ new Euler();
  12984. const _m1 = /*@__PURE__*/ new Matrix4();
  12985. class SceneNode extends Node {
  12986. static get type() {
  12987. return 'SceneNode';
  12988. }
  12989. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  12990. super();
  12991. this.scope = scope;
  12992. this.scene = scene;
  12993. }
  12994. setup( builder ) {
  12995. const scope = this.scope;
  12996. const scene = this.scene !== null ? this.scene : builder.scene;
  12997. let output;
  12998. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  12999. output = reference( 'backgroundBlurriness', 'float', scene );
  13000. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  13001. output = reference( 'backgroundIntensity', 'float', scene );
  13002. } else if ( scope === SceneNode.BACKGROUND_ROTATION ) {
  13003. output = uniform( 'mat4' ).label( 'backgroundRotation' ).setGroup( renderGroup ).onRenderUpdate( () => {
  13004. const background = scene.background;
  13005. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  13006. _e1.copy( scene.backgroundRotation );
  13007. // accommodate left-handed frame
  13008. _e1.x *= - 1; _e1.y *= - 1; _e1.z *= - 1;
  13009. _m1.makeRotationFromEuler( _e1 );
  13010. } else {
  13011. _m1.identity();
  13012. }
  13013. return _m1;
  13014. } );
  13015. } else {
  13016. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  13017. }
  13018. return output;
  13019. }
  13020. }
  13021. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  13022. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  13023. SceneNode.BACKGROUND_ROTATION = 'backgroundRotation';
  13024. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  13025. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  13026. const backgroundRotation = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_ROTATION );
  13027. class StorageTextureNode extends TextureNode {
  13028. static get type() {
  13029. return 'StorageTextureNode';
  13030. }
  13031. constructor( value, uvNode, storeNode = null ) {
  13032. super( value, uvNode );
  13033. this.storeNode = storeNode;
  13034. this.isStorageTextureNode = true;
  13035. this.access = NodeAccess.WRITE_ONLY;
  13036. }
  13037. getInputType( /*builder*/ ) {
  13038. return 'storageTexture';
  13039. }
  13040. setup( builder ) {
  13041. super.setup( builder );
  13042. const properties = builder.getNodeProperties( this );
  13043. properties.storeNode = this.storeNode;
  13044. }
  13045. setAccess( value ) {
  13046. this.access = value;
  13047. return this;
  13048. }
  13049. generate( builder, output ) {
  13050. let snippet;
  13051. if ( this.storeNode !== null ) {
  13052. snippet = this.generateStore( builder );
  13053. } else {
  13054. snippet = super.generate( builder, output );
  13055. }
  13056. return snippet;
  13057. }
  13058. toReadWrite() {
  13059. return this.setAccess( NodeAccess.READ_WRITE );
  13060. }
  13061. toReadOnly() {
  13062. return this.setAccess( NodeAccess.READ_ONLY );
  13063. }
  13064. toWriteOnly() {
  13065. return this.setAccess( NodeAccess.WRITE_ONLY );
  13066. }
  13067. generateStore( builder ) {
  13068. const properties = builder.getNodeProperties( this );
  13069. const { uvNode, storeNode } = properties;
  13070. const textureProperty = super.generate( builder, 'property' );
  13071. const uvSnippet = uvNode.build( builder, 'uvec2' );
  13072. const storeSnippet = storeNode.build( builder, 'vec4' );
  13073. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, storeSnippet );
  13074. builder.addLineFlowCode( snippet, this );
  13075. }
  13076. }
  13077. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode );
  13078. const textureStore = ( value, uvNode, storeNode ) => {
  13079. const node = storageTexture( value, uvNode, storeNode );
  13080. if ( storeNode !== null ) node.append();
  13081. return node;
  13082. };
  13083. class UserDataNode extends ReferenceNode {
  13084. static get type() {
  13085. return 'UserDataNode';
  13086. }
  13087. constructor( property, inputType, userData = null ) {
  13088. super( property, inputType, userData );
  13089. this.userData = userData;
  13090. }
  13091. updateReference( state ) {
  13092. this.reference = this.userData !== null ? this.userData : state.object.userData;
  13093. return this.reference;
  13094. }
  13095. }
  13096. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  13097. const _objectData = new WeakMap();
  13098. class VelocityNode extends TempNode {
  13099. static get type() {
  13100. return 'VelocityNode';
  13101. }
  13102. constructor() {
  13103. super( 'vec2' );
  13104. this.projectionMatrix = null;
  13105. this.updateType = NodeUpdateType.OBJECT;
  13106. this.updateAfterType = NodeUpdateType.OBJECT;
  13107. this.previousModelWorldMatrix = uniform( new Matrix4() );
  13108. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  13109. this.previousCameraViewMatrix = uniform( new Matrix4() );
  13110. }
  13111. setProjectionMatrix( projectionMatrix ) {
  13112. this.projectionMatrix = projectionMatrix;
  13113. }
  13114. update( { frameId, camera, object } ) {
  13115. const previousModelMatrix = getPreviousMatrix( object );
  13116. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  13117. //
  13118. const cameraData = getData( camera );
  13119. if ( cameraData.frameId !== frameId ) {
  13120. cameraData.frameId = frameId;
  13121. if ( cameraData.previousProjectionMatrix === undefined ) {
  13122. cameraData.previousProjectionMatrix = new Matrix4();
  13123. cameraData.previousCameraViewMatrix = new Matrix4();
  13124. cameraData.currentProjectionMatrix = new Matrix4();
  13125. cameraData.currentCameraViewMatrix = new Matrix4();
  13126. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  13127. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  13128. } else {
  13129. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  13130. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  13131. }
  13132. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  13133. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  13134. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  13135. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  13136. }
  13137. }
  13138. updateAfter( { object } ) {
  13139. getPreviousMatrix( object ).copy( object.matrixWorld );
  13140. }
  13141. setup( /*builder*/ ) {
  13142. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  13143. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  13144. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  13145. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  13146. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  13147. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  13148. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  13149. return velocity;
  13150. }
  13151. }
  13152. function getData( object ) {
  13153. let objectData = _objectData.get( object );
  13154. if ( objectData === undefined ) {
  13155. objectData = {};
  13156. _objectData.set( object, objectData );
  13157. }
  13158. return objectData;
  13159. }
  13160. function getPreviousMatrix( object, index = 0 ) {
  13161. const objectData = getData( object );
  13162. let matrix = objectData[ index ];
  13163. if ( matrix === undefined ) {
  13164. objectData[ index ] = matrix = new Matrix4();
  13165. }
  13166. return matrix;
  13167. }
  13168. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  13169. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13170. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  13171. } ).setLayout( {
  13172. name: 'blendBurn',
  13173. type: 'vec3',
  13174. inputs: [
  13175. { name: 'base', type: 'vec3' },
  13176. { name: 'blend', type: 'vec3' }
  13177. ]
  13178. } );
  13179. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13180. return min$1( base.div( blend.oneMinus() ), 1.0 );
  13181. } ).setLayout( {
  13182. name: 'blendDodge',
  13183. type: 'vec3',
  13184. inputs: [
  13185. { name: 'base', type: 'vec3' },
  13186. { name: 'blend', type: 'vec3' }
  13187. ]
  13188. } );
  13189. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13190. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  13191. } ).setLayout( {
  13192. name: 'blendScreen',
  13193. type: 'vec3',
  13194. inputs: [
  13195. { name: 'base', type: 'vec3' },
  13196. { name: 'blend', type: 'vec3' }
  13197. ]
  13198. } );
  13199. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13200. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  13201. } ).setLayout( {
  13202. name: 'blendOverlay',
  13203. type: 'vec3',
  13204. inputs: [
  13205. { name: 'base', type: 'vec3' },
  13206. { name: 'blend', type: 'vec3' }
  13207. ]
  13208. } );
  13209. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13210. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  13211. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  13212. } ).setLayout( {
  13213. name: 'blendColor',
  13214. type: 'vec4',
  13215. inputs: [
  13216. { name: 'base', type: 'vec4' },
  13217. { name: 'blend', type: 'vec4' }
  13218. ]
  13219. } );
  13220. // deprecated
  13221. const burn = ( ...params ) => { // @deprecated, r171
  13222. console.warn( 'THREE.TSL: "burn" has been renamed. Use "blendBurn" instead.' );
  13223. return blendBurn( params );
  13224. };
  13225. const dodge = ( ...params ) => { // @deprecated, r171
  13226. console.warn( 'THREE.TSL: "dodge" has been renamed. Use "blendDodge" instead.' );
  13227. return blendDodge( params );
  13228. };
  13229. const screen = ( ...params ) => { // @deprecated, r171
  13230. console.warn( 'THREE.TSL: "screen" has been renamed. Use "blendScreen" instead.' );
  13231. return blendScreen( params );
  13232. };
  13233. const overlay = ( ...params ) => { // @deprecated, r171
  13234. console.warn( 'THREE.TSL: "overlay" has been renamed. Use "blendOverlay" instead.' );
  13235. return blendOverlay( params );
  13236. };
  13237. /** @module ColorAdjustment **/
  13238. /**
  13239. * Computes a grayscale value for the given RGB color value.
  13240. *
  13241. * @method
  13242. * @param {vec3} color - The color value to compute the grayscale for.
  13243. * @return {vec3} The grayscale color.
  13244. */
  13245. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  13246. return luminance( color.rgb );
  13247. } );
  13248. /**
  13249. * Super-saturates or desaturates the given RGB color.
  13250. *
  13251. * @method
  13252. * @param {vec3} color - The input color.
  13253. * @param {float} [adjustment=1] - Specifies the amount of the conversion. A value under `1` desaturates the color, a value over `1` super-saturates it.
  13254. * @return {vec3} The saturated color.
  13255. */
  13256. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  13257. return adjustment.mix( luminance( color.rgb ), color.rgb );
  13258. } );
  13259. /**
  13260. * Selectively enhance the intensity of less saturated RGB colors. Can result
  13261. * in a more natural and visually appealing image with enhanced color depth
  13262. * compared to {@link ColorAdjustment#saturation}.
  13263. *
  13264. * @method
  13265. * @param {vec3} color - The input color.
  13266. * @param {float} [adjustment=1] - Controls the intensity of the vibrance effect.
  13267. * @return {vec3} The updated color.
  13268. */
  13269. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  13270. const average = add( color.r, color.g, color.b ).div( 3.0 );
  13271. const mx = color.r.max( color.g.max( color.b ) );
  13272. const amt = mx.sub( average ).mul( adjustment ).mul( - 3.0 );
  13273. return mix( color.rgb, mx, amt );
  13274. } );
  13275. /**
  13276. * Updates the hue component of the given RGB color while preserving its luminance and saturation.
  13277. *
  13278. * @method
  13279. * @param {vec3} color - The input color.
  13280. * @param {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.
  13281. * @return {vec3} The updated color.
  13282. */
  13283. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  13284. const k = vec3( 0.57735, 0.57735, 0.57735 );
  13285. const cosAngle = adjustment.cos();
  13286. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  13287. } );
  13288. /**
  13289. * Computes the luminance for the given RGB color value.
  13290. *
  13291. * @method
  13292. * @param {vec3} color - The color value to compute the luminance for.
  13293. * @param {vec3?} luminanceCoefficients - The luminance coefficients. By default predefined values of the current working color space are used.
  13294. * @return {vec3} The luminance.
  13295. */
  13296. const luminance = (
  13297. color,
  13298. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  13299. ) => dot( color, luminanceCoefficients );
  13300. /**
  13301. * Color Decision List (CDL) v1.2
  13302. *
  13303. * Compact representation of color grading information, defined by slope, offset, power, and
  13304. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  13305. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  13306. *
  13307. * @method
  13308. * @param {vec4} color Input (-Infinity < input < +Infinity)
  13309. * @param {number | vec3} slope Slope (0 ≤ slope < +Infinity)
  13310. * @param {number | vec3} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  13311. * @param {number | vec3} power Power (0 < power < +Infinity)
  13312. * @param {number} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  13313. * @param {vec3} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  13314. * @return Output, -Infinity < output < +Infinity
  13315. *
  13316. * References:
  13317. * - ASC CDL v1.2
  13318. * - {@link https://blender.stackexchange.com/a/55239/43930}
  13319. * - {@link https://docs.acescentral.com/specifications/acescc/}
  13320. */
  13321. const cdl = /*@__PURE__*/ Fn( ( [
  13322. color,
  13323. slope = vec3( 1 ),
  13324. offset = vec3( 0 ),
  13325. power = vec3( 1 ),
  13326. saturation = float( 1 ),
  13327. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  13328. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  13329. ] ) => {
  13330. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  13331. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  13332. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  13333. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  13334. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  13335. const pv = v.pow( power ).toVar();
  13336. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  13337. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  13338. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  13339. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  13340. return vec4( v.rgb, color.a );
  13341. } );
  13342. /**
  13343. * Represents a posterize effect which reduces the number of colors
  13344. * in an image, resulting in a more blocky and stylized appearance.
  13345. *
  13346. * @augments TempNode
  13347. */
  13348. class PosterizeNode extends TempNode {
  13349. static get type() {
  13350. return 'PosterizeNode';
  13351. }
  13352. /**
  13353. * Constructs a new posterize node.
  13354. *
  13355. * @param {Node} sourceNode - The input color.
  13356. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  13357. */
  13358. constructor( sourceNode, stepsNode ) {
  13359. super();
  13360. /**
  13361. * The input color.
  13362. *
  13363. * @type {Node}
  13364. */
  13365. this.sourceNode = sourceNode;
  13366. /**
  13367. * Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  13368. *
  13369. * @type {Node}
  13370. */
  13371. this.stepsNode = stepsNode;
  13372. }
  13373. setup() {
  13374. const { sourceNode, stepsNode } = this;
  13375. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  13376. }
  13377. }
  13378. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode );
  13379. const _size = /*@__PURE__*/ new Vector2();
  13380. /**
  13381. * Represents the texture of a pass node.
  13382. *
  13383. * @augments TextureNode
  13384. * @private
  13385. */
  13386. class PassTextureNode extends TextureNode {
  13387. static get type() {
  13388. return 'PassTextureNode';
  13389. }
  13390. /**
  13391. * Constructs a new pass texture node.
  13392. *
  13393. * @param {PassNode} passNode - The pass node.
  13394. * @param {Texture} texture - The output texture.
  13395. */
  13396. constructor( passNode, texture ) {
  13397. super( texture );
  13398. /**
  13399. * A reference to the pass node.
  13400. *
  13401. * @type {PassNode}
  13402. */
  13403. this.passNode = passNode;
  13404. this.setUpdateMatrix( false );
  13405. }
  13406. setup( builder ) {
  13407. if ( builder.object.isQuadMesh ) this.passNode.build( builder );
  13408. return super.setup( builder );
  13409. }
  13410. clone() {
  13411. return new this.constructor( this.passNode, this.value );
  13412. }
  13413. }
  13414. /**
  13415. * An extension of `PassTextureNode` which allows to manage more than one
  13416. * internal texture. Relevant for the `getPreviousTexture()` related API.
  13417. *
  13418. * @augments PassTextureNode
  13419. * @private
  13420. */
  13421. class PassMultipleTextureNode extends PassTextureNode {
  13422. static get type() {
  13423. return 'PassMultipleTextureNode';
  13424. }
  13425. /**
  13426. * Constructs a new pass texture node.
  13427. *
  13428. * @param {PassNode} passNode - The pass node.
  13429. * @param {String} textureName - The output texture name.
  13430. * @param {Boolean} [previousTexture=false] - Whether previous frame data should be used or not.
  13431. */
  13432. constructor( passNode, textureName, previousTexture = false ) {
  13433. // null is passed to the super call since this class does not
  13434. // use an external texture for rendering pass data into. Instead
  13435. // the texture is managed by the pass node itself
  13436. super( passNode, null );
  13437. /**
  13438. * The output texture name.
  13439. *
  13440. * @type {String}
  13441. */
  13442. this.textureName = textureName;
  13443. /**
  13444. * Whether previous frame data should be used or not.
  13445. *
  13446. * @type {Boolean}
  13447. */
  13448. this.previousTexture = previousTexture;
  13449. }
  13450. /**
  13451. * Updates the texture reference of this node.
  13452. */
  13453. updateTexture() {
  13454. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  13455. }
  13456. setup( builder ) {
  13457. this.updateTexture();
  13458. return super.setup( builder );
  13459. }
  13460. clone() {
  13461. return new this.constructor( this.passNode, this.textureName, this.previousTexture );
  13462. }
  13463. }
  13464. /**
  13465. * Represents a render pass (sometimes called beauty pass) in context of post processing.
  13466. * This pass produces a render for the given scene and camera and can provide multiple outputs
  13467. * via MRT for further processing.
  13468. *
  13469. * ```js
  13470. * const postProcessing = new PostProcessing( renderer );
  13471. *
  13472. * const scenePass = pass( scene, camera );
  13473. *
  13474. * postProcessing.outputNode = scenePass;
  13475. * ```
  13476. *
  13477. * @augments TempNode
  13478. */
  13479. class PassNode extends TempNode {
  13480. static get type() {
  13481. return 'PassNode';
  13482. }
  13483. /**
  13484. * Constructs a new pass node.
  13485. *
  13486. * @param {('color'|'depth')} scope - The scope of the pass. The scope determines whether the node outputs color or depth.
  13487. * @param {Scene} scene - A reference to the scene.
  13488. * @param {Camera} camera - A reference to the camera.
  13489. * @param {Object} options - Options for the internal render target.
  13490. */
  13491. constructor( scope, scene, camera, options = {} ) {
  13492. super( 'vec4' );
  13493. /**
  13494. * The scope of the pass. The scope determines whether the node outputs color or depth.
  13495. *
  13496. * @type {('color'|'depth')}
  13497. */
  13498. this.scope = scope;
  13499. /**
  13500. * A reference to the scene.
  13501. *
  13502. * @type {Scene}
  13503. */
  13504. this.scene = scene;
  13505. /**
  13506. * A reference to the camera.
  13507. *
  13508. * @type {camera}
  13509. */
  13510. this.camera = camera;
  13511. /**
  13512. * Options for the internal render target.
  13513. *
  13514. * @type {Object}
  13515. */
  13516. this.options = options;
  13517. /**
  13518. * The pass's pixel ratio. Will be kept automatically kept in sync with the renderer's pixel ratio.
  13519. *
  13520. * @private
  13521. * @type {Number}
  13522. * @default 1
  13523. */
  13524. this._pixelRatio = 1;
  13525. /**
  13526. * The pass's pixel width. Will be kept automatically kept in sync with the renderer's width.
  13527. * @private
  13528. * @type {Number}
  13529. * @default 1
  13530. */
  13531. this._width = 1;
  13532. /**
  13533. * The pass's pixel height. Will be kept automatically kept in sync with the renderer's height.
  13534. * @private
  13535. * @type {Number}
  13536. * @default 1
  13537. */
  13538. this._height = 1;
  13539. const depthTexture = new DepthTexture();
  13540. depthTexture.isRenderTargetTexture = true;
  13541. //depthTexture.type = FloatType;
  13542. depthTexture.name = 'depth';
  13543. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  13544. renderTarget.texture.name = 'output';
  13545. renderTarget.depthTexture = depthTexture;
  13546. /**
  13547. * The pass's render target.
  13548. *
  13549. * @type {RenderTarget}
  13550. */
  13551. this.renderTarget = renderTarget;
  13552. /**
  13553. * A dictionary holding the internal result textures.
  13554. *
  13555. * @private
  13556. * @type {Object}
  13557. */
  13558. this._textures = {
  13559. output: renderTarget.texture,
  13560. depth: depthTexture
  13561. };
  13562. /**
  13563. * A dictionary holding the internal texture nodes.
  13564. *
  13565. * @private
  13566. * @type {Object}
  13567. */
  13568. this._textureNodes = {};
  13569. /**
  13570. * A dictionary holding the internal depth nodes.
  13571. *
  13572. * @private
  13573. * @type {Object}
  13574. */
  13575. this._linearDepthNodes = {};
  13576. /**
  13577. * A dictionary holding the internal viewZ nodes.
  13578. *
  13579. * @private
  13580. * @type {Object}
  13581. */
  13582. this._viewZNodes = {};
  13583. /**
  13584. * A dictionary holding the texture data of the previous frame.
  13585. * Used for computing velocity/motion vectors.
  13586. *
  13587. * @private
  13588. * @type {Object}
  13589. */
  13590. this._previousTextures = {};
  13591. /**
  13592. * A dictionary holding the texture nodes of the previous frame.
  13593. * Used for computing velocity/motion vectors.
  13594. *
  13595. * @private
  13596. * @type {Object}
  13597. */
  13598. this._previousTextureNodes = {};
  13599. /**
  13600. * The `near` property of the camera as a uniform.
  13601. *
  13602. * @private
  13603. * @type {UniformNode}
  13604. */
  13605. this._cameraNear = uniform( 0 );
  13606. /**
  13607. * The `far` property of the camera as a uniform.
  13608. *
  13609. * @private
  13610. * @type {UniformNode}
  13611. */
  13612. this._cameraFar = uniform( 0 );
  13613. /**
  13614. * A MRT node configuring the MRT settings.
  13615. *
  13616. * @private
  13617. * @type {MRTNode?}
  13618. * @default null
  13619. */
  13620. this._mrt = null;
  13621. /**
  13622. * This flag can be used for type testing.
  13623. *
  13624. * @type {Boolean}
  13625. * @readonly
  13626. * @default true
  13627. */
  13628. this.isPassNode = true;
  13629. /**
  13630. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  13631. * scene once per frame in its {@link PassNode#updateBefore} method.
  13632. *
  13633. * @type {String}
  13634. * @default 'frame'
  13635. */
  13636. this.updateBeforeType = NodeUpdateType.FRAME;
  13637. }
  13638. /**
  13639. * Sets the given MRT node to setup MRT for this pass.
  13640. *
  13641. * @param {MRTNode} mrt - The MRT object.
  13642. * @return {PassNode} A reference to this pass.
  13643. */
  13644. setMRT( mrt ) {
  13645. this._mrt = mrt;
  13646. return this;
  13647. }
  13648. /**
  13649. * Returns the current MRT node.
  13650. *
  13651. * @return {MRTNode} The current MRT node.
  13652. */
  13653. getMRT() {
  13654. return this._mrt;
  13655. }
  13656. /**
  13657. * The method is overwritten so it always returns `true`.
  13658. *
  13659. * @return {Boolean} Whether this node is global or not.
  13660. */
  13661. isGlobal() {
  13662. return true;
  13663. }
  13664. /**
  13665. * Returns the texture for the given output name.
  13666. *
  13667. * @param {String} name - The output name to get the texture for.
  13668. * @return {Texture} The texture.
  13669. */
  13670. getTexture( name ) {
  13671. let texture = this._textures[ name ];
  13672. if ( texture === undefined ) {
  13673. const refTexture = this.renderTarget.texture;
  13674. texture = refTexture.clone();
  13675. texture.name = name;
  13676. this._textures[ name ] = texture;
  13677. this.renderTarget.textures.push( texture );
  13678. }
  13679. return texture;
  13680. }
  13681. /**
  13682. * Returns the texture holding the data of the previous frame for the given output name.
  13683. *
  13684. * @param {String} name - The output name to get the texture for.
  13685. * @return {Texture} The texture holding the data of the previous frame.
  13686. */
  13687. getPreviousTexture( name ) {
  13688. let texture = this._previousTextures[ name ];
  13689. if ( texture === undefined ) {
  13690. texture = this.getTexture( name ).clone();
  13691. this._previousTextures[ name ] = texture;
  13692. }
  13693. return texture;
  13694. }
  13695. /**
  13696. * Switches current and previous textures for the given output name.
  13697. *
  13698. * @param {String} name - The output name.
  13699. */
  13700. toggleTexture( name ) {
  13701. const prevTexture = this._previousTextures[ name ];
  13702. if ( prevTexture !== undefined ) {
  13703. const texture = this._textures[ name ];
  13704. const index = this.renderTarget.textures.indexOf( texture );
  13705. this.renderTarget.textures[ index ] = prevTexture;
  13706. this._textures[ name ] = prevTexture;
  13707. this._previousTextures[ name ] = texture;
  13708. this._textureNodes[ name ].updateTexture();
  13709. this._previousTextureNodes[ name ].updateTexture();
  13710. }
  13711. }
  13712. /**
  13713. * Returns the texture node for the given output name.
  13714. *
  13715. * @param {String} [name='output'] - The output name to get the texture node for.
  13716. * @return {TextureNode} The texture node.
  13717. */
  13718. getTextureNode( name = 'output' ) {
  13719. let textureNode = this._textureNodes[ name ];
  13720. if ( textureNode === undefined ) {
  13721. textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  13722. textureNode.updateTexture();
  13723. this._textureNodes[ name ] = textureNode;
  13724. }
  13725. return textureNode;
  13726. }
  13727. /**
  13728. * Returns the previous texture node for the given output name.
  13729. *
  13730. * @param {String} [name='output'] - The output name to get the previous texture node for.
  13731. * @return {TextureNode} The previous texture node.
  13732. */
  13733. getPreviousTextureNode( name = 'output' ) {
  13734. let textureNode = this._previousTextureNodes[ name ];
  13735. if ( textureNode === undefined ) {
  13736. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  13737. textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  13738. textureNode.updateTexture();
  13739. this._previousTextureNodes[ name ] = textureNode;
  13740. }
  13741. return textureNode;
  13742. }
  13743. /**
  13744. * Returns a viewZ node of this pass.
  13745. *
  13746. * @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.
  13747. * @return {Node} The viewZ node.
  13748. */
  13749. getViewZNode( name = 'depth' ) {
  13750. let viewZNode = this._viewZNodes[ name ];
  13751. if ( viewZNode === undefined ) {
  13752. const cameraNear = this._cameraNear;
  13753. const cameraFar = this._cameraFar;
  13754. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  13755. }
  13756. return viewZNode;
  13757. }
  13758. /**
  13759. * Returns a linear depth node of this pass.
  13760. *
  13761. * @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.
  13762. * @return {Node} The linear depth node.
  13763. */
  13764. getLinearDepthNode( name = 'depth' ) {
  13765. let linearDepthNode = this._linearDepthNodes[ name ];
  13766. if ( linearDepthNode === undefined ) {
  13767. const cameraNear = this._cameraNear;
  13768. const cameraFar = this._cameraFar;
  13769. const viewZNode = this.getViewZNode( name );
  13770. // TODO: just if ( builder.camera.isPerspectiveCamera )
  13771. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  13772. }
  13773. return linearDepthNode;
  13774. }
  13775. setup( { renderer } ) {
  13776. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  13777. // Disable MSAA for WebGL backend for now
  13778. if ( renderer.backend.isWebGLBackend === true ) {
  13779. this.renderTarget.samples = 0;
  13780. }
  13781. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  13782. }
  13783. updateBefore( frame ) {
  13784. const { renderer } = frame;
  13785. const { scene, camera } = this;
  13786. this._pixelRatio = renderer.getPixelRatio();
  13787. const size = renderer.getSize( _size );
  13788. this.setSize( size.width, size.height );
  13789. const currentRenderTarget = renderer.getRenderTarget();
  13790. const currentMRT = renderer.getMRT();
  13791. this._cameraNear.value = camera.near;
  13792. this._cameraFar.value = camera.far;
  13793. for ( const name in this._previousTextures ) {
  13794. this.toggleTexture( name );
  13795. }
  13796. renderer.setRenderTarget( this.renderTarget );
  13797. renderer.setMRT( this._mrt );
  13798. renderer.render( scene, camera );
  13799. renderer.setRenderTarget( currentRenderTarget );
  13800. renderer.setMRT( currentMRT );
  13801. }
  13802. /**
  13803. * Sets the size of the pass's render target. Honors the pixel ratio.
  13804. *
  13805. * @param {Number} width - The width to set.
  13806. * @param {Number} height - The height to set.
  13807. */
  13808. setSize( width, height ) {
  13809. this._width = width;
  13810. this._height = height;
  13811. const effectiveWidth = this._width * this._pixelRatio;
  13812. const effectiveHeight = this._height * this._pixelRatio;
  13813. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  13814. }
  13815. /**
  13816. * Sets the pixel ratio the pass's render target and updates the size.
  13817. *
  13818. * @param {Number} pixelRatio - The pixel ratio to set.
  13819. */
  13820. setPixelRatio( pixelRatio ) {
  13821. this._pixelRatio = pixelRatio;
  13822. this.setSize( this._width, this._height );
  13823. }
  13824. /**
  13825. * Frees internal resources. Should be called when the node is no longer in use.
  13826. */
  13827. dispose() {
  13828. this.renderTarget.dispose();
  13829. }
  13830. }
  13831. PassNode.COLOR = 'color';
  13832. PassNode.DEPTH = 'depth';
  13833. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  13834. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  13835. const depthPass = ( scene, camera ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera ) );
  13836. /**
  13837. * Represents a render pass for producing a toon outline effect on compatible objects.
  13838. * Only 3D objects with materials of type `MeshToonMaterial` and `MeshToonNodeMaterial`
  13839. * will receive the outline.
  13840. *
  13841. * ```js
  13842. * const postProcessing = new PostProcessing( renderer );
  13843. *
  13844. * const scenePass = toonOutlinePass( scene, camera );
  13845. *
  13846. * postProcessing.outputNode = scenePass;
  13847. * ```
  13848. * @augments PassNode
  13849. */
  13850. class ToonOutlinePassNode extends PassNode {
  13851. static get type() {
  13852. return 'ToonOutlinePassNode';
  13853. }
  13854. /**
  13855. * Constructs a new outline pass node.
  13856. *
  13857. * @param {Scene} scene - A reference to the scene.
  13858. * @param {Camera} camera - A reference to the camera.
  13859. * @param {Node} colorNode - Defines the outline's color.
  13860. * @param {Node} thicknessNode - Defines the outline's thickness.
  13861. * @param {Node} alphaNode - Defines the outline's alpha.
  13862. */
  13863. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  13864. super( PassNode.COLOR, scene, camera );
  13865. /**
  13866. * Defines the outline's color.
  13867. *
  13868. * @type {Node}
  13869. */
  13870. this.colorNode = colorNode;
  13871. /**
  13872. * Defines the outline's thickness.
  13873. *
  13874. * @type {Node}
  13875. */
  13876. this.thicknessNode = thicknessNode;
  13877. /**
  13878. * Defines the outline's alpha.
  13879. *
  13880. * @type {Node}
  13881. */
  13882. this.alphaNode = alphaNode;
  13883. /**
  13884. * An internal material cache.
  13885. *
  13886. * @private
  13887. * @type {WeakMap}
  13888. */
  13889. this._materialCache = new WeakMap();
  13890. }
  13891. updateBefore( frame ) {
  13892. const { renderer } = frame;
  13893. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  13894. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  13895. // only render outline for supported materials
  13896. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  13897. if ( material.wireframe === false ) {
  13898. const outlineMaterial = this._getOutlineMaterial( material );
  13899. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  13900. }
  13901. }
  13902. // default
  13903. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  13904. } );
  13905. super.updateBefore( frame );
  13906. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  13907. }
  13908. /**
  13909. * Creates the material used for outline rendering.
  13910. *
  13911. * @private
  13912. * @return {NodeMaterial} The outline material.
  13913. */
  13914. _createMaterial() {
  13915. const material = new NodeMaterial();
  13916. material.isMeshToonOutlineMaterial = true;
  13917. material.name = 'Toon_Outline';
  13918. material.side = BackSide;
  13919. // vertex node
  13920. const outlineNormal = normalLocal.negate();
  13921. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  13922. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  13923. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  13924. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  13925. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  13926. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  13927. // color node
  13928. material.colorNode = vec4( this.colorNode, this.alphaNode );
  13929. return material;
  13930. }
  13931. /**
  13932. * For the given toon material, this method returns a correspoding
  13933. * outline material.
  13934. *
  13935. * @private
  13936. * @param {(MeshToonMaterial|MeshToonNodeMaterial)} originalMaterial - The toon material.
  13937. * @return {NodeMaterial} The outline material.
  13938. */
  13939. _getOutlineMaterial( originalMaterial ) {
  13940. let outlineMaterial = this._materialCache.get( originalMaterial );
  13941. if ( outlineMaterial === undefined ) {
  13942. outlineMaterial = this._createMaterial();
  13943. this._materialCache.set( originalMaterial, outlineMaterial );
  13944. }
  13945. return outlineMaterial;
  13946. }
  13947. }
  13948. 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 ) ) );
  13949. /** @module ToneMappingFunctions **/
  13950. /**
  13951. * Linear tone mapping, exposure only.
  13952. *
  13953. * @method
  13954. * @param {vec3} color - The color that should be tone mapped.
  13955. * @param {float} exposure - The exposure.
  13956. * @return {vec3} The tone mapped color.
  13957. */
  13958. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  13959. return color.mul( exposure ).clamp();
  13960. } ).setLayout( {
  13961. name: 'linearToneMapping',
  13962. type: 'vec3',
  13963. inputs: [
  13964. { name: 'color', type: 'vec3' },
  13965. { name: 'exposure', type: 'float' }
  13966. ]
  13967. } );
  13968. /**
  13969. * Reinhard tone mapping.
  13970. *
  13971. * Reference: {@link https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf}
  13972. *
  13973. * @method
  13974. * @param {vec3} color - The color that should be tone mapped.
  13975. * @param {float} exposure - The exposure.
  13976. * @return {vec3} The tone mapped color.
  13977. */
  13978. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  13979. color = color.mul( exposure );
  13980. return color.div( color.add( 1.0 ) ).clamp();
  13981. } ).setLayout( {
  13982. name: 'reinhardToneMapping',
  13983. type: 'vec3',
  13984. inputs: [
  13985. { name: 'color', type: 'vec3' },
  13986. { name: 'exposure', type: 'float' }
  13987. ]
  13988. } );
  13989. /**
  13990. * Cineon tone mapping.
  13991. *
  13992. * Reference: {@link http://filmicworlds.com/blog/filmic-tonemapping-operators/}
  13993. *
  13994. * @method
  13995. * @param {vec3} color - The color that should be tone mapped.
  13996. * @param {float} exposure - The exposure.
  13997. * @return {vec3} The tone mapped color.
  13998. */
  13999. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  14000. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  14001. color = color.mul( exposure );
  14002. color = color.sub( 0.004 ).max( 0.0 );
  14003. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  14004. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  14005. return a.div( b ).pow( 2.2 );
  14006. } ).setLayout( {
  14007. name: 'cineonToneMapping',
  14008. type: 'vec3',
  14009. inputs: [
  14010. { name: 'color', type: 'vec3' },
  14011. { name: 'exposure', type: 'float' }
  14012. ]
  14013. } );
  14014. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  14015. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  14016. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  14017. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  14018. return a.div( b );
  14019. } );
  14020. /**
  14021. * ACESFilmic tone mapping.
  14022. *
  14023. * Reference: {@link https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs}
  14024. *
  14025. * @method
  14026. * @param {vec3} color - The color that should be tone mapped.
  14027. * @param {float} exposure - The exposure.
  14028. * @return {vec3} The tone mapped color.
  14029. */
  14030. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  14031. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  14032. const ACESInputMat = mat3(
  14033. 0.59719, 0.35458, 0.04823,
  14034. 0.07600, 0.90834, 0.01566,
  14035. 0.02840, 0.13383, 0.83777
  14036. );
  14037. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  14038. const ACESOutputMat = mat3(
  14039. 1.60475, - 0.53108, - 0.07367,
  14040. - 0.10208, 1.10813, - 0.00605,
  14041. - 0.00327, - 0.07276, 1.07602
  14042. );
  14043. color = color.mul( exposure ).div( 0.6 );
  14044. color = ACESInputMat.mul( color );
  14045. // Apply RRT and ODT
  14046. color = RRTAndODTFit( color );
  14047. color = ACESOutputMat.mul( color );
  14048. // Clamp to [0, 1]
  14049. return color.clamp();
  14050. } ).setLayout( {
  14051. name: 'acesFilmicToneMapping',
  14052. type: 'vec3',
  14053. inputs: [
  14054. { name: 'color', type: 'vec3' },
  14055. { name: 'exposure', type: 'float' }
  14056. ]
  14057. } );
  14058. 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 ) );
  14059. 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 ) );
  14060. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  14061. const x = vec3( x_immutable ).toVar();
  14062. const x2 = vec3( x.mul( x ) ).toVar();
  14063. const x4 = vec3( x2.mul( x2 ) ).toVar();
  14064. 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 ) ) ) );
  14065. } );
  14066. /**
  14067. * AgX tone mapping.
  14068. *
  14069. * @method
  14070. * @param {vec3} color - The color that should be tone mapped.
  14071. * @param {float} exposure - The exposure.
  14072. * @return {vec3} The tone mapped color.
  14073. */
  14074. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  14075. const colortone = vec3( color ).toVar();
  14076. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  14077. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) );
  14078. const AgxMinEv = float( - 12.47393 );
  14079. const AgxMaxEv = float( 4.026069 );
  14080. colortone.mulAssign( exposure );
  14081. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  14082. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  14083. colortone.assign( max$1( colortone, 1e-10 ) );
  14084. colortone.assign( log2( colortone ) );
  14085. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  14086. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  14087. colortone.assign( agxDefaultContrastApprox( colortone ) );
  14088. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  14089. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  14090. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  14091. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  14092. return colortone;
  14093. } ).setLayout( {
  14094. name: 'agxToneMapping',
  14095. type: 'vec3',
  14096. inputs: [
  14097. { name: 'color', type: 'vec3' },
  14098. { name: 'exposure', type: 'float' }
  14099. ]
  14100. } );
  14101. /**
  14102. * Neutral tone mapping.
  14103. *
  14104. * Reference: {@link https://modelviewer.dev/examples/tone-mapping}
  14105. *
  14106. * @method
  14107. * @param {vec3} color - The color that should be tone mapped.
  14108. * @param {float} exposure - The exposure.
  14109. * @return {vec3} The tone mapped color.
  14110. */
  14111. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  14112. const StartCompression = float( 0.8 - 0.04 );
  14113. const Desaturation = float( 0.15 );
  14114. color = color.mul( exposure );
  14115. const x = min$1( color.r, min$1( color.g, color.b ) );
  14116. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  14117. color.subAssign( offset );
  14118. const peak = max$1( color.r, max$1( color.g, color.b ) );
  14119. If( peak.lessThan( StartCompression ), () => {
  14120. return color;
  14121. } );
  14122. const d = sub( 1, StartCompression );
  14123. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  14124. color.mulAssign( newPeak.div( peak ) );
  14125. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  14126. return mix( color, vec3( newPeak ), g );
  14127. } ).setLayout( {
  14128. name: 'neutralToneMapping',
  14129. type: 'vec3',
  14130. inputs: [
  14131. { name: 'color', type: 'vec3' },
  14132. { name: 'exposure', type: 'float' }
  14133. ]
  14134. } );
  14135. /**
  14136. * This class represents native code sections. It is the base
  14137. * class for modules like {@link FunctionNode} which allows to implement
  14138. * functions with native shader languages.
  14139. *
  14140. * @augments Node
  14141. */
  14142. class CodeNode extends Node {
  14143. static get type() {
  14144. return 'CodeNode';
  14145. }
  14146. /**
  14147. * Constructs a new code node.
  14148. *
  14149. * @param {String} [code=''] - The native code.
  14150. * @param {Array<Node>} [includes=[]] - An array of includes.
  14151. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  14152. */
  14153. constructor( code = '', includes = [], language = '' ) {
  14154. super( 'code' );
  14155. /**
  14156. * This flag can be used for type testing.
  14157. *
  14158. * @type {Boolean}
  14159. * @readonly
  14160. * @default true
  14161. */
  14162. this.isCodeNode = true;
  14163. /**
  14164. * The native code.
  14165. *
  14166. * @type {String}
  14167. * @default ''
  14168. */
  14169. this.code = code;
  14170. /**
  14171. * An array of includes
  14172. *
  14173. * @type {Array<Node>}
  14174. * @default []
  14175. */
  14176. this.includes = includes;
  14177. /**
  14178. * The used language.
  14179. *
  14180. * @type {('js'|'wgsl'|'glsl')}
  14181. * @default ''
  14182. */
  14183. this.language = language;
  14184. }
  14185. /**
  14186. * The method is overwritten so it always returns `true`.
  14187. *
  14188. * @return {Boolean} Whether this node is global or not.
  14189. */
  14190. isGlobal() {
  14191. return true;
  14192. }
  14193. /**
  14194. * Sets the includes of this code node.
  14195. *
  14196. * @param {Array<Node>} includes - The includes to set.
  14197. * @return {CodeNode} A reference to this node.
  14198. */
  14199. setIncludes( includes ) {
  14200. this.includes = includes;
  14201. return this;
  14202. }
  14203. /**
  14204. * Returns the includes of this code node.
  14205. *
  14206. * @param {NodeBuilder} builder - The current node builder.
  14207. * @return {Array<Node>} The includes.
  14208. */
  14209. getIncludes( /*builder*/ ) {
  14210. return this.includes;
  14211. }
  14212. generate( builder ) {
  14213. const includes = this.getIncludes( builder );
  14214. for ( const include of includes ) {
  14215. include.build( builder );
  14216. }
  14217. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  14218. nodeCode.code = this.code;
  14219. return nodeCode.code;
  14220. }
  14221. serialize( data ) {
  14222. super.serialize( data );
  14223. data.code = this.code;
  14224. data.language = this.language;
  14225. }
  14226. deserialize( data ) {
  14227. super.deserialize( data );
  14228. this.code = data.code;
  14229. this.language = data.language;
  14230. }
  14231. }
  14232. const code = /*@__PURE__*/ nodeProxy( CodeNode );
  14233. const js = ( src, includes ) => code( src, includes, 'js' );
  14234. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  14235. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  14236. /**
  14237. * This class represents a native shader function. It can be used to implement
  14238. * certain aspects of a node material with native shader code. There are two predefined
  14239. * TSL functions for easier usage.
  14240. *
  14241. * - `wgslFn`: Creates a WGSL function node.
  14242. * - `glslFn`: Creates a GLSL function node.
  14243. *
  14244. * A basic example with one include looks like so:
  14245. *
  14246. * ```js
  14247. * const desaturateWGSLFn = wgslFn( `
  14248. * fn desaturate( color:vec3<f32> ) -> vec3<f32> {
  14249. * let lum = vec3<f32>( 0.299, 0.587, 0.114 );
  14250. * return vec3<f32>( dot( lum, color ) );
  14251. * }`
  14252. *);
  14253. * const someWGSLFn = wgslFn( `
  14254. * fn someFn( color:vec3<f32> ) -> vec3<f32> {
  14255. * return desaturate( color );
  14256. * }
  14257. * `, [ desaturateWGSLFn ] );
  14258. * material.colorNode = someWGSLFn( { color: texture( map ) } );
  14259. *```
  14260. * @augments CodeNode
  14261. */
  14262. class FunctionNode extends CodeNode {
  14263. static get type() {
  14264. return 'FunctionNode';
  14265. }
  14266. /**
  14267. * Constructs a new function node.
  14268. *
  14269. * @param {String} [code=''] - The native code.
  14270. * @param {Array<Node>} [includes=[]] - An array of includes.
  14271. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  14272. */
  14273. constructor( code = '', includes = [], language = '' ) {
  14274. super( code, includes, language );
  14275. }
  14276. getNodeType( builder ) {
  14277. return this.getNodeFunction( builder ).type;
  14278. }
  14279. /**
  14280. * Returns the inputs of this function node.
  14281. *
  14282. * @param {NodeBuilder} builder - The current node builder.
  14283. * @return {Array<NodeFunctionInput>} The inputs.
  14284. */
  14285. getInputs( builder ) {
  14286. return this.getNodeFunction( builder ).inputs;
  14287. }
  14288. /**
  14289. * Returns the node function for this function node.
  14290. *
  14291. * @param {NodeBuilder} builder - The current node builder.
  14292. * @return {NodeFunction} The node function.
  14293. */
  14294. getNodeFunction( builder ) {
  14295. const nodeData = builder.getDataFromNode( this );
  14296. let nodeFunction = nodeData.nodeFunction;
  14297. if ( nodeFunction === undefined ) {
  14298. nodeFunction = builder.parser.parseFunction( this.code );
  14299. nodeData.nodeFunction = nodeFunction;
  14300. }
  14301. return nodeFunction;
  14302. }
  14303. generate( builder, output ) {
  14304. super.generate( builder );
  14305. const nodeFunction = this.getNodeFunction( builder );
  14306. const name = nodeFunction.name;
  14307. const type = nodeFunction.type;
  14308. const nodeCode = builder.getCodeFromNode( this, type );
  14309. if ( name !== '' ) {
  14310. // use a custom property name
  14311. nodeCode.name = name;
  14312. }
  14313. const propertyName = builder.getPropertyName( nodeCode );
  14314. const code = this.getNodeFunction( builder ).getCode( propertyName );
  14315. nodeCode.code = code + '\n';
  14316. if ( output === 'property' ) {
  14317. return propertyName;
  14318. } else {
  14319. return builder.format( `${ propertyName }()`, type, output );
  14320. }
  14321. }
  14322. }
  14323. const nativeFn = ( code, includes = [], language = '' ) => {
  14324. for ( let i = 0; i < includes.length; i ++ ) {
  14325. const include = includes[ i ];
  14326. // TSL Function: glslFn, wgslFn
  14327. if ( typeof include === 'function' ) {
  14328. includes[ i ] = include.functionNode;
  14329. }
  14330. }
  14331. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  14332. const fn = ( ...params ) => functionNode.call( ...params );
  14333. fn.functionNode = functionNode;
  14334. return fn;
  14335. };
  14336. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  14337. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  14338. class ScriptableValueNode extends Node {
  14339. static get type() {
  14340. return 'ScriptableValueNode';
  14341. }
  14342. constructor( value = null ) {
  14343. super();
  14344. this._value = value;
  14345. this._cache = null;
  14346. this.inputType = null;
  14347. this.outputType = null;
  14348. this.events = new EventDispatcher();
  14349. this.isScriptableValueNode = true;
  14350. }
  14351. get isScriptableOutputNode() {
  14352. return this.outputType !== null;
  14353. }
  14354. set value( val ) {
  14355. if ( this._value === val ) return;
  14356. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  14357. URL.revokeObjectURL( this._cache );
  14358. this._cache = null;
  14359. }
  14360. this._value = val;
  14361. this.events.dispatchEvent( { type: 'change' } );
  14362. this.refresh();
  14363. }
  14364. get value() {
  14365. return this._value;
  14366. }
  14367. refresh() {
  14368. this.events.dispatchEvent( { type: 'refresh' } );
  14369. }
  14370. getValue() {
  14371. const value = this.value;
  14372. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  14373. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  14374. } else if ( value && value.value !== null && value.value !== undefined && (
  14375. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  14376. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  14377. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  14378. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  14379. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  14380. ( this.inputType === 'Color' && value.value.isColor ) ||
  14381. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  14382. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  14383. ) ) {
  14384. return value.value;
  14385. }
  14386. return this._cache || value;
  14387. }
  14388. getNodeType( builder ) {
  14389. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  14390. }
  14391. setup() {
  14392. return this.value && this.value.isNode ? this.value : float();
  14393. }
  14394. serialize( data ) {
  14395. super.serialize( data );
  14396. if ( this.value !== null ) {
  14397. if ( this.inputType === 'ArrayBuffer' ) {
  14398. data.value = arrayBufferToBase64( this.value );
  14399. } else {
  14400. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  14401. }
  14402. } else {
  14403. data.value = null;
  14404. }
  14405. data.inputType = this.inputType;
  14406. data.outputType = this.outputType;
  14407. }
  14408. deserialize( data ) {
  14409. super.deserialize( data );
  14410. let value = null;
  14411. if ( data.value !== null ) {
  14412. if ( data.inputType === 'ArrayBuffer' ) {
  14413. value = base64ToArrayBuffer( data.value );
  14414. } else if ( data.inputType === 'Texture' ) {
  14415. value = data.meta.textures[ data.value ];
  14416. } else {
  14417. value = data.meta.nodes[ data.value ] || null;
  14418. }
  14419. }
  14420. this.value = value;
  14421. this.inputType = data.inputType;
  14422. this.outputType = data.outputType;
  14423. }
  14424. }
  14425. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode );
  14426. class Resources extends Map {
  14427. get( key, callback = null, ...params ) {
  14428. if ( this.has( key ) ) return super.get( key );
  14429. if ( callback !== null ) {
  14430. const value = callback( ...params );
  14431. this.set( key, value );
  14432. return value;
  14433. }
  14434. }
  14435. }
  14436. class Parameters {
  14437. constructor( scriptableNode ) {
  14438. this.scriptableNode = scriptableNode;
  14439. }
  14440. get parameters() {
  14441. return this.scriptableNode.parameters;
  14442. }
  14443. get layout() {
  14444. return this.scriptableNode.getLayout();
  14445. }
  14446. getInputLayout( id ) {
  14447. return this.scriptableNode.getInputLayout( id );
  14448. }
  14449. get( name ) {
  14450. const param = this.parameters[ name ];
  14451. const value = param ? param.getValue() : null;
  14452. return value;
  14453. }
  14454. }
  14455. const ScriptableNodeResources = new Resources();
  14456. class ScriptableNode extends Node {
  14457. static get type() {
  14458. return 'ScriptableNode';
  14459. }
  14460. constructor( codeNode = null, parameters = {} ) {
  14461. super();
  14462. this.codeNode = codeNode;
  14463. this.parameters = parameters;
  14464. this._local = new Resources();
  14465. this._output = scriptableValue();
  14466. this._outputs = {};
  14467. this._source = this.source;
  14468. this._method = null;
  14469. this._object = null;
  14470. this._value = null;
  14471. this._needsOutputUpdate = true;
  14472. this.onRefresh = this.onRefresh.bind( this );
  14473. this.isScriptableNode = true;
  14474. }
  14475. get source() {
  14476. return this.codeNode ? this.codeNode.code : '';
  14477. }
  14478. setLocal( name, value ) {
  14479. return this._local.set( name, value );
  14480. }
  14481. getLocal( name ) {
  14482. return this._local.get( name );
  14483. }
  14484. onRefresh() {
  14485. this._refresh();
  14486. }
  14487. getInputLayout( id ) {
  14488. for ( const element of this.getLayout() ) {
  14489. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  14490. return element;
  14491. }
  14492. }
  14493. }
  14494. getOutputLayout( id ) {
  14495. for ( const element of this.getLayout() ) {
  14496. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  14497. return element;
  14498. }
  14499. }
  14500. }
  14501. setOutput( name, value ) {
  14502. const outputs = this._outputs;
  14503. if ( outputs[ name ] === undefined ) {
  14504. outputs[ name ] = scriptableValue( value );
  14505. } else {
  14506. outputs[ name ].value = value;
  14507. }
  14508. return this;
  14509. }
  14510. getOutput( name ) {
  14511. return this._outputs[ name ];
  14512. }
  14513. getParameter( name ) {
  14514. return this.parameters[ name ];
  14515. }
  14516. setParameter( name, value ) {
  14517. const parameters = this.parameters;
  14518. if ( value && value.isScriptableNode ) {
  14519. this.deleteParameter( name );
  14520. parameters[ name ] = value;
  14521. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  14522. } else if ( value && value.isScriptableValueNode ) {
  14523. this.deleteParameter( name );
  14524. parameters[ name ] = value;
  14525. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  14526. } else if ( parameters[ name ] === undefined ) {
  14527. parameters[ name ] = scriptableValue( value );
  14528. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  14529. } else {
  14530. parameters[ name ].value = value;
  14531. }
  14532. return this;
  14533. }
  14534. getValue() {
  14535. return this.getDefaultOutput().getValue();
  14536. }
  14537. deleteParameter( name ) {
  14538. let valueNode = this.parameters[ name ];
  14539. if ( valueNode ) {
  14540. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  14541. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  14542. }
  14543. return this;
  14544. }
  14545. clearParameters() {
  14546. for ( const name of Object.keys( this.parameters ) ) {
  14547. this.deleteParameter( name );
  14548. }
  14549. this.needsUpdate = true;
  14550. return this;
  14551. }
  14552. call( name, ...params ) {
  14553. const object = this.getObject();
  14554. const method = object[ name ];
  14555. if ( typeof method === 'function' ) {
  14556. return method( ...params );
  14557. }
  14558. }
  14559. async callAsync( name, ...params ) {
  14560. const object = this.getObject();
  14561. const method = object[ name ];
  14562. if ( typeof method === 'function' ) {
  14563. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  14564. }
  14565. }
  14566. getNodeType( builder ) {
  14567. return this.getDefaultOutputNode().getNodeType( builder );
  14568. }
  14569. refresh( output = null ) {
  14570. if ( output !== null ) {
  14571. this.getOutput( output ).refresh();
  14572. } else {
  14573. this._refresh();
  14574. }
  14575. }
  14576. getObject() {
  14577. if ( this.needsUpdate ) this.dispose();
  14578. if ( this._object !== null ) return this._object;
  14579. //
  14580. const refresh = () => this.refresh();
  14581. const setOutput = ( id, value ) => this.setOutput( id, value );
  14582. const parameters = new Parameters( this );
  14583. const THREE = ScriptableNodeResources.get( 'THREE' );
  14584. const TSL = ScriptableNodeResources.get( 'TSL' );
  14585. const method = this.getMethod( this.codeNode );
  14586. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  14587. this._object = method( ...params );
  14588. const layout = this._object.layout;
  14589. if ( layout ) {
  14590. if ( layout.cache === false ) {
  14591. this._local.clear();
  14592. }
  14593. // default output
  14594. this._output.outputType = layout.outputType || null;
  14595. if ( Array.isArray( layout.elements ) ) {
  14596. for ( const element of layout.elements ) {
  14597. const id = element.id || element.name;
  14598. if ( element.inputType ) {
  14599. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  14600. this.getParameter( id ).inputType = element.inputType;
  14601. }
  14602. if ( element.outputType ) {
  14603. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  14604. this.getOutput( id ).outputType = element.outputType;
  14605. }
  14606. }
  14607. }
  14608. }
  14609. return this._object;
  14610. }
  14611. deserialize( data ) {
  14612. super.deserialize( data );
  14613. for ( const name in this.parameters ) {
  14614. let valueNode = this.parameters[ name ];
  14615. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  14616. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  14617. }
  14618. }
  14619. getLayout() {
  14620. return this.getObject().layout;
  14621. }
  14622. getDefaultOutputNode() {
  14623. const output = this.getDefaultOutput().value;
  14624. if ( output && output.isNode ) {
  14625. return output;
  14626. }
  14627. return float();
  14628. }
  14629. getDefaultOutput() {
  14630. return this._exec()._output;
  14631. }
  14632. getMethod() {
  14633. if ( this.needsUpdate ) this.dispose();
  14634. if ( this._method !== null ) return this._method;
  14635. //
  14636. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  14637. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  14638. const properties = interfaceProps.join( ', ' );
  14639. const declarations = 'var ' + properties + '; var output = {};\n';
  14640. const returns = '\nreturn { ...output, ' + properties + ' };';
  14641. const code = declarations + this.codeNode.code + returns;
  14642. //
  14643. this._method = new Function( ...parametersProps, code );
  14644. return this._method;
  14645. }
  14646. dispose() {
  14647. if ( this._method === null ) return;
  14648. if ( this._object && typeof this._object.dispose === 'function' ) {
  14649. this._object.dispose();
  14650. }
  14651. this._method = null;
  14652. this._object = null;
  14653. this._source = null;
  14654. this._value = null;
  14655. this._needsOutputUpdate = true;
  14656. this._output.value = null;
  14657. this._outputs = {};
  14658. }
  14659. setup() {
  14660. return this.getDefaultOutputNode();
  14661. }
  14662. getCacheKey( force ) {
  14663. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  14664. for ( const param in this.parameters ) {
  14665. values.push( this.parameters[ param ].getCacheKey( force ) );
  14666. }
  14667. return hashArray( values );
  14668. }
  14669. set needsUpdate( value ) {
  14670. if ( value === true ) this.dispose();
  14671. }
  14672. get needsUpdate() {
  14673. return this.source !== this._source;
  14674. }
  14675. _exec() {
  14676. if ( this.codeNode === null ) return this;
  14677. if ( this._needsOutputUpdate === true ) {
  14678. this._value = this.call( 'main' );
  14679. this._needsOutputUpdate = false;
  14680. }
  14681. this._output.value = this._value;
  14682. return this;
  14683. }
  14684. _refresh() {
  14685. this.needsUpdate = true;
  14686. this._exec();
  14687. this._output.refresh();
  14688. }
  14689. }
  14690. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode );
  14691. /**
  14692. * This class can be used to configure a fog for the scene.
  14693. * Nodes of this type are assigned to `Scene.fogNode`.
  14694. *
  14695. * @augments Node
  14696. */
  14697. class FogNode extends Node {
  14698. static get type() {
  14699. return 'FogNode';
  14700. }
  14701. /**
  14702. * Constructs a new fog node.
  14703. *
  14704. * @param {Node} colorNode - Defines the color of the fog.
  14705. * @param {Node} factorNode - Defines how the fog is factored in the scene.
  14706. */
  14707. constructor( colorNode, factorNode ) {
  14708. super( 'float' );
  14709. /**
  14710. * This flag can be used for type testing.
  14711. *
  14712. * @type {Boolean}
  14713. * @readonly
  14714. * @default true
  14715. */
  14716. this.isFogNode = true;
  14717. /**
  14718. * Defines the color of the fog.
  14719. *
  14720. * @type {Node?}
  14721. */
  14722. this.colorNode = colorNode;
  14723. /**
  14724. * Defines how the fog is factored in the scene.
  14725. *
  14726. * @type {Node?}
  14727. */
  14728. this.factorNode = factorNode;
  14729. }
  14730. /**
  14731. * Returns a node that represents the `z` coordinate in view space
  14732. * for the current fragment. It's a different representation of the
  14733. * default depth value.
  14734. *
  14735. * This value can be part of a computation that defines how the fog
  14736. * density increases when moving away from the camera.
  14737. *
  14738. * @param {NodeBuilder} builder - The current node builder.
  14739. * @return {Node} The viewZ node.
  14740. */
  14741. getViewZNode( builder ) {
  14742. let viewZ;
  14743. const getViewZ = builder.context.getViewZ;
  14744. if ( getViewZ !== undefined ) {
  14745. viewZ = getViewZ( this );
  14746. }
  14747. return ( viewZ || positionView.z ).negate();
  14748. }
  14749. setup() {
  14750. return this.factorNode;
  14751. }
  14752. }
  14753. const fog = /*@__PURE__*/ nodeProxy( FogNode );
  14754. /**
  14755. * Represents a range fog. The fog is smoothly interpolated
  14756. * between a range defined via near and far values.
  14757. *
  14758. * @augments FogNode
  14759. */
  14760. class FogRangeNode extends FogNode {
  14761. static get type() {
  14762. return 'FogRangeNode';
  14763. }
  14764. /**
  14765. * Constructs a new range node.
  14766. *
  14767. * @param {Node} colorNode - Defines the color of the fog.
  14768. * @param {Node} nearNode - Defines the near value.
  14769. * @param {Node} farNode - Defines the far value.
  14770. */
  14771. constructor( colorNode, nearNode, farNode ) {
  14772. super( colorNode, null );
  14773. /**
  14774. * This flag can be used for type testing.
  14775. *
  14776. * @type {Boolean}
  14777. * @readonly
  14778. * @default true
  14779. */
  14780. this.isFogRangeNode = true;
  14781. /**
  14782. * Defines the near value.
  14783. *
  14784. * @type {Node}
  14785. */
  14786. this.nearNode = nearNode;
  14787. /**
  14788. * Defines the far value.
  14789. *
  14790. * @type {Node}
  14791. */
  14792. this.farNode = farNode;
  14793. }
  14794. setup( builder ) {
  14795. const viewZ = this.getViewZNode( builder );
  14796. return smoothstep( this.nearNode, this.farNode, viewZ );
  14797. }
  14798. }
  14799. const rangeFog = /*@__PURE__*/ nodeProxy( FogRangeNode );
  14800. /**
  14801. * Represents an exponential squared fog. This type of fog gives
  14802. * a clear view near the camera and a faster than exponentially
  14803. * densening fog farther from the camera.
  14804. *
  14805. * @augments FogNode
  14806. */
  14807. class FogExp2Node extends FogNode {
  14808. static get type() {
  14809. return 'FogExp2Node';
  14810. }
  14811. /**
  14812. * Constructs a new exponential squared fog node.
  14813. *
  14814. * @param {Node} colorNode - Defines the color of the fog.
  14815. * @param {Node} densityNode - Defines the fog density.
  14816. */
  14817. constructor( colorNode, densityNode ) {
  14818. super( colorNode, null );
  14819. /**
  14820. * This flag can be used for type testing.
  14821. *
  14822. * @type {Boolean}
  14823. * @readonly
  14824. * @default true
  14825. */
  14826. this.isFogExp2Node = true;
  14827. /**
  14828. * Defines the fog density.
  14829. *
  14830. * @type {Node}
  14831. */
  14832. this.densityNode = densityNode;
  14833. }
  14834. setup( builder ) {
  14835. const viewZ = this.getViewZNode( builder );
  14836. const density = this.densityNode;
  14837. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  14838. }
  14839. }
  14840. const densityFog = /*@__PURE__*/ nodeProxy( FogExp2Node );
  14841. let min = null;
  14842. let max = null;
  14843. class RangeNode extends Node {
  14844. static get type() {
  14845. return 'RangeNode';
  14846. }
  14847. constructor( minNode = float(), maxNode = float() ) {
  14848. super();
  14849. this.minNode = minNode;
  14850. this.maxNode = maxNode;
  14851. }
  14852. getVectorLength( builder ) {
  14853. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  14854. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  14855. return minLength > maxLength ? minLength : maxLength;
  14856. }
  14857. getNodeType( builder ) {
  14858. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  14859. }
  14860. setup( builder ) {
  14861. const object = builder.object;
  14862. let output = null;
  14863. if ( object.count > 1 ) {
  14864. const minValue = this.minNode.value;
  14865. const maxValue = this.maxNode.value;
  14866. const minLength = builder.getTypeLength( getValueType( minValue ) );
  14867. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  14868. min = min || new Vector4();
  14869. max = max || new Vector4();
  14870. min.setScalar( 0 );
  14871. max.setScalar( 0 );
  14872. if ( minLength === 1 ) min.setScalar( minValue );
  14873. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b );
  14874. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  14875. if ( maxLength === 1 ) max.setScalar( maxValue );
  14876. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b );
  14877. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  14878. const stride = 4;
  14879. const length = stride * object.count;
  14880. const array = new Float32Array( length );
  14881. for ( let i = 0; i < length; i ++ ) {
  14882. const index = i % stride;
  14883. const minElementValue = min.getComponent( index );
  14884. const maxElementValue = max.getComponent( index );
  14885. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  14886. }
  14887. const nodeType = this.getNodeType( builder );
  14888. if ( object.count <= 4096 ) {
  14889. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  14890. } else {
  14891. // TODO: Improve anonymous buffer attribute creation removing this part
  14892. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  14893. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  14894. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  14895. }
  14896. } else {
  14897. output = float( 0 );
  14898. }
  14899. return output;
  14900. }
  14901. }
  14902. const range = /*@__PURE__*/ nodeProxy( RangeNode );
  14903. class ComputeBuiltinNode extends Node {
  14904. static get type() {
  14905. return 'ComputeBuiltinNode';
  14906. }
  14907. constructor( builtinName, nodeType ) {
  14908. super( nodeType );
  14909. this._builtinName = builtinName;
  14910. }
  14911. getHash( builder ) {
  14912. return this.getBuiltinName( builder );
  14913. }
  14914. getNodeType( /*builder*/ ) {
  14915. return this.nodeType;
  14916. }
  14917. setBuiltinName( builtinName ) {
  14918. this._builtinName = builtinName;
  14919. return this;
  14920. }
  14921. getBuiltinName( /*builder*/ ) {
  14922. return this._builtinName;
  14923. }
  14924. hasBuiltin( builder ) {
  14925. builder.hasBuiltin( this._builtinName );
  14926. }
  14927. generate( builder, output ) {
  14928. const builtinName = this.getBuiltinName( builder );
  14929. const nodeType = this.getNodeType( builder );
  14930. if ( builder.shaderStage === 'compute' ) {
  14931. return builder.format( builtinName, nodeType, output );
  14932. } else {
  14933. console.warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  14934. return builder.generateConst( nodeType );
  14935. }
  14936. }
  14937. serialize( data ) {
  14938. super.serialize( data );
  14939. data.global = this.global;
  14940. data._builtinName = this._builtinName;
  14941. }
  14942. deserialize( data ) {
  14943. super.deserialize( data );
  14944. this.global = data.global;
  14945. this._builtinName = data._builtinName;
  14946. }
  14947. }
  14948. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  14949. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  14950. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  14951. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  14952. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  14953. class BarrierNode extends Node {
  14954. constructor( scope ) {
  14955. super();
  14956. this.scope = scope;
  14957. }
  14958. generate( builder ) {
  14959. const { scope } = this;
  14960. const { renderer } = builder;
  14961. if ( renderer.backend.isWebGLBackend === true ) {
  14962. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  14963. } else {
  14964. builder.addLineFlowCode( `${scope}Barrier()`, this );
  14965. }
  14966. }
  14967. }
  14968. const barrier = nodeProxy( BarrierNode );
  14969. const workgroupBarrier = () => barrier( 'workgroup' ).append();
  14970. const storageBarrier = () => barrier( 'storage' ).append();
  14971. const textureBarrier = () => barrier( 'texture' ).append();
  14972. class WorkgroupInfoElementNode extends ArrayElementNode {
  14973. constructor( workgroupInfoNode, indexNode ) {
  14974. super( workgroupInfoNode, indexNode );
  14975. this.isWorkgroupInfoElementNode = true;
  14976. }
  14977. generate( builder, output ) {
  14978. let snippet;
  14979. const isAssignContext = builder.context.assign;
  14980. snippet = super.generate( builder );
  14981. if ( isAssignContext !== true ) {
  14982. const type = this.getNodeType( builder );
  14983. snippet = builder.format( snippet, type, output );
  14984. }
  14985. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  14986. return snippet;
  14987. }
  14988. }
  14989. class WorkgroupInfoNode extends Node {
  14990. constructor( scope, bufferType, bufferCount = 0 ) {
  14991. super( bufferType );
  14992. this.bufferType = bufferType;
  14993. this.bufferCount = bufferCount;
  14994. this.isWorkgroupInfoNode = true;
  14995. this.scope = scope;
  14996. }
  14997. label( name ) {
  14998. this.name = name;
  14999. return this;
  15000. }
  15001. getHash() {
  15002. return this.uuid;
  15003. }
  15004. setScope( scope ) {
  15005. this.scope = scope;
  15006. return this;
  15007. }
  15008. getInputType( /*builder*/ ) {
  15009. return `${this.scope}Array`;
  15010. }
  15011. element( indexNode ) {
  15012. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  15013. }
  15014. generate( builder ) {
  15015. return builder.getScopedArray( this.name || `${this.scope}Array_${this.id}`, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  15016. }
  15017. }
  15018. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  15019. class AtomicFunctionNode extends TempNode {
  15020. static get type() {
  15021. return 'AtomicFunctionNode';
  15022. }
  15023. constructor( method, pointerNode, valueNode, storeNode = null ) {
  15024. super( 'uint' );
  15025. this.method = method;
  15026. this.pointerNode = pointerNode;
  15027. this.valueNode = valueNode;
  15028. this.storeNode = storeNode;
  15029. }
  15030. getInputType( builder ) {
  15031. return this.pointerNode.getNodeType( builder );
  15032. }
  15033. getNodeType( builder ) {
  15034. return this.getInputType( builder );
  15035. }
  15036. generate( builder ) {
  15037. const method = this.method;
  15038. const type = this.getNodeType( builder );
  15039. const inputType = this.getInputType( builder );
  15040. const a = this.pointerNode;
  15041. const b = this.valueNode;
  15042. const params = [];
  15043. params.push( `&${ a.build( builder, inputType ) }` );
  15044. params.push( b.build( builder, inputType ) );
  15045. const methodSnippet = `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`;
  15046. if ( this.storeNode !== null ) {
  15047. const varSnippet = this.storeNode.build( builder, inputType );
  15048. builder.addLineFlowCode( `${varSnippet} = ${methodSnippet}`, this );
  15049. } else {
  15050. builder.addLineFlowCode( methodSnippet, this );
  15051. }
  15052. }
  15053. }
  15054. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  15055. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  15056. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  15057. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  15058. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  15059. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  15060. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  15061. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  15062. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  15063. const atomicNode = nodeProxy( AtomicFunctionNode );
  15064. const atomicFunc = ( method, pointerNode, valueNode, storeNode ) => {
  15065. const node = atomicNode( method, pointerNode, valueNode, storeNode );
  15066. node.append();
  15067. return node;
  15068. };
  15069. const atomicStore = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode, storeNode );
  15070. const atomicAdd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode, storeNode );
  15071. const atomicSub = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode, storeNode );
  15072. const atomicMax = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode, storeNode );
  15073. const atomicMin = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode, storeNode );
  15074. const atomicAnd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode, storeNode );
  15075. const atomicOr = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode, storeNode );
  15076. const atomicXor = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode, storeNode );
  15077. let uniformsLib;
  15078. function getLightData( light ) {
  15079. uniformsLib = uniformsLib || new WeakMap();
  15080. let uniforms = uniformsLib.get( light );
  15081. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  15082. return uniforms;
  15083. }
  15084. function lightShadowMatrix( light ) {
  15085. const data = getLightData( light );
  15086. return data.shadowMatrix || ( data.shadowMatrix = uniform( 'mat4' ).setGroup( renderGroup ).onRenderUpdate( () => {
  15087. light.shadow.updateMatrices( light );
  15088. return light.shadow.matrix;
  15089. } ) );
  15090. }
  15091. function lightProjectionUV( light ) {
  15092. const data = getLightData( light );
  15093. if ( data.projectionUV === undefined ) {
  15094. const spotLightCoord = lightShadowMatrix( light ).mul( positionWorld );
  15095. data.projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  15096. }
  15097. return data.projectionUV;
  15098. }
  15099. function lightPosition( light ) {
  15100. const data = getLightData( light );
  15101. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  15102. }
  15103. function lightTargetPosition( light ) {
  15104. const data = getLightData( light );
  15105. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  15106. }
  15107. function lightViewPosition( light ) {
  15108. const data = getLightData( light );
  15109. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  15110. self.value = self.value || new Vector3();
  15111. self.value.setFromMatrixPosition( light.matrixWorld );
  15112. self.value.applyMatrix4( camera.matrixWorldInverse );
  15113. } ) );
  15114. }
  15115. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  15116. const sortLights = ( lights ) => {
  15117. return lights.sort( ( a, b ) => a.id - b.id );
  15118. };
  15119. const getLightNodeById = ( id, lightNodes ) => {
  15120. for ( const lightNode of lightNodes ) {
  15121. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  15122. return lightNode;
  15123. }
  15124. }
  15125. return null;
  15126. };
  15127. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  15128. class LightsNode extends Node {
  15129. static get type() {
  15130. return 'LightsNode';
  15131. }
  15132. constructor() {
  15133. super( 'vec3' );
  15134. this.totalDiffuseNode = vec3().toVar( 'totalDiffuse' );
  15135. this.totalSpecularNode = vec3().toVar( 'totalSpecular' );
  15136. this.outgoingLightNode = vec3().toVar( 'outgoingLight' );
  15137. this._lights = [];
  15138. this._lightNodes = null;
  15139. this._lightNodesHash = null;
  15140. this.global = true;
  15141. }
  15142. /**
  15143. * Overwrites the default `customCacheKey()` implementation by including the
  15144. * light IDs into the cache key.
  15145. *
  15146. * @return {Number} The hash.
  15147. */
  15148. customCacheKey() {
  15149. const lightIDs = [];
  15150. for ( let i = 0; i < lights.length; i ++ ) {
  15151. lightIDs.push( lights[ i ].id );
  15152. }
  15153. return hashArray( lightIDs );
  15154. }
  15155. getHash( builder ) {
  15156. if ( this._lightNodesHash === null ) {
  15157. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  15158. const hash = [];
  15159. for ( const lightNode of this._lightNodes ) {
  15160. hash.push( lightNode.getSelf().getHash() );
  15161. }
  15162. this._lightNodesHash = 'lights-' + hash.join( ',' );
  15163. }
  15164. return this._lightNodesHash;
  15165. }
  15166. analyze( builder ) {
  15167. const properties = builder.getDataFromNode( this );
  15168. for ( const node of properties.nodes ) {
  15169. node.build( builder );
  15170. }
  15171. }
  15172. setupLightsNode( builder ) {
  15173. const lightNodes = [];
  15174. const previousLightNodes = this._lightNodes;
  15175. const lights = sortLights( this._lights );
  15176. const nodeLibrary = builder.renderer.library;
  15177. for ( const light of lights ) {
  15178. if ( light.isNode ) {
  15179. lightNodes.push( nodeObject( light ) );
  15180. } else {
  15181. let lightNode = null;
  15182. if ( previousLightNodes !== null ) {
  15183. lightNode = getLightNodeById( light.id, previousLightNodes ); // reuse existing light node
  15184. }
  15185. if ( lightNode === null ) {
  15186. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  15187. if ( lightNodeClass === null ) {
  15188. console.warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  15189. continue;
  15190. }
  15191. let lightNode = null;
  15192. if ( ! _lightsNodeRef.has( light ) ) {
  15193. lightNode = nodeObject( new lightNodeClass( light ) );
  15194. _lightsNodeRef.set( light, lightNode );
  15195. } else {
  15196. lightNode = _lightsNodeRef.get( light );
  15197. }
  15198. lightNodes.push( lightNode );
  15199. }
  15200. }
  15201. }
  15202. this._lightNodes = lightNodes;
  15203. }
  15204. setupLights( builder, lightNodes ) {
  15205. for ( const lightNode of lightNodes ) {
  15206. lightNode.build( builder );
  15207. }
  15208. }
  15209. setup( builder ) {
  15210. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  15211. const context = builder.context;
  15212. const lightingModel = context.lightingModel;
  15213. let outgoingLightNode = this.outgoingLightNode;
  15214. if ( lightingModel ) {
  15215. const { _lightNodes, totalDiffuseNode, totalSpecularNode } = this;
  15216. context.outgoingLight = outgoingLightNode;
  15217. const stack = builder.addStack();
  15218. //
  15219. const properties = builder.getDataFromNode( this );
  15220. properties.nodes = stack.nodes;
  15221. //
  15222. lightingModel.start( context, stack, builder );
  15223. // lights
  15224. this.setupLights( builder, _lightNodes );
  15225. //
  15226. lightingModel.indirect( context, stack, builder );
  15227. //
  15228. const { backdrop, backdropAlpha } = context;
  15229. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  15230. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  15231. if ( backdrop !== null ) {
  15232. if ( backdropAlpha !== null ) {
  15233. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  15234. } else {
  15235. totalDiffuse = vec3( backdrop );
  15236. }
  15237. context.material.transparent = true;
  15238. }
  15239. totalDiffuseNode.assign( totalDiffuse );
  15240. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  15241. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  15242. //
  15243. lightingModel.finish( context, stack, builder );
  15244. //
  15245. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  15246. }
  15247. return outgoingLightNode;
  15248. }
  15249. setLights( lights ) {
  15250. this._lights = lights;
  15251. this._lightNodes = null;
  15252. this._lightNodesHash = null;
  15253. return this;
  15254. }
  15255. getLights() {
  15256. return this._lights;
  15257. }
  15258. get hasLights() {
  15259. return this._lights.length > 0;
  15260. }
  15261. }
  15262. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  15263. class ShadowBaseNode extends Node {
  15264. static get type() {
  15265. return 'ShadowBaseNode';
  15266. }
  15267. constructor( light ) {
  15268. super();
  15269. this.light = light;
  15270. this.updateBeforeType = NodeUpdateType.RENDER;
  15271. this.isShadowBaseNode = true;
  15272. }
  15273. setupShadowPosition( { material } ) {
  15274. // Use assign inside an Fn()
  15275. shadowWorldPosition.assign( material.shadowPositionNode || positionWorld );
  15276. }
  15277. dispose() {
  15278. this.updateBeforeType = NodeUpdateType.NONE;
  15279. }
  15280. }
  15281. const shadowWorldPosition = /*@__PURE__*/ vec3().toVar( 'shadowWorldPosition' );
  15282. const shadowMaterialLib = /*@__PURE__*/ new WeakMap();
  15283. const linearDistance = /*@__PURE__*/ Fn( ( [ position, cameraNear, cameraFar ] ) => {
  15284. let dist = positionWorld.sub( position ).length();
  15285. dist = dist.sub( cameraNear ).div( cameraFar.sub( cameraNear ) );
  15286. dist = dist.saturate(); // clamp to [ 0, 1 ]
  15287. return dist;
  15288. } );
  15289. const linearShadowDistance = ( light ) => {
  15290. const camera = light.shadow.camera;
  15291. const nearDistance = reference( 'near', 'float', camera ).setGroup( renderGroup );
  15292. const farDistance = reference( 'far', 'float', camera ).setGroup( renderGroup );
  15293. const referencePosition = objectPosition( light );
  15294. return linearDistance( referencePosition, nearDistance, farDistance );
  15295. };
  15296. const getShadowMaterial = ( light ) => {
  15297. let material = shadowMaterialLib.get( light );
  15298. if ( material === undefined ) {
  15299. const depthNode = light.isPointLight ? linearShadowDistance( light ) : null;
  15300. material = new NodeMaterial();
  15301. material.colorNode = vec4( 0, 0, 0, 1 );
  15302. material.depthNode = depthNode;
  15303. material.isShadowNodeMaterial = true; // Use to avoid other overrideMaterial override material.colorNode unintentionally when using material.shadowNode
  15304. material.blending = NoBlending;
  15305. material.name = 'ShadowMaterial';
  15306. shadowMaterialLib.set( light, material );
  15307. }
  15308. return material;
  15309. };
  15310. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord } ) => {
  15311. return texture( depthTexture, shadowCoord.xy ).compare( shadowCoord.z );
  15312. } );
  15313. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  15314. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  15315. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  15316. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  15317. const texelSize = vec2( 1 ).div( mapSize );
  15318. const dx0 = texelSize.x.negate().mul( radius );
  15319. const dy0 = texelSize.y.negate().mul( radius );
  15320. const dx1 = texelSize.x.mul( radius );
  15321. const dy1 = texelSize.y.mul( radius );
  15322. const dx2 = dx0.div( 2 );
  15323. const dy2 = dy0.div( 2 );
  15324. const dx3 = dx1.div( 2 );
  15325. const dy3 = dy1.div( 2 );
  15326. return add(
  15327. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  15328. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  15329. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  15330. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  15331. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  15332. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  15333. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  15334. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  15335. depthCompare( shadowCoord.xy, shadowCoord.z ),
  15336. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  15337. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  15338. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  15339. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  15340. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  15341. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  15342. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  15343. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  15344. ).mul( 1 / 17 );
  15345. } );
  15346. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  15347. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  15348. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  15349. const texelSize = vec2( 1 ).div( mapSize );
  15350. const dx = texelSize.x;
  15351. const dy = texelSize.y;
  15352. const uv = shadowCoord.xy;
  15353. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  15354. uv.subAssign( f.mul( texelSize ) );
  15355. return add(
  15356. depthCompare( uv, shadowCoord.z ),
  15357. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  15358. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  15359. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  15360. mix(
  15361. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  15362. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  15363. f.x
  15364. ),
  15365. mix(
  15366. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  15367. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  15368. f.x
  15369. ),
  15370. mix(
  15371. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  15372. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  15373. f.y
  15374. ),
  15375. mix(
  15376. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  15377. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  15378. f.y
  15379. ),
  15380. mix(
  15381. mix(
  15382. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  15383. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  15384. f.x
  15385. ),
  15386. mix(
  15387. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  15388. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  15389. f.x
  15390. ),
  15391. f.y
  15392. )
  15393. ).mul( 1 / 9 );
  15394. } );
  15395. // VSM
  15396. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord } ) => {
  15397. const occlusion = float( 1 ).toVar();
  15398. const distribution = texture( depthTexture ).sample( shadowCoord.xy ).rg;
  15399. const hardShadow = step( shadowCoord.z, distribution.x );
  15400. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  15401. const distance = shadowCoord.z.sub( distribution.x );
  15402. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  15403. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  15404. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  15405. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  15406. } );
  15407. return occlusion;
  15408. } );
  15409. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass } ) => {
  15410. const mean = float( 0 ).toVar();
  15411. const squaredMean = float( 0 ).toVar();
  15412. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  15413. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  15414. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  15415. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  15416. const depth = shadowPass.sample( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) ).x;
  15417. mean.addAssign( depth );
  15418. squaredMean.addAssign( depth.mul( depth ) );
  15419. } );
  15420. mean.divAssign( samples );
  15421. squaredMean.divAssign( samples );
  15422. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  15423. return vec2( mean, std_dev );
  15424. } );
  15425. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass } ) => {
  15426. const mean = float( 0 ).toVar();
  15427. const squaredMean = float( 0 ).toVar();
  15428. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  15429. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  15430. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  15431. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  15432. const distribution = shadowPass.sample( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  15433. mean.addAssign( distribution.x );
  15434. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  15435. } );
  15436. mean.divAssign( samples );
  15437. squaredMean.divAssign( samples );
  15438. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  15439. return vec2( mean, std_dev );
  15440. } );
  15441. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  15442. //
  15443. const _quadMesh$1 = /*@__PURE__*/ new QuadMesh();
  15444. class ShadowNode extends ShadowBaseNode {
  15445. static get type() {
  15446. return 'ShadowNode';
  15447. }
  15448. constructor( light, shadow = null ) {
  15449. super( light );
  15450. this.shadow = shadow || light.shadow;
  15451. this.shadowMap = null;
  15452. this.vsmShadowMapVertical = null;
  15453. this.vsmShadowMapHorizontal = null;
  15454. this.vsmMaterialVertical = null;
  15455. this.vsmMaterialHorizontal = null;
  15456. this._node = null;
  15457. this.isShadowNode = true;
  15458. }
  15459. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow } ) {
  15460. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  15461. .and( shadowCoord.x.lessThanEqual( 1 ) )
  15462. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  15463. .and( shadowCoord.y.lessThanEqual( 1 ) )
  15464. .and( shadowCoord.z.lessThanEqual( 1 ) );
  15465. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow } );
  15466. return frustumTest.select( shadowNode, float( 1 ) );
  15467. }
  15468. setupShadowCoord( builder, shadowPosition ) {
  15469. const { shadow } = this;
  15470. const { renderer } = builder;
  15471. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  15472. let shadowCoord = shadowPosition;
  15473. let coordZ;
  15474. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  15475. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  15476. coordZ = shadowCoord.z;
  15477. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  15478. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  15479. }
  15480. } else {
  15481. const w = shadowCoord.w;
  15482. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  15483. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  15484. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  15485. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  15486. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  15487. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  15488. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  15489. }
  15490. shadowCoord = vec3(
  15491. shadowCoord.x,
  15492. shadowCoord.y.oneMinus(), // follow webgpu standards
  15493. coordZ.add( bias )
  15494. );
  15495. return shadowCoord;
  15496. }
  15497. getShadowFilterFn( type ) {
  15498. return _shadowFilterLib[ type ];
  15499. }
  15500. setupShadow( builder ) {
  15501. const { renderer } = builder;
  15502. const { light, shadow } = this;
  15503. const shadowMapType = renderer.shadowMap.type;
  15504. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  15505. depthTexture.compareFunction = LessCompare;
  15506. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  15507. shadowMap.depthTexture = depthTexture;
  15508. shadow.camera.updateProjectionMatrix();
  15509. // VSM
  15510. if ( shadowMapType === VSMShadowMap ) {
  15511. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  15512. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  15513. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  15514. const shadowPassVertical = texture( depthTexture );
  15515. const shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  15516. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  15517. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  15518. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  15519. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  15520. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical } ).context( builder.getSharedContext() );
  15521. material.name = 'VSMVertical';
  15522. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  15523. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal } ).context( builder.getSharedContext() );
  15524. material.name = 'VSMHorizontal';
  15525. }
  15526. //
  15527. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  15528. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  15529. const shadowPosition = lightShadowMatrix( light ).mul( shadowWorldPosition.add( transformedNormalWorld.mul( normalBias ) ) );
  15530. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  15531. //
  15532. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  15533. if ( filterFn === null ) {
  15534. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  15535. }
  15536. const shadowDepthTexture = ( shadowMapType === VSMShadowMap ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  15537. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow } );
  15538. const shadowColor = texture( shadowMap.texture, shadowCoord );
  15539. const shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  15540. this.shadowMap = shadowMap;
  15541. this.shadow.map = shadowMap;
  15542. return shadowOutput;
  15543. }
  15544. setup( builder ) {
  15545. if ( builder.renderer.shadowMap.enabled === false ) return;
  15546. return Fn( () => {
  15547. let node = this._node;
  15548. this.setupShadowPosition( builder );
  15549. if ( node === null ) {
  15550. this._node = node = this.setupShadow( builder );
  15551. }
  15552. if ( builder.material.shadowNode ) { // @deprecated, r171
  15553. console.warn( 'THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.' );
  15554. }
  15555. if ( builder.material.receivedShadowNode ) {
  15556. node = builder.material.receivedShadowNode( node );
  15557. }
  15558. return node;
  15559. } )();
  15560. }
  15561. renderShadow( frame ) {
  15562. const { shadow, shadowMap } = this;
  15563. const { renderer, scene } = frame;
  15564. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height );
  15565. renderer.render( scene, shadow.camera );
  15566. }
  15567. updateShadow( frame ) {
  15568. const { shadowMap, light, shadow } = this;
  15569. const { renderer, scene, camera } = frame;
  15570. const shadowType = renderer.shadowMap.type;
  15571. const depthVersion = shadowMap.depthTexture.version;
  15572. this._depthVersionCached = depthVersion;
  15573. const currentOverrideMaterial = scene.overrideMaterial;
  15574. scene.overrideMaterial = getShadowMaterial( light );
  15575. shadow.camera.layers.mask = camera.layers.mask;
  15576. const currentRenderTarget = renderer.getRenderTarget();
  15577. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  15578. const currentMRT = renderer.getMRT();
  15579. renderer.setMRT( null );
  15580. renderer.setRenderObjectFunction( ( object, scene, _camera, geometry, material, group, ...params ) => {
  15581. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  15582. object.onBeforeShadow( renderer, object, camera, shadow.camera, geometry, scene.overrideMaterial, group );
  15583. renderer.renderObject( object, scene, _camera, geometry, material, group, ...params );
  15584. object.onAfterShadow( renderer, object, camera, shadow.camera, geometry, scene.overrideMaterial, group );
  15585. }
  15586. } );
  15587. renderer.setRenderTarget( shadowMap );
  15588. this.renderShadow( frame );
  15589. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  15590. // vsm blur pass
  15591. if ( light.isPointLight !== true && shadowType === VSMShadowMap ) {
  15592. this.vsmPass( renderer );
  15593. }
  15594. renderer.setRenderTarget( currentRenderTarget );
  15595. renderer.setMRT( currentMRT );
  15596. scene.overrideMaterial = currentOverrideMaterial;
  15597. }
  15598. vsmPass( renderer ) {
  15599. const { shadow } = this;
  15600. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height );
  15601. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height );
  15602. renderer.setRenderTarget( this.vsmShadowMapVertical );
  15603. _quadMesh$1.material = this.vsmMaterialVertical;
  15604. _quadMesh$1.render( renderer );
  15605. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  15606. _quadMesh$1.material = this.vsmMaterialHorizontal;
  15607. _quadMesh$1.render( renderer );
  15608. }
  15609. dispose() {
  15610. this.shadowMap.dispose();
  15611. this.shadowMap = null;
  15612. if ( this.vsmShadowMapVertical !== null ) {
  15613. this.vsmShadowMapVertical.dispose();
  15614. this.vsmShadowMapVertical = null;
  15615. this.vsmMaterialVertical.dispose();
  15616. this.vsmMaterialVertical = null;
  15617. }
  15618. if ( this.vsmShadowMapHorizontal !== null ) {
  15619. this.vsmShadowMapHorizontal.dispose();
  15620. this.vsmShadowMapHorizontal = null;
  15621. this.vsmMaterialHorizontal.dispose();
  15622. this.vsmMaterialHorizontal = null;
  15623. }
  15624. super.dispose();
  15625. }
  15626. updateBefore( frame ) {
  15627. const { shadow } = this;
  15628. const needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  15629. if ( needsUpdate ) {
  15630. this.updateShadow( frame );
  15631. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  15632. shadow.needsUpdate = false;
  15633. }
  15634. }
  15635. }
  15636. }
  15637. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  15638. class AnalyticLightNode extends LightingNode {
  15639. static get type() {
  15640. return 'AnalyticLightNode';
  15641. }
  15642. constructor( light = null ) {
  15643. super();
  15644. this.light = light;
  15645. this.color = new Color();
  15646. this.colorNode = ( light && light.colorNode ) || uniform( this.color ).setGroup( renderGroup );
  15647. this.baseColorNode = null;
  15648. this.shadowNode = null;
  15649. this.shadowColorNode = null;
  15650. this.isAnalyticLightNode = true;
  15651. this.updateType = NodeUpdateType.FRAME;
  15652. }
  15653. /**
  15654. * Overwrites the default `customCacheKey()` implementation by including the
  15655. * light.id and light.castShadow into the cache key.
  15656. *
  15657. * @return {Number} The hash.
  15658. */
  15659. customCacheKey() {
  15660. return hash$1( this.light.id, this.light.castShadow ? 1 : 0 );
  15661. }
  15662. getHash() {
  15663. return this.light.uuid;
  15664. }
  15665. setupShadowNode() {
  15666. return shadow( this.light );
  15667. }
  15668. setupShadow( builder ) {
  15669. const { renderer } = builder;
  15670. if ( renderer.shadowMap.enabled === false ) return;
  15671. let shadowColorNode = this.shadowColorNode;
  15672. if ( shadowColorNode === null ) {
  15673. const customShadowNode = this.light.shadow.shadowNode;
  15674. let shadowNode;
  15675. if ( customShadowNode !== undefined ) {
  15676. shadowNode = nodeObject( customShadowNode );
  15677. } else {
  15678. shadowNode = this.setupShadowNode( builder );
  15679. }
  15680. this.shadowNode = shadowNode;
  15681. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  15682. this.baseColorNode = this.colorNode;
  15683. }
  15684. //
  15685. this.colorNode = shadowColorNode;
  15686. }
  15687. setup( builder ) {
  15688. this.colorNode = this.baseColorNode || this.colorNode;
  15689. if ( this.light.castShadow ) {
  15690. if ( builder.object.receiveShadow ) {
  15691. this.setupShadow( builder );
  15692. }
  15693. } else if ( this.shadowNode !== null ) {
  15694. this.shadowNode.dispose();
  15695. this.shadowNode = null;
  15696. this.shadowColorNode = null;
  15697. }
  15698. }
  15699. update( /*frame*/ ) {
  15700. const { light } = this;
  15701. this.color.copy( light.color ).multiplyScalar( light.intensity );
  15702. }
  15703. }
  15704. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( inputs ) => {
  15705. const { lightDistance, cutoffDistance, decayExponent } = inputs;
  15706. // based upon Frostbite 3 Moving to Physically-based Rendering
  15707. // page 32, equation 26: E[window1]
  15708. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  15709. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  15710. return cutoffDistance.greaterThan( 0 ).select(
  15711. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  15712. distanceFalloff
  15713. );
  15714. } ); // validated
  15715. const _clearColor$2 = /*@__PURE__*/ new Color();
  15716. // cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D
  15717. // vector suitable for 2D texture mapping. This code uses the following layout for the
  15718. // 2D texture:
  15719. //
  15720. // xzXZ
  15721. // y Y
  15722. //
  15723. // Y - Positive y direction
  15724. // y - Negative y direction
  15725. // X - Positive x direction
  15726. // x - Negative x direction
  15727. // Z - Positive z direction
  15728. // z - Negative z direction
  15729. //
  15730. // Source and test bed:
  15731. // https://gist.github.com/tschw/da10c43c467ce8afd0c4
  15732. const cubeToUV = /*@__PURE__*/ Fn( ( [ pos, texelSizeY ] ) => {
  15733. const v = pos.toVar();
  15734. // Number of texels to avoid at the edge of each square
  15735. const absV = abs( v );
  15736. // Intersect unit cube
  15737. const scaleToCube = div( 1.0, max$1( absV.x, max$1( absV.y, absV.z ) ) );
  15738. absV.mulAssign( scaleToCube );
  15739. // Apply scale to avoid seams
  15740. // two texels less per square (one texel will do for NEAREST)
  15741. v.mulAssign( scaleToCube.mul( texelSizeY.mul( 2 ).oneMinus() ) );
  15742. // Unwrap
  15743. // space: -1 ... 1 range for each square
  15744. //
  15745. // #X## dim := ( 4 , 2 )
  15746. // # # center := ( 1 , 1 )
  15747. const planar = vec2( v.xy ).toVar();
  15748. const almostATexel = texelSizeY.mul( 1.5 );
  15749. const almostOne = almostATexel.oneMinus();
  15750. If( absV.z.greaterThanEqual( almostOne ), () => {
  15751. If( v.z.greaterThan( 0.0 ), () => {
  15752. planar.x.assign( sub( 4.0, v.x ) );
  15753. } );
  15754. } ).ElseIf( absV.x.greaterThanEqual( almostOne ), () => {
  15755. const signX = sign( v.x );
  15756. planar.x.assign( v.z.mul( signX ).add( signX.mul( 2.0 ) ) );
  15757. } ).ElseIf( absV.y.greaterThanEqual( almostOne ), () => {
  15758. const signY = sign( v.y );
  15759. planar.x.assign( v.x.add( signY.mul( 2.0 ) ).add( 2.0 ) );
  15760. planar.y.assign( v.z.mul( signY ).sub( 2.0 ) );
  15761. } );
  15762. // Transform to UV space
  15763. // scale := 0.5 / dim
  15764. // translate := ( center + 0.5 ) / dim
  15765. return vec2( 0.125, 0.25 ).mul( planar ).add( vec2( 0.375, 0.75 ) ).flipY();
  15766. } ).setLayout( {
  15767. name: 'cubeToUV',
  15768. type: 'vec2',
  15769. inputs: [
  15770. { name: 'pos', type: 'vec3' },
  15771. { name: 'texelSizeY', type: 'float' }
  15772. ]
  15773. } );
  15774. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize } ) => {
  15775. return texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp );
  15776. } );
  15777. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize, shadow } ) => {
  15778. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  15779. const offset = vec2( - 1.0, 1.0 ).mul( radius ).mul( texelSize.y );
  15780. return texture( depthTexture, cubeToUV( bd3D.add( offset.xyy ), texelSize.y ) ).compare( dp )
  15781. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyy ), texelSize.y ) ).compare( dp ) )
  15782. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xyx ), texelSize.y ) ).compare( dp ) )
  15783. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyx ), texelSize.y ) ).compare( dp ) )
  15784. .add( texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp ) )
  15785. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxy ), texelSize.y ) ).compare( dp ) )
  15786. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxy ), texelSize.y ) ).compare( dp ) )
  15787. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxx ), texelSize.y ) ).compare( dp ) )
  15788. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxx ), texelSize.y ) ).compare( dp ) )
  15789. .mul( 1.0 / 9.0 );
  15790. } );
  15791. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow } ) => {
  15792. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  15793. // the vector from the light to the world-space position of the fragment.
  15794. const lightToPosition = shadowCoord.xyz.toVar();
  15795. const lightToPositionLength = lightToPosition.length();
  15796. const cameraNearLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.near );
  15797. const cameraFarLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.far );
  15798. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  15799. const mapSize = uniform( shadow.mapSize ).setGroup( renderGroup );
  15800. const result = float( 1.0 ).toVar();
  15801. If( lightToPositionLength.sub( cameraFarLocal ).lessThanEqual( 0.0 ).and( lightToPositionLength.sub( cameraNearLocal ).greaterThanEqual( 0.0 ) ), () => {
  15802. // dp = normalized distance from light to fragment position
  15803. const dp = lightToPositionLength.sub( cameraNearLocal ).div( cameraFarLocal.sub( cameraNearLocal ) ).toVar(); // need to clamp?
  15804. dp.addAssign( bias );
  15805. // bd3D = base direction 3D
  15806. const bd3D = lightToPosition.normalize();
  15807. const texelSize = vec2( 1.0 ).div( mapSize.mul( vec2( 4.0, 2.0 ) ) );
  15808. // percentage-closer filtering
  15809. result.assign( filterFn( { depthTexture, bd3D, dp, texelSize, shadow } ) );
  15810. } );
  15811. return result;
  15812. } );
  15813. const _viewport = /*@__PURE__*/ new Vector4();
  15814. const _viewportSize = /*@__PURE__*/ new Vector2();
  15815. const _shadowMapSize = /*@__PURE__*/ new Vector2();
  15816. //
  15817. class PointShadowNode extends ShadowNode {
  15818. static get type() {
  15819. return 'PointShadowNode';
  15820. }
  15821. constructor( light, shadow = null ) {
  15822. super( light, shadow );
  15823. }
  15824. getShadowFilterFn( type ) {
  15825. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  15826. }
  15827. setupShadowCoord( builder, shadowPosition ) {
  15828. return shadowPosition;
  15829. }
  15830. setupShadowFilter( builder, { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } ) {
  15831. return pointShadowFilter( { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } );
  15832. }
  15833. renderShadow( frame ) {
  15834. const { shadow, shadowMap, light } = this;
  15835. const { renderer, scene } = frame;
  15836. const shadowFrameExtents = shadow.getFrameExtents();
  15837. _shadowMapSize.copy( shadow.mapSize );
  15838. _shadowMapSize.multiply( shadowFrameExtents );
  15839. shadowMap.setSize( _shadowMapSize.width, _shadowMapSize.height );
  15840. _viewportSize.copy( shadow.mapSize );
  15841. //
  15842. const previousAutoClear = renderer.autoClear;
  15843. const previousClearColor = renderer.getClearColor( _clearColor$2 );
  15844. const previousClearAlpha = renderer.getClearAlpha();
  15845. renderer.autoClear = false;
  15846. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  15847. renderer.clear();
  15848. const viewportCount = shadow.getViewportCount();
  15849. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  15850. const viewport = shadow.getViewport( vp );
  15851. const x = _viewportSize.x * viewport.x;
  15852. const y = _shadowMapSize.y - _viewportSize.y - ( _viewportSize.y * viewport.y );
  15853. _viewport.set(
  15854. x,
  15855. y,
  15856. _viewportSize.x * viewport.z,
  15857. _viewportSize.y * viewport.w
  15858. );
  15859. shadowMap.viewport.copy( _viewport );
  15860. shadow.updateMatrices( light, vp );
  15861. renderer.render( scene, shadow.camera );
  15862. }
  15863. //
  15864. renderer.autoClear = previousAutoClear;
  15865. renderer.setClearColor( previousClearColor, previousClearAlpha );
  15866. }
  15867. }
  15868. const pointShadow = ( light, shadow ) => nodeObject( new PointShadowNode( light, shadow ) );
  15869. const directPointLight = Fn( ( { color, lightViewPosition, cutoffDistance, decayExponent }, builder ) => {
  15870. const lightingModel = builder.context.lightingModel;
  15871. const lVector = lightViewPosition.sub( positionView ); // @TODO: Add it into LightNode
  15872. const lightDirection = lVector.normalize();
  15873. const lightDistance = lVector.length();
  15874. const lightAttenuation = getDistanceAttenuation( {
  15875. lightDistance,
  15876. cutoffDistance,
  15877. decayExponent
  15878. } );
  15879. const lightColor = color.mul( lightAttenuation );
  15880. const reflectedLight = builder.context.reflectedLight;
  15881. lightingModel.direct( {
  15882. lightDirection,
  15883. lightColor,
  15884. reflectedLight
  15885. }, builder.stack, builder );
  15886. } );
  15887. class PointLightNode extends AnalyticLightNode {
  15888. static get type() {
  15889. return 'PointLightNode';
  15890. }
  15891. constructor( light = null ) {
  15892. super( light );
  15893. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  15894. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  15895. }
  15896. update( frame ) {
  15897. const { light } = this;
  15898. super.update( frame );
  15899. this.cutoffDistanceNode.value = light.distance;
  15900. this.decayExponentNode.value = light.decay;
  15901. }
  15902. setupShadowNode() {
  15903. return pointShadow( this.light );
  15904. }
  15905. setup( builder ) {
  15906. super.setup( builder );
  15907. directPointLight( {
  15908. color: this.colorNode,
  15909. lightViewPosition: lightViewPosition( this.light ),
  15910. cutoffDistance: this.cutoffDistanceNode,
  15911. decayExponent: this.decayExponentNode
  15912. } ).append();
  15913. }
  15914. }
  15915. /** @module Procedural **/
  15916. /**
  15917. * Creates a 2x2 checkerboard pattern that can be used as procedural texture data.
  15918. *
  15919. * @method
  15920. * @param {Node<vec2>} uv - The uv coordinates.
  15921. * @return {Node<float>} The result data.
  15922. */
  15923. const checker = /*@__PURE__*/ Fn( ( [ coord = uv() ] ) => {
  15924. const uv = coord.mul( 2.0 );
  15925. const cx = uv.x.floor();
  15926. const cy = uv.y.floor();
  15927. const result = cx.add( cy ).mod( 2.0 );
  15928. return result.sign();
  15929. } );
  15930. // Three.js Transpiler
  15931. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  15932. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  15933. const f = float( f_immutable ).toVar();
  15934. const t = float( t_immutable ).toVar();
  15935. const b = bool( b_immutable ).toVar();
  15936. return select( b, t, f );
  15937. } ).setLayout( {
  15938. name: 'mx_select',
  15939. type: 'float',
  15940. inputs: [
  15941. { name: 'b', type: 'bool' },
  15942. { name: 't', type: 'float' },
  15943. { name: 'f', type: 'float' }
  15944. ]
  15945. } );
  15946. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  15947. const b = bool( b_immutable ).toVar();
  15948. const val = float( val_immutable ).toVar();
  15949. return select( b, val.negate(), val );
  15950. } ).setLayout( {
  15951. name: 'mx_negate_if',
  15952. type: 'float',
  15953. inputs: [
  15954. { name: 'val', type: 'float' },
  15955. { name: 'b', type: 'bool' }
  15956. ]
  15957. } );
  15958. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  15959. const x = float( x_immutable ).toVar();
  15960. return int( floor( x ) );
  15961. } ).setLayout( {
  15962. name: 'mx_floor',
  15963. type: 'int',
  15964. inputs: [
  15965. { name: 'x', type: 'float' }
  15966. ]
  15967. } );
  15968. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  15969. const x = float( x_immutable ).toVar();
  15970. i.assign( mx_floor( x ) );
  15971. return x.sub( float( i ) );
  15972. } );
  15973. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  15974. const t = float( t_immutable ).toVar();
  15975. const s = float( s_immutable ).toVar();
  15976. const v3 = float( v3_immutable ).toVar();
  15977. const v2 = float( v2_immutable ).toVar();
  15978. const v1 = float( v1_immutable ).toVar();
  15979. const v0 = float( v0_immutable ).toVar();
  15980. const s1 = float( sub( 1.0, s ) ).toVar();
  15981. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  15982. } ).setLayout( {
  15983. name: 'mx_bilerp_0',
  15984. type: 'float',
  15985. inputs: [
  15986. { name: 'v0', type: 'float' },
  15987. { name: 'v1', type: 'float' },
  15988. { name: 'v2', type: 'float' },
  15989. { name: 'v3', type: 'float' },
  15990. { name: 's', type: 'float' },
  15991. { name: 't', type: 'float' }
  15992. ]
  15993. } );
  15994. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  15995. const t = float( t_immutable ).toVar();
  15996. const s = float( s_immutable ).toVar();
  15997. const v3 = vec3( v3_immutable ).toVar();
  15998. const v2 = vec3( v2_immutable ).toVar();
  15999. const v1 = vec3( v1_immutable ).toVar();
  16000. const v0 = vec3( v0_immutable ).toVar();
  16001. const s1 = float( sub( 1.0, s ) ).toVar();
  16002. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  16003. } ).setLayout( {
  16004. name: 'mx_bilerp_1',
  16005. type: 'vec3',
  16006. inputs: [
  16007. { name: 'v0', type: 'vec3' },
  16008. { name: 'v1', type: 'vec3' },
  16009. { name: 'v2', type: 'vec3' },
  16010. { name: 'v3', type: 'vec3' },
  16011. { name: 's', type: 'float' },
  16012. { name: 't', type: 'float' }
  16013. ]
  16014. } );
  16015. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  16016. 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 ] ) => {
  16017. const r = float( r_immutable ).toVar();
  16018. const t = float( t_immutable ).toVar();
  16019. const s = float( s_immutable ).toVar();
  16020. const v7 = float( v7_immutable ).toVar();
  16021. const v6 = float( v6_immutable ).toVar();
  16022. const v5 = float( v5_immutable ).toVar();
  16023. const v4 = float( v4_immutable ).toVar();
  16024. const v3 = float( v3_immutable ).toVar();
  16025. const v2 = float( v2_immutable ).toVar();
  16026. const v1 = float( v1_immutable ).toVar();
  16027. const v0 = float( v0_immutable ).toVar();
  16028. const s1 = float( sub( 1.0, s ) ).toVar();
  16029. const t1 = float( sub( 1.0, t ) ).toVar();
  16030. const r1 = float( sub( 1.0, r ) ).toVar();
  16031. 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 ) ) ) ) ) );
  16032. } ).setLayout( {
  16033. name: 'mx_trilerp_0',
  16034. type: 'float',
  16035. inputs: [
  16036. { name: 'v0', type: 'float' },
  16037. { name: 'v1', type: 'float' },
  16038. { name: 'v2', type: 'float' },
  16039. { name: 'v3', type: 'float' },
  16040. { name: 'v4', type: 'float' },
  16041. { name: 'v5', type: 'float' },
  16042. { name: 'v6', type: 'float' },
  16043. { name: 'v7', type: 'float' },
  16044. { name: 's', type: 'float' },
  16045. { name: 't', type: 'float' },
  16046. { name: 'r', type: 'float' }
  16047. ]
  16048. } );
  16049. 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 ] ) => {
  16050. const r = float( r_immutable ).toVar();
  16051. const t = float( t_immutable ).toVar();
  16052. const s = float( s_immutable ).toVar();
  16053. const v7 = vec3( v7_immutable ).toVar();
  16054. const v6 = vec3( v6_immutable ).toVar();
  16055. const v5 = vec3( v5_immutable ).toVar();
  16056. const v4 = vec3( v4_immutable ).toVar();
  16057. const v3 = vec3( v3_immutable ).toVar();
  16058. const v2 = vec3( v2_immutable ).toVar();
  16059. const v1 = vec3( v1_immutable ).toVar();
  16060. const v0 = vec3( v0_immutable ).toVar();
  16061. const s1 = float( sub( 1.0, s ) ).toVar();
  16062. const t1 = float( sub( 1.0, t ) ).toVar();
  16063. const r1 = float( sub( 1.0, r ) ).toVar();
  16064. 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 ) ) ) ) ) );
  16065. } ).setLayout( {
  16066. name: 'mx_trilerp_1',
  16067. type: 'vec3',
  16068. inputs: [
  16069. { name: 'v0', type: 'vec3' },
  16070. { name: 'v1', type: 'vec3' },
  16071. { name: 'v2', type: 'vec3' },
  16072. { name: 'v3', type: 'vec3' },
  16073. { name: 'v4', type: 'vec3' },
  16074. { name: 'v5', type: 'vec3' },
  16075. { name: 'v6', type: 'vec3' },
  16076. { name: 'v7', type: 'vec3' },
  16077. { name: 's', type: 'float' },
  16078. { name: 't', type: 'float' },
  16079. { name: 'r', type: 'float' }
  16080. ]
  16081. } );
  16082. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  16083. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  16084. const y = float( y_immutable ).toVar();
  16085. const x = float( x_immutable ).toVar();
  16086. const hash = uint( hash_immutable ).toVar();
  16087. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  16088. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  16089. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  16090. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  16091. } ).setLayout( {
  16092. name: 'mx_gradient_float_0',
  16093. type: 'float',
  16094. inputs: [
  16095. { name: 'hash', type: 'uint' },
  16096. { name: 'x', type: 'float' },
  16097. { name: 'y', type: 'float' }
  16098. ]
  16099. } );
  16100. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  16101. const z = float( z_immutable ).toVar();
  16102. const y = float( y_immutable ).toVar();
  16103. const x = float( x_immutable ).toVar();
  16104. const hash = uint( hash_immutable ).toVar();
  16105. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  16106. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  16107. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  16108. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  16109. } ).setLayout( {
  16110. name: 'mx_gradient_float_1',
  16111. type: 'float',
  16112. inputs: [
  16113. { name: 'hash', type: 'uint' },
  16114. { name: 'x', type: 'float' },
  16115. { name: 'y', type: 'float' },
  16116. { name: 'z', type: 'float' }
  16117. ]
  16118. } );
  16119. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  16120. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  16121. const y = float( y_immutable ).toVar();
  16122. const x = float( x_immutable ).toVar();
  16123. const hash = uvec3( hash_immutable ).toVar();
  16124. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  16125. } ).setLayout( {
  16126. name: 'mx_gradient_vec3_0',
  16127. type: 'vec3',
  16128. inputs: [
  16129. { name: 'hash', type: 'uvec3' },
  16130. { name: 'x', type: 'float' },
  16131. { name: 'y', type: 'float' }
  16132. ]
  16133. } );
  16134. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  16135. const z = float( z_immutable ).toVar();
  16136. const y = float( y_immutable ).toVar();
  16137. const x = float( x_immutable ).toVar();
  16138. const hash = uvec3( hash_immutable ).toVar();
  16139. 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 ) );
  16140. } ).setLayout( {
  16141. name: 'mx_gradient_vec3_1',
  16142. type: 'vec3',
  16143. inputs: [
  16144. { name: 'hash', type: 'uvec3' },
  16145. { name: 'x', type: 'float' },
  16146. { name: 'y', type: 'float' },
  16147. { name: 'z', type: 'float' }
  16148. ]
  16149. } );
  16150. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  16151. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  16152. const v = float( v_immutable ).toVar();
  16153. return mul( 0.6616, v );
  16154. } ).setLayout( {
  16155. name: 'mx_gradient_scale2d_0',
  16156. type: 'float',
  16157. inputs: [
  16158. { name: 'v', type: 'float' }
  16159. ]
  16160. } );
  16161. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  16162. const v = float( v_immutable ).toVar();
  16163. return mul( 0.9820, v );
  16164. } ).setLayout( {
  16165. name: 'mx_gradient_scale3d_0',
  16166. type: 'float',
  16167. inputs: [
  16168. { name: 'v', type: 'float' }
  16169. ]
  16170. } );
  16171. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  16172. const v = vec3( v_immutable ).toVar();
  16173. return mul( 0.6616, v );
  16174. } ).setLayout( {
  16175. name: 'mx_gradient_scale2d_1',
  16176. type: 'vec3',
  16177. inputs: [
  16178. { name: 'v', type: 'vec3' }
  16179. ]
  16180. } );
  16181. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  16182. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  16183. const v = vec3( v_immutable ).toVar();
  16184. return mul( 0.9820, v );
  16185. } ).setLayout( {
  16186. name: 'mx_gradient_scale3d_1',
  16187. type: 'vec3',
  16188. inputs: [
  16189. { name: 'v', type: 'vec3' }
  16190. ]
  16191. } );
  16192. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  16193. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  16194. const k = int( k_immutable ).toVar();
  16195. const x = uint( x_immutable ).toVar();
  16196. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  16197. } ).setLayout( {
  16198. name: 'mx_rotl32',
  16199. type: 'uint',
  16200. inputs: [
  16201. { name: 'x', type: 'uint' },
  16202. { name: 'k', type: 'int' }
  16203. ]
  16204. } );
  16205. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  16206. a.subAssign( c );
  16207. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  16208. c.addAssign( b );
  16209. b.subAssign( a );
  16210. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  16211. a.addAssign( c );
  16212. c.subAssign( b );
  16213. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  16214. b.addAssign( a );
  16215. a.subAssign( c );
  16216. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  16217. c.addAssign( b );
  16218. b.subAssign( a );
  16219. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  16220. a.addAssign( c );
  16221. c.subAssign( b );
  16222. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  16223. b.addAssign( a );
  16224. } );
  16225. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  16226. const c = uint( c_immutable ).toVar();
  16227. const b = uint( b_immutable ).toVar();
  16228. const a = uint( a_immutable ).toVar();
  16229. c.bitXorAssign( b );
  16230. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  16231. a.bitXorAssign( c );
  16232. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  16233. b.bitXorAssign( a );
  16234. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  16235. c.bitXorAssign( b );
  16236. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  16237. a.bitXorAssign( c );
  16238. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  16239. b.bitXorAssign( a );
  16240. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  16241. c.bitXorAssign( b );
  16242. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  16243. return c;
  16244. } ).setLayout( {
  16245. name: 'mx_bjfinal',
  16246. type: 'uint',
  16247. inputs: [
  16248. { name: 'a', type: 'uint' },
  16249. { name: 'b', type: 'uint' },
  16250. { name: 'c', type: 'uint' }
  16251. ]
  16252. } );
  16253. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  16254. const bits = uint( bits_immutable ).toVar();
  16255. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  16256. } ).setLayout( {
  16257. name: 'mx_bits_to_01',
  16258. type: 'float',
  16259. inputs: [
  16260. { name: 'bits', type: 'uint' }
  16261. ]
  16262. } );
  16263. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  16264. const t = float( t_immutable ).toVar();
  16265. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  16266. } ).setLayout( {
  16267. name: 'mx_fade',
  16268. type: 'float',
  16269. inputs: [
  16270. { name: 't', type: 'float' }
  16271. ]
  16272. } );
  16273. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  16274. const x = int( x_immutable ).toVar();
  16275. const len = uint( uint( 1 ) ).toVar();
  16276. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  16277. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  16278. } ).setLayout( {
  16279. name: 'mx_hash_int_0',
  16280. type: 'uint',
  16281. inputs: [
  16282. { name: 'x', type: 'int' }
  16283. ]
  16284. } );
  16285. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  16286. const y = int( y_immutable ).toVar();
  16287. const x = int( x_immutable ).toVar();
  16288. const len = uint( uint( 2 ) ).toVar();
  16289. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  16290. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  16291. a.addAssign( uint( x ) );
  16292. b.addAssign( uint( y ) );
  16293. return mx_bjfinal( a, b, c );
  16294. } ).setLayout( {
  16295. name: 'mx_hash_int_1',
  16296. type: 'uint',
  16297. inputs: [
  16298. { name: 'x', type: 'int' },
  16299. { name: 'y', type: 'int' }
  16300. ]
  16301. } );
  16302. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  16303. const z = int( z_immutable ).toVar();
  16304. const y = int( y_immutable ).toVar();
  16305. const x = int( x_immutable ).toVar();
  16306. const len = uint( uint( 3 ) ).toVar();
  16307. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  16308. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  16309. a.addAssign( uint( x ) );
  16310. b.addAssign( uint( y ) );
  16311. c.addAssign( uint( z ) );
  16312. return mx_bjfinal( a, b, c );
  16313. } ).setLayout( {
  16314. name: 'mx_hash_int_2',
  16315. type: 'uint',
  16316. inputs: [
  16317. { name: 'x', type: 'int' },
  16318. { name: 'y', type: 'int' },
  16319. { name: 'z', type: 'int' }
  16320. ]
  16321. } );
  16322. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  16323. const xx = int( xx_immutable ).toVar();
  16324. const z = int( z_immutable ).toVar();
  16325. const y = int( y_immutable ).toVar();
  16326. const x = int( x_immutable ).toVar();
  16327. const len = uint( uint( 4 ) ).toVar();
  16328. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  16329. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  16330. a.addAssign( uint( x ) );
  16331. b.addAssign( uint( y ) );
  16332. c.addAssign( uint( z ) );
  16333. mx_bjmix( a, b, c );
  16334. a.addAssign( uint( xx ) );
  16335. return mx_bjfinal( a, b, c );
  16336. } ).setLayout( {
  16337. name: 'mx_hash_int_3',
  16338. type: 'uint',
  16339. inputs: [
  16340. { name: 'x', type: 'int' },
  16341. { name: 'y', type: 'int' },
  16342. { name: 'z', type: 'int' },
  16343. { name: 'xx', type: 'int' }
  16344. ]
  16345. } );
  16346. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  16347. const yy = int( yy_immutable ).toVar();
  16348. const xx = int( xx_immutable ).toVar();
  16349. const z = int( z_immutable ).toVar();
  16350. const y = int( y_immutable ).toVar();
  16351. const x = int( x_immutable ).toVar();
  16352. const len = uint( uint( 5 ) ).toVar();
  16353. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  16354. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  16355. a.addAssign( uint( x ) );
  16356. b.addAssign( uint( y ) );
  16357. c.addAssign( uint( z ) );
  16358. mx_bjmix( a, b, c );
  16359. a.addAssign( uint( xx ) );
  16360. b.addAssign( uint( yy ) );
  16361. return mx_bjfinal( a, b, c );
  16362. } ).setLayout( {
  16363. name: 'mx_hash_int_4',
  16364. type: 'uint',
  16365. inputs: [
  16366. { name: 'x', type: 'int' },
  16367. { name: 'y', type: 'int' },
  16368. { name: 'z', type: 'int' },
  16369. { name: 'xx', type: 'int' },
  16370. { name: 'yy', type: 'int' }
  16371. ]
  16372. } );
  16373. 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 ] );
  16374. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  16375. const y = int( y_immutable ).toVar();
  16376. const x = int( x_immutable ).toVar();
  16377. const h = uint( mx_hash_int( x, y ) ).toVar();
  16378. const result = uvec3().toVar();
  16379. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  16380. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  16381. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  16382. return result;
  16383. } ).setLayout( {
  16384. name: 'mx_hash_vec3_0',
  16385. type: 'uvec3',
  16386. inputs: [
  16387. { name: 'x', type: 'int' },
  16388. { name: 'y', type: 'int' }
  16389. ]
  16390. } );
  16391. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  16392. const z = int( z_immutable ).toVar();
  16393. const y = int( y_immutable ).toVar();
  16394. const x = int( x_immutable ).toVar();
  16395. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  16396. const result = uvec3().toVar();
  16397. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  16398. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  16399. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  16400. return result;
  16401. } ).setLayout( {
  16402. name: 'mx_hash_vec3_1',
  16403. type: 'uvec3',
  16404. inputs: [
  16405. { name: 'x', type: 'int' },
  16406. { name: 'y', type: 'int' },
  16407. { name: 'z', type: 'int' }
  16408. ]
  16409. } );
  16410. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  16411. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  16412. const p = vec2( p_immutable ).toVar();
  16413. const X = int().toVar(), Y = int().toVar();
  16414. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  16415. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  16416. const u = float( mx_fade( fx ) ).toVar();
  16417. const v = float( mx_fade( fy ) ).toVar();
  16418. 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();
  16419. return mx_gradient_scale2d( result );
  16420. } ).setLayout( {
  16421. name: 'mx_perlin_noise_float_0',
  16422. type: 'float',
  16423. inputs: [
  16424. { name: 'p', type: 'vec2' }
  16425. ]
  16426. } );
  16427. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  16428. const p = vec3( p_immutable ).toVar();
  16429. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  16430. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  16431. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  16432. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  16433. const u = float( mx_fade( fx ) ).toVar();
  16434. const v = float( mx_fade( fy ) ).toVar();
  16435. const w = float( mx_fade( fz ) ).toVar();
  16436. 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();
  16437. return mx_gradient_scale3d( result );
  16438. } ).setLayout( {
  16439. name: 'mx_perlin_noise_float_1',
  16440. type: 'float',
  16441. inputs: [
  16442. { name: 'p', type: 'vec3' }
  16443. ]
  16444. } );
  16445. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  16446. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  16447. const p = vec2( p_immutable ).toVar();
  16448. const X = int().toVar(), Y = int().toVar();
  16449. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  16450. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  16451. const u = float( mx_fade( fx ) ).toVar();
  16452. const v = float( mx_fade( fy ) ).toVar();
  16453. 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();
  16454. return mx_gradient_scale2d( result );
  16455. } ).setLayout( {
  16456. name: 'mx_perlin_noise_vec3_0',
  16457. type: 'vec3',
  16458. inputs: [
  16459. { name: 'p', type: 'vec2' }
  16460. ]
  16461. } );
  16462. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  16463. const p = vec3( p_immutable ).toVar();
  16464. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  16465. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  16466. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  16467. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  16468. const u = float( mx_fade( fx ) ).toVar();
  16469. const v = float( mx_fade( fy ) ).toVar();
  16470. const w = float( mx_fade( fz ) ).toVar();
  16471. 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();
  16472. return mx_gradient_scale3d( result );
  16473. } ).setLayout( {
  16474. name: 'mx_perlin_noise_vec3_1',
  16475. type: 'vec3',
  16476. inputs: [
  16477. { name: 'p', type: 'vec3' }
  16478. ]
  16479. } );
  16480. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  16481. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  16482. const p = float( p_immutable ).toVar();
  16483. const ix = int( mx_floor( p ) ).toVar();
  16484. return mx_bits_to_01( mx_hash_int( ix ) );
  16485. } ).setLayout( {
  16486. name: 'mx_cell_noise_float_0',
  16487. type: 'float',
  16488. inputs: [
  16489. { name: 'p', type: 'float' }
  16490. ]
  16491. } );
  16492. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  16493. const p = vec2( p_immutable ).toVar();
  16494. const ix = int( mx_floor( p.x ) ).toVar();
  16495. const iy = int( mx_floor( p.y ) ).toVar();
  16496. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  16497. } ).setLayout( {
  16498. name: 'mx_cell_noise_float_1',
  16499. type: 'float',
  16500. inputs: [
  16501. { name: 'p', type: 'vec2' }
  16502. ]
  16503. } );
  16504. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  16505. const p = vec3( p_immutable ).toVar();
  16506. const ix = int( mx_floor( p.x ) ).toVar();
  16507. const iy = int( mx_floor( p.y ) ).toVar();
  16508. const iz = int( mx_floor( p.z ) ).toVar();
  16509. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  16510. } ).setLayout( {
  16511. name: 'mx_cell_noise_float_2',
  16512. type: 'float',
  16513. inputs: [
  16514. { name: 'p', type: 'vec3' }
  16515. ]
  16516. } );
  16517. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  16518. const p = vec4( p_immutable ).toVar();
  16519. const ix = int( mx_floor( p.x ) ).toVar();
  16520. const iy = int( mx_floor( p.y ) ).toVar();
  16521. const iz = int( mx_floor( p.z ) ).toVar();
  16522. const iw = int( mx_floor( p.w ) ).toVar();
  16523. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  16524. } ).setLayout( {
  16525. name: 'mx_cell_noise_float_3',
  16526. type: 'float',
  16527. inputs: [
  16528. { name: 'p', type: 'vec4' }
  16529. ]
  16530. } );
  16531. 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 ] );
  16532. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  16533. const p = float( p_immutable ).toVar();
  16534. const ix = int( mx_floor( p ) ).toVar();
  16535. 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 ) ) ) );
  16536. } ).setLayout( {
  16537. name: 'mx_cell_noise_vec3_0',
  16538. type: 'vec3',
  16539. inputs: [
  16540. { name: 'p', type: 'float' }
  16541. ]
  16542. } );
  16543. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  16544. const p = vec2( p_immutable ).toVar();
  16545. const ix = int( mx_floor( p.x ) ).toVar();
  16546. const iy = int( mx_floor( p.y ) ).toVar();
  16547. 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 ) ) ) );
  16548. } ).setLayout( {
  16549. name: 'mx_cell_noise_vec3_1',
  16550. type: 'vec3',
  16551. inputs: [
  16552. { name: 'p', type: 'vec2' }
  16553. ]
  16554. } );
  16555. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  16556. const p = vec3( p_immutable ).toVar();
  16557. const ix = int( mx_floor( p.x ) ).toVar();
  16558. const iy = int( mx_floor( p.y ) ).toVar();
  16559. const iz = int( mx_floor( p.z ) ).toVar();
  16560. 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 ) ) ) );
  16561. } ).setLayout( {
  16562. name: 'mx_cell_noise_vec3_2',
  16563. type: 'vec3',
  16564. inputs: [
  16565. { name: 'p', type: 'vec3' }
  16566. ]
  16567. } );
  16568. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  16569. const p = vec4( p_immutable ).toVar();
  16570. const ix = int( mx_floor( p.x ) ).toVar();
  16571. const iy = int( mx_floor( p.y ) ).toVar();
  16572. const iz = int( mx_floor( p.z ) ).toVar();
  16573. const iw = int( mx_floor( p.w ) ).toVar();
  16574. 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 ) ) ) );
  16575. } ).setLayout( {
  16576. name: 'mx_cell_noise_vec3_3',
  16577. type: 'vec3',
  16578. inputs: [
  16579. { name: 'p', type: 'vec4' }
  16580. ]
  16581. } );
  16582. 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 ] );
  16583. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  16584. const diminish = float( diminish_immutable ).toVar();
  16585. const lacunarity = float( lacunarity_immutable ).toVar();
  16586. const octaves = int( octaves_immutable ).toVar();
  16587. const p = vec3( p_immutable ).toVar();
  16588. const result = float( 0.0 ).toVar();
  16589. const amplitude = float( 1.0 ).toVar();
  16590. Loop( octaves, () => {
  16591. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  16592. amplitude.mulAssign( diminish );
  16593. p.mulAssign( lacunarity );
  16594. } );
  16595. return result;
  16596. } ).setLayout( {
  16597. name: 'mx_fractal_noise_float',
  16598. type: 'float',
  16599. inputs: [
  16600. { name: 'p', type: 'vec3' },
  16601. { name: 'octaves', type: 'int' },
  16602. { name: 'lacunarity', type: 'float' },
  16603. { name: 'diminish', type: 'float' }
  16604. ]
  16605. } );
  16606. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  16607. const diminish = float( diminish_immutable ).toVar();
  16608. const lacunarity = float( lacunarity_immutable ).toVar();
  16609. const octaves = int( octaves_immutable ).toVar();
  16610. const p = vec3( p_immutable ).toVar();
  16611. const result = vec3( 0.0 ).toVar();
  16612. const amplitude = float( 1.0 ).toVar();
  16613. Loop( octaves, () => {
  16614. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  16615. amplitude.mulAssign( diminish );
  16616. p.mulAssign( lacunarity );
  16617. } );
  16618. return result;
  16619. } ).setLayout( {
  16620. name: 'mx_fractal_noise_vec3',
  16621. type: 'vec3',
  16622. inputs: [
  16623. { name: 'p', type: 'vec3' },
  16624. { name: 'octaves', type: 'int' },
  16625. { name: 'lacunarity', type: 'float' },
  16626. { name: 'diminish', type: 'float' }
  16627. ]
  16628. } );
  16629. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  16630. const diminish = float( diminish_immutable ).toVar();
  16631. const lacunarity = float( lacunarity_immutable ).toVar();
  16632. const octaves = int( octaves_immutable ).toVar();
  16633. const p = vec3( p_immutable ).toVar();
  16634. 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 ) );
  16635. } ).setLayout( {
  16636. name: 'mx_fractal_noise_vec2',
  16637. type: 'vec2',
  16638. inputs: [
  16639. { name: 'p', type: 'vec3' },
  16640. { name: 'octaves', type: 'int' },
  16641. { name: 'lacunarity', type: 'float' },
  16642. { name: 'diminish', type: 'float' }
  16643. ]
  16644. } );
  16645. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  16646. const diminish = float( diminish_immutable ).toVar();
  16647. const lacunarity = float( lacunarity_immutable ).toVar();
  16648. const octaves = int( octaves_immutable ).toVar();
  16649. const p = vec3( p_immutable ).toVar();
  16650. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  16651. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  16652. return vec4( c, f );
  16653. } ).setLayout( {
  16654. name: 'mx_fractal_noise_vec4',
  16655. type: 'vec4',
  16656. inputs: [
  16657. { name: 'p', type: 'vec3' },
  16658. { name: 'octaves', type: 'int' },
  16659. { name: 'lacunarity', type: 'float' },
  16660. { name: 'diminish', type: 'float' }
  16661. ]
  16662. } );
  16663. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  16664. const metric = int( metric_immutable ).toVar();
  16665. const jitter = float( jitter_immutable ).toVar();
  16666. const yoff = int( yoff_immutable ).toVar();
  16667. const xoff = int( xoff_immutable ).toVar();
  16668. const y = int( y_immutable ).toVar();
  16669. const x = int( x_immutable ).toVar();
  16670. const p = vec2( p_immutable ).toVar();
  16671. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  16672. const off = vec2( tmp.x, tmp.y ).toVar();
  16673. off.subAssign( 0.5 );
  16674. off.mulAssign( jitter );
  16675. off.addAssign( 0.5 );
  16676. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  16677. const diff = vec2( cellpos.sub( p ) ).toVar();
  16678. If( metric.equal( int( 2 ) ), () => {
  16679. return abs( diff.x ).add( abs( diff.y ) );
  16680. } );
  16681. If( metric.equal( int( 3 ) ), () => {
  16682. return max$1( abs( diff.x ), abs( diff.y ) );
  16683. } );
  16684. return dot( diff, diff );
  16685. } ).setLayout( {
  16686. name: 'mx_worley_distance_0',
  16687. type: 'float',
  16688. inputs: [
  16689. { name: 'p', type: 'vec2' },
  16690. { name: 'x', type: 'int' },
  16691. { name: 'y', type: 'int' },
  16692. { name: 'xoff', type: 'int' },
  16693. { name: 'yoff', type: 'int' },
  16694. { name: 'jitter', type: 'float' },
  16695. { name: 'metric', type: 'int' }
  16696. ]
  16697. } );
  16698. 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 ] ) => {
  16699. const metric = int( metric_immutable ).toVar();
  16700. const jitter = float( jitter_immutable ).toVar();
  16701. const zoff = int( zoff_immutable ).toVar();
  16702. const yoff = int( yoff_immutable ).toVar();
  16703. const xoff = int( xoff_immutable ).toVar();
  16704. const z = int( z_immutable ).toVar();
  16705. const y = int( y_immutable ).toVar();
  16706. const x = int( x_immutable ).toVar();
  16707. const p = vec3( p_immutable ).toVar();
  16708. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  16709. off.subAssign( 0.5 );
  16710. off.mulAssign( jitter );
  16711. off.addAssign( 0.5 );
  16712. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  16713. const diff = vec3( cellpos.sub( p ) ).toVar();
  16714. If( metric.equal( int( 2 ) ), () => {
  16715. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  16716. } );
  16717. If( metric.equal( int( 3 ) ), () => {
  16718. return max$1( max$1( abs( diff.x ), abs( diff.y ) ), abs( diff.z ) );
  16719. } );
  16720. return dot( diff, diff );
  16721. } ).setLayout( {
  16722. name: 'mx_worley_distance_1',
  16723. type: 'float',
  16724. inputs: [
  16725. { name: 'p', type: 'vec3' },
  16726. { name: 'x', type: 'int' },
  16727. { name: 'y', type: 'int' },
  16728. { name: 'z', type: 'int' },
  16729. { name: 'xoff', type: 'int' },
  16730. { name: 'yoff', type: 'int' },
  16731. { name: 'zoff', type: 'int' },
  16732. { name: 'jitter', type: 'float' },
  16733. { name: 'metric', type: 'int' }
  16734. ]
  16735. } );
  16736. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  16737. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  16738. const metric = int( metric_immutable ).toVar();
  16739. const jitter = float( jitter_immutable ).toVar();
  16740. const p = vec2( p_immutable ).toVar();
  16741. const X = int().toVar(), Y = int().toVar();
  16742. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  16743. const sqdist = float( 1e6 ).toVar();
  16744. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  16745. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  16746. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  16747. sqdist.assign( min$1( sqdist, dist ) );
  16748. } );
  16749. } );
  16750. If( metric.equal( int( 0 ) ), () => {
  16751. sqdist.assign( sqrt( sqdist ) );
  16752. } );
  16753. return sqdist;
  16754. } ).setLayout( {
  16755. name: 'mx_worley_noise_float_0',
  16756. type: 'float',
  16757. inputs: [
  16758. { name: 'p', type: 'vec2' },
  16759. { name: 'jitter', type: 'float' },
  16760. { name: 'metric', type: 'int' }
  16761. ]
  16762. } );
  16763. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  16764. const metric = int( metric_immutable ).toVar();
  16765. const jitter = float( jitter_immutable ).toVar();
  16766. const p = vec2( p_immutable ).toVar();
  16767. const X = int().toVar(), Y = int().toVar();
  16768. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  16769. const sqdist = vec2( 1e6, 1e6 ).toVar();
  16770. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  16771. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  16772. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  16773. If( dist.lessThan( sqdist.x ), () => {
  16774. sqdist.y.assign( sqdist.x );
  16775. sqdist.x.assign( dist );
  16776. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  16777. sqdist.y.assign( dist );
  16778. } );
  16779. } );
  16780. } );
  16781. If( metric.equal( int( 0 ) ), () => {
  16782. sqdist.assign( sqrt( sqdist ) );
  16783. } );
  16784. return sqdist;
  16785. } ).setLayout( {
  16786. name: 'mx_worley_noise_vec2_0',
  16787. type: 'vec2',
  16788. inputs: [
  16789. { name: 'p', type: 'vec2' },
  16790. { name: 'jitter', type: 'float' },
  16791. { name: 'metric', type: 'int' }
  16792. ]
  16793. } );
  16794. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  16795. const metric = int( metric_immutable ).toVar();
  16796. const jitter = float( jitter_immutable ).toVar();
  16797. const p = vec2( p_immutable ).toVar();
  16798. const X = int().toVar(), Y = int().toVar();
  16799. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  16800. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  16801. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  16802. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  16803. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  16804. If( dist.lessThan( sqdist.x ), () => {
  16805. sqdist.z.assign( sqdist.y );
  16806. sqdist.y.assign( sqdist.x );
  16807. sqdist.x.assign( dist );
  16808. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  16809. sqdist.z.assign( sqdist.y );
  16810. sqdist.y.assign( dist );
  16811. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  16812. sqdist.z.assign( dist );
  16813. } );
  16814. } );
  16815. } );
  16816. If( metric.equal( int( 0 ) ), () => {
  16817. sqdist.assign( sqrt( sqdist ) );
  16818. } );
  16819. return sqdist;
  16820. } ).setLayout( {
  16821. name: 'mx_worley_noise_vec3_0',
  16822. type: 'vec3',
  16823. inputs: [
  16824. { name: 'p', type: 'vec2' },
  16825. { name: 'jitter', type: 'float' },
  16826. { name: 'metric', type: 'int' }
  16827. ]
  16828. } );
  16829. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  16830. const metric = int( metric_immutable ).toVar();
  16831. const jitter = float( jitter_immutable ).toVar();
  16832. const p = vec3( p_immutable ).toVar();
  16833. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  16834. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  16835. const sqdist = float( 1e6 ).toVar();
  16836. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  16837. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  16838. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  16839. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  16840. sqdist.assign( min$1( sqdist, dist ) );
  16841. } );
  16842. } );
  16843. } );
  16844. If( metric.equal( int( 0 ) ), () => {
  16845. sqdist.assign( sqrt( sqdist ) );
  16846. } );
  16847. return sqdist;
  16848. } ).setLayout( {
  16849. name: 'mx_worley_noise_float_1',
  16850. type: 'float',
  16851. inputs: [
  16852. { name: 'p', type: 'vec3' },
  16853. { name: 'jitter', type: 'float' },
  16854. { name: 'metric', type: 'int' }
  16855. ]
  16856. } );
  16857. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  16858. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  16859. const metric = int( metric_immutable ).toVar();
  16860. const jitter = float( jitter_immutable ).toVar();
  16861. const p = vec3( p_immutable ).toVar();
  16862. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  16863. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  16864. const sqdist = vec2( 1e6, 1e6 ).toVar();
  16865. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  16866. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  16867. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  16868. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  16869. If( dist.lessThan( sqdist.x ), () => {
  16870. sqdist.y.assign( sqdist.x );
  16871. sqdist.x.assign( dist );
  16872. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  16873. sqdist.y.assign( dist );
  16874. } );
  16875. } );
  16876. } );
  16877. } );
  16878. If( metric.equal( int( 0 ) ), () => {
  16879. sqdist.assign( sqrt( sqdist ) );
  16880. } );
  16881. return sqdist;
  16882. } ).setLayout( {
  16883. name: 'mx_worley_noise_vec2_1',
  16884. type: 'vec2',
  16885. inputs: [
  16886. { name: 'p', type: 'vec3' },
  16887. { name: 'jitter', type: 'float' },
  16888. { name: 'metric', type: 'int' }
  16889. ]
  16890. } );
  16891. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  16892. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  16893. const metric = int( metric_immutable ).toVar();
  16894. const jitter = float( jitter_immutable ).toVar();
  16895. const p = vec3( p_immutable ).toVar();
  16896. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  16897. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  16898. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  16899. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  16900. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  16901. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  16902. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  16903. If( dist.lessThan( sqdist.x ), () => {
  16904. sqdist.z.assign( sqdist.y );
  16905. sqdist.y.assign( sqdist.x );
  16906. sqdist.x.assign( dist );
  16907. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  16908. sqdist.z.assign( sqdist.y );
  16909. sqdist.y.assign( dist );
  16910. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  16911. sqdist.z.assign( dist );
  16912. } );
  16913. } );
  16914. } );
  16915. } );
  16916. If( metric.equal( int( 0 ) ), () => {
  16917. sqdist.assign( sqrt( sqdist ) );
  16918. } );
  16919. return sqdist;
  16920. } ).setLayout( {
  16921. name: 'mx_worley_noise_vec3_1',
  16922. type: 'vec3',
  16923. inputs: [
  16924. { name: 'p', type: 'vec3' },
  16925. { name: 'jitter', type: 'float' },
  16926. { name: 'metric', type: 'int' }
  16927. ]
  16928. } );
  16929. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  16930. // Three.js Transpiler
  16931. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  16932. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  16933. const s = hsv.y;
  16934. const v = hsv.z;
  16935. const result = vec3().toVar();
  16936. If( s.lessThan( 0.0001 ), () => {
  16937. result.assign( vec3( v, v, v ) );
  16938. } ).Else( () => {
  16939. let h = hsv.x;
  16940. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  16941. const hi = int( trunc( h ) );
  16942. const f = h.sub( float( hi ) );
  16943. const p = v.mul( s.oneMinus() );
  16944. const q = v.mul( s.mul( f ).oneMinus() );
  16945. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  16946. If( hi.equal( int( 0 ) ), () => {
  16947. result.assign( vec3( v, t, p ) );
  16948. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  16949. result.assign( vec3( q, v, p ) );
  16950. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  16951. result.assign( vec3( p, v, t ) );
  16952. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  16953. result.assign( vec3( p, q, v ) );
  16954. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  16955. result.assign( vec3( t, p, v ) );
  16956. } ).Else( () => {
  16957. result.assign( vec3( v, p, q ) );
  16958. } );
  16959. } );
  16960. return result;
  16961. } ).setLayout( {
  16962. name: 'mx_hsvtorgb',
  16963. type: 'vec3',
  16964. inputs: [
  16965. { name: 'hsv', type: 'vec3' }
  16966. ]
  16967. } );
  16968. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  16969. const c = vec3( c_immutable ).toVar();
  16970. const r = float( c.x ).toVar();
  16971. const g = float( c.y ).toVar();
  16972. const b = float( c.z ).toVar();
  16973. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  16974. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  16975. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  16976. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  16977. v.assign( maxcomp );
  16978. If( maxcomp.greaterThan( 0.0 ), () => {
  16979. s.assign( delta.div( maxcomp ) );
  16980. } ).Else( () => {
  16981. s.assign( 0.0 );
  16982. } );
  16983. If( s.lessThanEqual( 0.0 ), () => {
  16984. h.assign( 0.0 );
  16985. } ).Else( () => {
  16986. If( r.greaterThanEqual( maxcomp ), () => {
  16987. h.assign( g.sub( b ).div( delta ) );
  16988. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  16989. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  16990. } ).Else( () => {
  16991. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  16992. } );
  16993. h.mulAssign( 1.0 / 6.0 );
  16994. If( h.lessThan( 0.0 ), () => {
  16995. h.addAssign( 1.0 );
  16996. } );
  16997. } );
  16998. return vec3( h, s, v );
  16999. } ).setLayout( {
  17000. name: 'mx_rgbtohsv',
  17001. type: 'vec3',
  17002. inputs: [
  17003. { name: 'c', type: 'vec3' }
  17004. ]
  17005. } );
  17006. // Three.js Transpiler
  17007. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  17008. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  17009. const color = vec3( color_immutable ).toVar();
  17010. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  17011. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  17012. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  17013. return mix( linSeg, powSeg, isAbove );
  17014. } ).setLayout( {
  17015. name: 'mx_srgb_texture_to_lin_rec709',
  17016. type: 'vec3',
  17017. inputs: [
  17018. { name: 'color', type: 'vec3' }
  17019. ]
  17020. } );
  17021. const mx_aastep = ( threshold, value ) => {
  17022. threshold = float( threshold );
  17023. value = float( value );
  17024. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  17025. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  17026. };
  17027. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  17028. const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' );
  17029. const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' );
  17030. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  17031. const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' );
  17032. const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' );
  17033. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  17034. const mx_safepower = ( in1, in2 = 1 ) => {
  17035. in1 = float( in1 );
  17036. return in1.abs().pow( in2 ).mul( in1.sign() );
  17037. };
  17038. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  17039. const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  17040. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  17041. const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  17042. const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => {
  17043. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  17044. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  17045. return noise_vec4.mul( amplitude ).add( pivot );
  17046. };
  17047. const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  17048. const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  17049. const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  17050. const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  17051. 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 );
  17052. 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 );
  17053. 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 );
  17054. 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 );
  17055. // https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html
  17056. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  17057. const nDir = normalize( normal ).toVar( 'nDir' );
  17058. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmax' );
  17059. const rbmin = sub( float( - 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmin' );
  17060. const rbminmax = vec3().toVar( 'rbminmax' );
  17061. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  17062. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  17063. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  17064. const correction = min$1( min$1( rbminmax.x, rbminmax.y ), rbminmax.z ).toVar( 'correction' );
  17065. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar( 'boxIntersection' );
  17066. return boxIntersection.sub( cubePos );
  17067. } );
  17068. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  17069. // normal is assumed to have unit length
  17070. const x = normal.x, y = normal.y, z = normal.z;
  17071. // band 0
  17072. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  17073. // band 1
  17074. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  17075. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  17076. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  17077. // band 2
  17078. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  17079. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  17080. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  17081. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  17082. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  17083. return result;
  17084. } );
  17085. // constants
  17086. var TSL = /*#__PURE__*/Object.freeze({
  17087. __proto__: null,
  17088. BRDF_GGX: BRDF_GGX,
  17089. BRDF_Lambert: BRDF_Lambert,
  17090. BasicShadowFilter: BasicShadowFilter,
  17091. Break: Break,
  17092. Continue: Continue,
  17093. DFGApprox: DFGApprox,
  17094. D_GGX: D_GGX,
  17095. Discard: Discard,
  17096. EPSILON: EPSILON,
  17097. F_Schlick: F_Schlick,
  17098. Fn: Fn,
  17099. INFINITY: INFINITY,
  17100. If: If,
  17101. Loop: Loop,
  17102. NodeAccess: NodeAccess,
  17103. NodeShaderStage: NodeShaderStage,
  17104. NodeType: NodeType,
  17105. NodeUpdateType: NodeUpdateType,
  17106. PCFShadowFilter: PCFShadowFilter,
  17107. PCFSoftShadowFilter: PCFSoftShadowFilter,
  17108. PI: PI,
  17109. PI2: PI2,
  17110. Return: Return,
  17111. Schlick_to_F0: Schlick_to_F0,
  17112. ScriptableNodeResources: ScriptableNodeResources,
  17113. ShaderNode: ShaderNode,
  17114. TBNViewMatrix: TBNViewMatrix,
  17115. VSMShadowFilter: VSMShadowFilter,
  17116. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  17117. abs: abs,
  17118. acesFilmicToneMapping: acesFilmicToneMapping,
  17119. acos: acos,
  17120. add: add,
  17121. addMethodChaining: addMethodChaining,
  17122. addNodeElement: addNodeElement,
  17123. agxToneMapping: agxToneMapping,
  17124. all: all,
  17125. alphaT: alphaT,
  17126. and: and,
  17127. anisotropy: anisotropy,
  17128. anisotropyB: anisotropyB,
  17129. anisotropyT: anisotropyT,
  17130. any: any,
  17131. append: append,
  17132. arrayBuffer: arrayBuffer,
  17133. asin: asin,
  17134. assign: assign,
  17135. atan: atan,
  17136. atan2: atan2,
  17137. atomicAdd: atomicAdd,
  17138. atomicAnd: atomicAnd,
  17139. atomicFunc: atomicFunc,
  17140. atomicMax: atomicMax,
  17141. atomicMin: atomicMin,
  17142. atomicOr: atomicOr,
  17143. atomicStore: atomicStore,
  17144. atomicSub: atomicSub,
  17145. atomicXor: atomicXor,
  17146. attenuationColor: attenuationColor,
  17147. attenuationDistance: attenuationDistance,
  17148. attribute: attribute,
  17149. attributeArray: attributeArray,
  17150. backgroundBlurriness: backgroundBlurriness,
  17151. backgroundIntensity: backgroundIntensity,
  17152. backgroundRotation: backgroundRotation,
  17153. batch: batch,
  17154. billboarding: billboarding,
  17155. bitAnd: bitAnd,
  17156. bitNot: bitNot,
  17157. bitOr: bitOr,
  17158. bitXor: bitXor,
  17159. bitangentGeometry: bitangentGeometry,
  17160. bitangentLocal: bitangentLocal,
  17161. bitangentView: bitangentView,
  17162. bitangentWorld: bitangentWorld,
  17163. bitcast: bitcast,
  17164. blendBurn: blendBurn,
  17165. blendColor: blendColor,
  17166. blendDodge: blendDodge,
  17167. blendOverlay: blendOverlay,
  17168. blendScreen: blendScreen,
  17169. blur: blur,
  17170. bool: bool,
  17171. buffer: buffer,
  17172. bufferAttribute: bufferAttribute,
  17173. bumpMap: bumpMap,
  17174. burn: burn,
  17175. bvec2: bvec2,
  17176. bvec3: bvec3,
  17177. bvec4: bvec4,
  17178. bypass: bypass,
  17179. cache: cache,
  17180. call: call,
  17181. cameraFar: cameraFar,
  17182. cameraNear: cameraNear,
  17183. cameraNormalMatrix: cameraNormalMatrix,
  17184. cameraPosition: cameraPosition,
  17185. cameraProjectionMatrix: cameraProjectionMatrix,
  17186. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  17187. cameraViewMatrix: cameraViewMatrix,
  17188. cameraWorldMatrix: cameraWorldMatrix,
  17189. cbrt: cbrt,
  17190. cdl: cdl,
  17191. ceil: ceil,
  17192. checker: checker,
  17193. cineonToneMapping: cineonToneMapping,
  17194. clamp: clamp,
  17195. clearcoat: clearcoat,
  17196. clearcoatRoughness: clearcoatRoughness,
  17197. code: code,
  17198. color: color,
  17199. colorSpaceToWorking: colorSpaceToWorking,
  17200. colorToDirection: colorToDirection,
  17201. compute: compute,
  17202. cond: cond,
  17203. context: context,
  17204. convert: convert,
  17205. convertColorSpace: convertColorSpace,
  17206. convertToTexture: convertToTexture,
  17207. cos: cos,
  17208. cross: cross,
  17209. cubeTexture: cubeTexture,
  17210. dFdx: dFdx,
  17211. dFdy: dFdy,
  17212. dashSize: dashSize,
  17213. defaultBuildStages: defaultBuildStages,
  17214. defaultShaderStages: defaultShaderStages,
  17215. defined: defined,
  17216. degrees: degrees,
  17217. deltaTime: deltaTime,
  17218. densityFog: densityFog,
  17219. depth: depth,
  17220. depthPass: depthPass,
  17221. difference: difference,
  17222. diffuseColor: diffuseColor,
  17223. directPointLight: directPointLight,
  17224. directionToColor: directionToColor,
  17225. dispersion: dispersion,
  17226. distance: distance,
  17227. div: div,
  17228. dodge: dodge,
  17229. dot: dot,
  17230. drawIndex: drawIndex,
  17231. dynamicBufferAttribute: dynamicBufferAttribute,
  17232. element: element,
  17233. emissive: emissive,
  17234. equal: equal,
  17235. equals: equals,
  17236. equirectUV: equirectUV,
  17237. exp: exp,
  17238. exp2: exp2,
  17239. expression: expression,
  17240. faceDirection: faceDirection,
  17241. faceForward: faceForward,
  17242. float: float,
  17243. floor: floor,
  17244. fog: fog,
  17245. fract: fract,
  17246. frameGroup: frameGroup,
  17247. frameId: frameId,
  17248. frontFacing: frontFacing,
  17249. fwidth: fwidth,
  17250. gain: gain,
  17251. gapSize: gapSize,
  17252. getConstNodeType: getConstNodeType,
  17253. getCurrentStack: getCurrentStack,
  17254. getDirection: getDirection,
  17255. getDistanceAttenuation: getDistanceAttenuation,
  17256. getGeometryRoughness: getGeometryRoughness,
  17257. getNormalFromDepth: getNormalFromDepth,
  17258. getParallaxCorrectNormal: getParallaxCorrectNormal,
  17259. getRoughness: getRoughness,
  17260. getScreenPosition: getScreenPosition,
  17261. getShIrradianceAt: getShIrradianceAt,
  17262. getTextureIndex: getTextureIndex,
  17263. getViewPosition: getViewPosition,
  17264. glsl: glsl,
  17265. glslFn: glslFn,
  17266. grayscale: grayscale,
  17267. greaterThan: greaterThan,
  17268. greaterThanEqual: greaterThanEqual,
  17269. hash: hash,
  17270. highPrecisionModelNormalViewMatrix: highPrecisionModelNormalViewMatrix,
  17271. highPrecisionModelViewMatrix: highPrecisionModelViewMatrix,
  17272. hue: hue,
  17273. instance: instance,
  17274. instanceIndex: instanceIndex,
  17275. instancedArray: instancedArray,
  17276. instancedBufferAttribute: instancedBufferAttribute,
  17277. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  17278. instancedMesh: instancedMesh,
  17279. int: int,
  17280. inverseSqrt: inverseSqrt,
  17281. invocationLocalIndex: invocationLocalIndex,
  17282. invocationSubgroupIndex: invocationSubgroupIndex,
  17283. ior: ior,
  17284. iridescence: iridescence,
  17285. iridescenceIOR: iridescenceIOR,
  17286. iridescenceThickness: iridescenceThickness,
  17287. ivec2: ivec2,
  17288. ivec3: ivec3,
  17289. ivec4: ivec4,
  17290. js: js,
  17291. label: label,
  17292. length: length,
  17293. lengthSq: lengthSq,
  17294. lessThan: lessThan,
  17295. lessThanEqual: lessThanEqual,
  17296. lightPosition: lightPosition,
  17297. lightProjectionUV: lightProjectionUV,
  17298. lightShadowMatrix: lightShadowMatrix,
  17299. lightTargetDirection: lightTargetDirection,
  17300. lightTargetPosition: lightTargetPosition,
  17301. lightViewPosition: lightViewPosition,
  17302. lightingContext: lightingContext,
  17303. lights: lights,
  17304. linearDepth: linearDepth,
  17305. linearToneMapping: linearToneMapping,
  17306. localId: localId,
  17307. log: log,
  17308. log2: log2,
  17309. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  17310. loop: loop,
  17311. luminance: luminance,
  17312. mat2: mat2,
  17313. mat3: mat3,
  17314. mat4: mat4,
  17315. matcapUV: matcapUV,
  17316. materialAOMap: materialAOMap,
  17317. materialAlphaTest: materialAlphaTest,
  17318. materialAnisotropy: materialAnisotropy,
  17319. materialAnisotropyVector: materialAnisotropyVector,
  17320. materialAttenuationColor: materialAttenuationColor,
  17321. materialAttenuationDistance: materialAttenuationDistance,
  17322. materialClearcoat: materialClearcoat,
  17323. materialClearcoatNormal: materialClearcoatNormal,
  17324. materialClearcoatRoughness: materialClearcoatRoughness,
  17325. materialColor: materialColor,
  17326. materialDispersion: materialDispersion,
  17327. materialEmissive: materialEmissive,
  17328. materialIOR: materialIOR,
  17329. materialIridescence: materialIridescence,
  17330. materialIridescenceIOR: materialIridescenceIOR,
  17331. materialIridescenceThickness: materialIridescenceThickness,
  17332. materialLightMap: materialLightMap,
  17333. materialLineDashOffset: materialLineDashOffset,
  17334. materialLineDashSize: materialLineDashSize,
  17335. materialLineGapSize: materialLineGapSize,
  17336. materialLineScale: materialLineScale,
  17337. materialLineWidth: materialLineWidth,
  17338. materialMetalness: materialMetalness,
  17339. materialNormal: materialNormal,
  17340. materialOpacity: materialOpacity,
  17341. materialPointWidth: materialPointWidth,
  17342. materialReference: materialReference,
  17343. materialReflectivity: materialReflectivity,
  17344. materialRefractionRatio: materialRefractionRatio,
  17345. materialRotation: materialRotation,
  17346. materialRoughness: materialRoughness,
  17347. materialSheen: materialSheen,
  17348. materialSheenRoughness: materialSheenRoughness,
  17349. materialShininess: materialShininess,
  17350. materialSpecular: materialSpecular,
  17351. materialSpecularColor: materialSpecularColor,
  17352. materialSpecularIntensity: materialSpecularIntensity,
  17353. materialSpecularStrength: materialSpecularStrength,
  17354. materialThickness: materialThickness,
  17355. materialTransmission: materialTransmission,
  17356. max: max$1,
  17357. maxMipLevel: maxMipLevel,
  17358. metalness: metalness,
  17359. min: min$1,
  17360. mix: mix,
  17361. mixElement: mixElement,
  17362. mod: mod,
  17363. modInt: modInt,
  17364. modelDirection: modelDirection,
  17365. modelNormalMatrix: modelNormalMatrix,
  17366. modelPosition: modelPosition,
  17367. modelScale: modelScale,
  17368. modelViewMatrix: modelViewMatrix,
  17369. modelViewPosition: modelViewPosition,
  17370. modelViewProjection: modelViewProjection,
  17371. modelWorldMatrix: modelWorldMatrix,
  17372. modelWorldMatrixInverse: modelWorldMatrixInverse,
  17373. morphReference: morphReference,
  17374. mrt: mrt,
  17375. mul: mul,
  17376. mx_aastep: mx_aastep,
  17377. mx_cell_noise_float: mx_cell_noise_float,
  17378. mx_contrast: mx_contrast,
  17379. mx_fractal_noise_float: mx_fractal_noise_float,
  17380. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  17381. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  17382. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  17383. mx_hsvtorgb: mx_hsvtorgb,
  17384. mx_noise_float: mx_noise_float,
  17385. mx_noise_vec3: mx_noise_vec3,
  17386. mx_noise_vec4: mx_noise_vec4,
  17387. mx_ramplr: mx_ramplr,
  17388. mx_ramptb: mx_ramptb,
  17389. mx_rgbtohsv: mx_rgbtohsv,
  17390. mx_safepower: mx_safepower,
  17391. mx_splitlr: mx_splitlr,
  17392. mx_splittb: mx_splittb,
  17393. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  17394. mx_transform_uv: mx_transform_uv,
  17395. mx_worley_noise_float: mx_worley_noise_float,
  17396. mx_worley_noise_vec2: mx_worley_noise_vec2,
  17397. mx_worley_noise_vec3: mx_worley_noise_vec3,
  17398. negate: negate,
  17399. neutralToneMapping: neutralToneMapping,
  17400. nodeArray: nodeArray,
  17401. nodeImmutable: nodeImmutable,
  17402. nodeObject: nodeObject,
  17403. nodeObjects: nodeObjects,
  17404. nodeProxy: nodeProxy,
  17405. normalFlat: normalFlat,
  17406. normalGeometry: normalGeometry,
  17407. normalLocal: normalLocal,
  17408. normalMap: normalMap,
  17409. normalView: normalView,
  17410. normalWorld: normalWorld,
  17411. normalize: normalize,
  17412. not: not,
  17413. notEqual: notEqual,
  17414. numWorkgroups: numWorkgroups,
  17415. objectDirection: objectDirection,
  17416. objectGroup: objectGroup,
  17417. objectPosition: objectPosition,
  17418. objectScale: objectScale,
  17419. objectViewPosition: objectViewPosition,
  17420. objectWorldMatrix: objectWorldMatrix,
  17421. oneMinus: oneMinus,
  17422. or: or,
  17423. orthographicDepthToViewZ: orthographicDepthToViewZ,
  17424. oscSawtooth: oscSawtooth,
  17425. oscSine: oscSine,
  17426. oscSquare: oscSquare,
  17427. oscTriangle: oscTriangle,
  17428. output: output,
  17429. outputStruct: outputStruct,
  17430. overlay: overlay,
  17431. overloadingFn: overloadingFn,
  17432. parabola: parabola,
  17433. parallaxDirection: parallaxDirection,
  17434. parallaxUV: parallaxUV,
  17435. parameter: parameter,
  17436. pass: pass,
  17437. passTexture: passTexture,
  17438. pcurve: pcurve,
  17439. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  17440. pmremTexture: pmremTexture,
  17441. pointUV: pointUV,
  17442. pointWidth: pointWidth,
  17443. positionGeometry: positionGeometry,
  17444. positionLocal: positionLocal,
  17445. positionPrevious: positionPrevious,
  17446. positionView: positionView,
  17447. positionViewDirection: positionViewDirection,
  17448. positionWorld: positionWorld,
  17449. positionWorldDirection: positionWorldDirection,
  17450. posterize: posterize,
  17451. pow: pow,
  17452. pow2: pow2,
  17453. pow3: pow3,
  17454. pow4: pow4,
  17455. property: property,
  17456. radians: radians,
  17457. rand: rand,
  17458. range: range,
  17459. rangeFog: rangeFog,
  17460. reciprocal: reciprocal,
  17461. reference: reference,
  17462. referenceBuffer: referenceBuffer,
  17463. reflect: reflect,
  17464. reflectVector: reflectVector,
  17465. reflectView: reflectView,
  17466. reflector: reflector,
  17467. refract: refract,
  17468. refractVector: refractVector,
  17469. refractView: refractView,
  17470. reinhardToneMapping: reinhardToneMapping,
  17471. remainder: remainder,
  17472. remap: remap,
  17473. remapClamp: remapClamp,
  17474. renderGroup: renderGroup,
  17475. renderOutput: renderOutput,
  17476. rendererReference: rendererReference,
  17477. rotate: rotate,
  17478. rotateUV: rotateUV,
  17479. roughness: roughness,
  17480. round: round,
  17481. rtt: rtt,
  17482. sRGBTransferEOTF: sRGBTransferEOTF,
  17483. sRGBTransferOETF: sRGBTransferOETF,
  17484. sampler: sampler,
  17485. saturate: saturate,
  17486. saturation: saturation,
  17487. screen: screen,
  17488. screenCoordinate: screenCoordinate,
  17489. screenSize: screenSize,
  17490. screenUV: screenUV,
  17491. scriptable: scriptable,
  17492. scriptableValue: scriptableValue,
  17493. select: select,
  17494. setCurrentStack: setCurrentStack,
  17495. shaderStages: shaderStages,
  17496. shadow: shadow,
  17497. sharedUniformGroup: sharedUniformGroup,
  17498. sheen: sheen,
  17499. sheenRoughness: sheenRoughness,
  17500. shiftLeft: shiftLeft,
  17501. shiftRight: shiftRight,
  17502. shininess: shininess,
  17503. sign: sign,
  17504. sin: sin,
  17505. sinc: sinc,
  17506. skinning: skinning,
  17507. skinningReference: skinningReference,
  17508. smoothstep: smoothstep,
  17509. smoothstepElement: smoothstepElement,
  17510. specularColor: specularColor,
  17511. specularF90: specularF90,
  17512. spherizeUV: spherizeUV,
  17513. split: split,
  17514. spritesheetUV: spritesheetUV,
  17515. sqrt: sqrt,
  17516. stack: stack,
  17517. step: step,
  17518. storage: storage,
  17519. storageBarrier: storageBarrier,
  17520. storageObject: storageObject,
  17521. storageTexture: storageTexture,
  17522. string: string,
  17523. sub: sub,
  17524. subgroupIndex: subgroupIndex,
  17525. subgroupSize: subgroupSize,
  17526. tan: tan,
  17527. tangentGeometry: tangentGeometry,
  17528. tangentLocal: tangentLocal,
  17529. tangentView: tangentView,
  17530. tangentWorld: tangentWorld,
  17531. temp: temp,
  17532. texture: texture,
  17533. texture3D: texture3D,
  17534. textureBarrier: textureBarrier,
  17535. textureBicubic: textureBicubic,
  17536. textureCubeUV: textureCubeUV,
  17537. textureLoad: textureLoad,
  17538. textureSize: textureSize,
  17539. textureStore: textureStore,
  17540. thickness: thickness,
  17541. time: time,
  17542. timerDelta: timerDelta,
  17543. timerGlobal: timerGlobal,
  17544. timerLocal: timerLocal,
  17545. toOutputColorSpace: toOutputColorSpace,
  17546. toWorkingColorSpace: toWorkingColorSpace,
  17547. toneMapping: toneMapping,
  17548. toneMappingExposure: toneMappingExposure,
  17549. toonOutlinePass: toonOutlinePass,
  17550. transformDirection: transformDirection,
  17551. transformNormal: transformNormal,
  17552. transformNormalToView: transformNormalToView,
  17553. transformedBentNormalView: transformedBentNormalView,
  17554. transformedBitangentView: transformedBitangentView,
  17555. transformedBitangentWorld: transformedBitangentWorld,
  17556. transformedClearcoatNormalView: transformedClearcoatNormalView,
  17557. transformedNormalView: transformedNormalView,
  17558. transformedNormalWorld: transformedNormalWorld,
  17559. transformedTangentView: transformedTangentView,
  17560. transformedTangentWorld: transformedTangentWorld,
  17561. transmission: transmission,
  17562. transpose: transpose,
  17563. tri: tri,
  17564. tri3: tri3,
  17565. triNoise3D: triNoise3D,
  17566. triplanarTexture: triplanarTexture,
  17567. triplanarTextures: triplanarTextures,
  17568. trunc: trunc,
  17569. tslFn: tslFn,
  17570. uint: uint,
  17571. uniform: uniform,
  17572. uniformArray: uniformArray,
  17573. uniformGroup: uniformGroup,
  17574. uniforms: uniforms,
  17575. userData: userData,
  17576. uv: uv,
  17577. uvec2: uvec2,
  17578. uvec3: uvec3,
  17579. uvec4: uvec4,
  17580. varying: varying,
  17581. varyingProperty: varyingProperty,
  17582. vec2: vec2,
  17583. vec3: vec3,
  17584. vec4: vec4,
  17585. vectorComponents: vectorComponents,
  17586. velocity: velocity,
  17587. vertexColor: vertexColor,
  17588. vertexIndex: vertexIndex,
  17589. vibrance: vibrance,
  17590. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  17591. viewZToOrthographicDepth: viewZToOrthographicDepth,
  17592. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  17593. viewport: viewport,
  17594. viewportBottomLeft: viewportBottomLeft,
  17595. viewportCoordinate: viewportCoordinate,
  17596. viewportDepthTexture: viewportDepthTexture,
  17597. viewportLinearDepth: viewportLinearDepth,
  17598. viewportMipTexture: viewportMipTexture,
  17599. viewportResolution: viewportResolution,
  17600. viewportSafeUV: viewportSafeUV,
  17601. viewportSharedTexture: viewportSharedTexture,
  17602. viewportSize: viewportSize,
  17603. viewportTexture: viewportTexture,
  17604. viewportTopLeft: viewportTopLeft,
  17605. viewportUV: viewportUV,
  17606. wgsl: wgsl,
  17607. wgslFn: wgslFn,
  17608. workgroupArray: workgroupArray,
  17609. workgroupBarrier: workgroupBarrier,
  17610. workgroupId: workgroupId,
  17611. workingToColorSpace: workingToColorSpace,
  17612. xor: xor
  17613. });
  17614. const _clearColor$1 = /*@__PURE__*/ new Color4();
  17615. class Background extends DataMap {
  17616. constructor( renderer, nodes ) {
  17617. super();
  17618. this.renderer = renderer;
  17619. this.nodes = nodes;
  17620. }
  17621. update( scene, renderList, renderContext ) {
  17622. const renderer = this.renderer;
  17623. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  17624. let forceClear = false;
  17625. if ( background === null ) {
  17626. // no background settings, use clear color configuration from the renderer
  17627. renderer._clearColor.getRGB( _clearColor$1, LinearSRGBColorSpace );
  17628. _clearColor$1.a = renderer._clearColor.a;
  17629. } else if ( background.isColor === true ) {
  17630. // background is an opaque color
  17631. background.getRGB( _clearColor$1, LinearSRGBColorSpace );
  17632. _clearColor$1.a = 1;
  17633. forceClear = true;
  17634. } else if ( background.isNode === true ) {
  17635. const sceneData = this.get( scene );
  17636. const backgroundNode = background;
  17637. _clearColor$1.copy( renderer._clearColor );
  17638. let backgroundMesh = sceneData.backgroundMesh;
  17639. if ( backgroundMesh === undefined ) {
  17640. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  17641. // @TODO: Add Texture2D support using node context
  17642. getUV: () => backgroundRotation.mul( normalWorld ),
  17643. getTextureLevel: () => backgroundBlurriness
  17644. } );
  17645. let viewProj = modelViewProjection();
  17646. viewProj = viewProj.setZ( viewProj.w );
  17647. const nodeMaterial = new NodeMaterial();
  17648. nodeMaterial.name = 'Background.material';
  17649. nodeMaterial.side = BackSide;
  17650. nodeMaterial.depthTest = false;
  17651. nodeMaterial.depthWrite = false;
  17652. nodeMaterial.fog = false;
  17653. nodeMaterial.lights = false;
  17654. nodeMaterial.vertexNode = viewProj;
  17655. nodeMaterial.colorNode = backgroundMeshNode;
  17656. sceneData.backgroundMeshNode = backgroundMeshNode;
  17657. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  17658. backgroundMesh.frustumCulled = false;
  17659. backgroundMesh.name = 'Background.mesh';
  17660. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  17661. this.matrixWorld.copyPosition( camera.matrixWorld );
  17662. };
  17663. }
  17664. const backgroundCacheKey = backgroundNode.getCacheKey();
  17665. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  17666. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  17667. sceneData.backgroundMeshNode.needsUpdate = true;
  17668. backgroundMesh.material.needsUpdate = true;
  17669. sceneData.backgroundCacheKey = backgroundCacheKey;
  17670. }
  17671. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  17672. } else {
  17673. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  17674. }
  17675. //
  17676. if ( renderer.autoClear === true || forceClear === true ) {
  17677. const clearColorValue = renderContext.clearColorValue;
  17678. clearColorValue.r = _clearColor$1.r;
  17679. clearColorValue.g = _clearColor$1.g;
  17680. clearColorValue.b = _clearColor$1.b;
  17681. clearColorValue.a = _clearColor$1.a;
  17682. // premultiply alpha
  17683. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  17684. clearColorValue.r *= clearColorValue.a;
  17685. clearColorValue.g *= clearColorValue.a;
  17686. clearColorValue.b *= clearColorValue.a;
  17687. }
  17688. //
  17689. renderContext.depthClearValue = renderer._clearDepth;
  17690. renderContext.stencilClearValue = renderer._clearStencil;
  17691. renderContext.clearColor = renderer.autoClearColor === true;
  17692. renderContext.clearDepth = renderer.autoClearDepth === true;
  17693. renderContext.clearStencil = renderer.autoClearStencil === true;
  17694. } else {
  17695. renderContext.clearColor = false;
  17696. renderContext.clearDepth = false;
  17697. renderContext.clearStencil = false;
  17698. }
  17699. }
  17700. }
  17701. let _id$6 = 0;
  17702. class BindGroup {
  17703. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  17704. this.name = name;
  17705. this.bindings = bindings;
  17706. this.index = index;
  17707. this.bindingsReference = bindingsReference;
  17708. this.id = _id$6 ++;
  17709. }
  17710. }
  17711. class NodeBuilderState {
  17712. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, monitor, transforms = [] ) {
  17713. this.vertexShader = vertexShader;
  17714. this.fragmentShader = fragmentShader;
  17715. this.computeShader = computeShader;
  17716. this.transforms = transforms;
  17717. this.nodeAttributes = nodeAttributes;
  17718. this.bindings = bindings;
  17719. this.updateNodes = updateNodes;
  17720. this.updateBeforeNodes = updateBeforeNodes;
  17721. this.updateAfterNodes = updateAfterNodes;
  17722. this.monitor = monitor;
  17723. this.usedTimes = 0;
  17724. }
  17725. createBindings() {
  17726. const bindings = [];
  17727. for ( const instanceGroup of this.bindings ) {
  17728. const shared = instanceGroup.bindings[ 0 ].groupNode.shared;
  17729. if ( shared !== true ) {
  17730. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup );
  17731. bindings.push( bindingsGroup );
  17732. for ( const instanceBinding of instanceGroup.bindings ) {
  17733. bindingsGroup.bindings.push( instanceBinding.clone() );
  17734. }
  17735. } else {
  17736. bindings.push( instanceGroup );
  17737. }
  17738. }
  17739. return bindings;
  17740. }
  17741. }
  17742. /**
  17743. * {@link NodeBuilder} is going to create instances of this class during the build process
  17744. * of nodes. They represent the final shader attributes that are going to be generated
  17745. * by the builder. Arrays of node attributes is maintained in {@link NodeBuilder#attributes}
  17746. * and {@link NodeBuilder#bufferAttributes} for this purpose.
  17747. */
  17748. class NodeAttribute {
  17749. /**
  17750. * Constructs a new node attribute.
  17751. *
  17752. * @param {String} name - The name of the attribute.
  17753. * @param {String} type - The type of the attribute.
  17754. * @param {Node?} node - An optional reference to the node.
  17755. */
  17756. constructor( name, type, node = null ) {
  17757. /**
  17758. * This flag can be used for type testing.
  17759. *
  17760. * @type {Boolean}
  17761. * @readonly
  17762. * @default true
  17763. */
  17764. this.isNodeAttribute = true;
  17765. /**
  17766. * The name of the attribute.
  17767. *
  17768. * @type {String}
  17769. */
  17770. this.name = name;
  17771. /**
  17772. * The type of the attribute.
  17773. *
  17774. * @type {String}
  17775. */
  17776. this.type = type;
  17777. /**
  17778. * An optional reference to the node.
  17779. *
  17780. * @type {Node?}
  17781. * @default null
  17782. */
  17783. this.node = node;
  17784. }
  17785. }
  17786. /**
  17787. * {@link NodeBuilder} is going to create instances of this class during the build process
  17788. * of nodes. They represent the final shader uniforms that are going to be generated
  17789. * by the builder. A dictionary of node uniforms is maintained in {@link NodeBuilder#uniforms}
  17790. * for this purpose.
  17791. */
  17792. class NodeUniform {
  17793. /**
  17794. * Constructs a new node uniform.
  17795. *
  17796. * @param {String} name - The name of the uniform.
  17797. * @param {String} type - The type of the uniform.
  17798. * @param {UniformNode} node - An reference to the node.
  17799. */
  17800. constructor( name, type, node ) {
  17801. /**
  17802. * This flag can be used for type testing.
  17803. *
  17804. * @type {Boolean}
  17805. * @readonly
  17806. * @default true
  17807. */
  17808. this.isNodeUniform = true;
  17809. /**
  17810. * The name of the uniform.
  17811. *
  17812. * @type {String}
  17813. */
  17814. this.name = name;
  17815. /**
  17816. * The type of the uniform.
  17817. *
  17818. * @type {String}
  17819. */
  17820. this.type = type;
  17821. /**
  17822. * An reference to the node.
  17823. *
  17824. * @type {UniformNode}
  17825. */
  17826. this.node = node.getSelf();
  17827. }
  17828. /**
  17829. * The value of the uniform node.
  17830. *
  17831. * @type {Any}
  17832. */
  17833. get value() {
  17834. return this.node.value;
  17835. }
  17836. set value( val ) {
  17837. this.node.value = val;
  17838. }
  17839. /**
  17840. * The id of the uniform node.
  17841. *
  17842. * @type {Number}
  17843. */
  17844. get id() {
  17845. return this.node.id;
  17846. }
  17847. /**
  17848. * The uniform node's group.
  17849. *
  17850. * @type {UniformGroupNode}
  17851. */
  17852. get groupNode() {
  17853. return this.node.groupNode;
  17854. }
  17855. }
  17856. /**
  17857. * {@link NodeBuilder} is going to create instances of this class during the build process
  17858. * of nodes. They represent the final shader variables that are going to be generated
  17859. * by the builder. A dictionary of node variables is maintained in {@link NodeBuilder#vars} for
  17860. * this purpose.
  17861. */
  17862. class NodeVar {
  17863. /**
  17864. * Constructs a new node variable.
  17865. *
  17866. * @param {String} name - The name of the variable.
  17867. * @param {String} type - The type of the variable.
  17868. */
  17869. constructor( name, type ) {
  17870. /**
  17871. * This flag can be used for type testing.
  17872. *
  17873. * @type {Boolean}
  17874. * @readonly
  17875. * @default true
  17876. */
  17877. this.isNodeVar = true;
  17878. /**
  17879. * The name of the variable.
  17880. *
  17881. * @type {String}
  17882. */
  17883. this.name = name;
  17884. /**
  17885. * The type of the variable.
  17886. *
  17887. * @type {String}
  17888. */
  17889. this.type = type;
  17890. }
  17891. }
  17892. /**
  17893. * {@link NodeBuilder} is going to create instances of this class during the build process
  17894. * of nodes. They represent the final shader varyings that are going to be generated
  17895. * by the builder. An array of node varyings is maintained in {@link NodeBuilder#varyings} for
  17896. * this purpose.
  17897. *
  17898. * @augments NodeVar
  17899. */
  17900. class NodeVarying extends NodeVar {
  17901. /**
  17902. * Constructs a new node varying.
  17903. *
  17904. * @param {String} name - The name of the varying.
  17905. * @param {String} type - The type of the varying.
  17906. */
  17907. constructor( name, type ) {
  17908. super( name, type );
  17909. /**
  17910. * Whether this varying requires interpolation or not. This property can be used
  17911. * to check if the varying can be optimized for a variable.
  17912. *
  17913. * @type {Boolean}
  17914. * @default false
  17915. */
  17916. this.needsInterpolation = false;
  17917. /**
  17918. * This flag can be used for type testing.
  17919. *
  17920. * @type {Boolean}
  17921. * @readonly
  17922. * @default true
  17923. */
  17924. this.isNodeVarying = true;
  17925. }
  17926. }
  17927. /**
  17928. * {@link NodeBuilder} is going to create instances of this class during the build process
  17929. * of nodes. They represent user-defined, native shader code portions that are going to be
  17930. * injected by the builder. A dictionary of node codes is maintained in {@link NodeBuilder#codes}
  17931. * for this purpose.
  17932. */
  17933. class NodeCode {
  17934. /**
  17935. * Constructs a new code node.
  17936. *
  17937. * @param {String} name - The name of the code.
  17938. * @param {String} type - The node type.
  17939. * @param {String} [code=''] - The native shader code.
  17940. */
  17941. constructor( name, type, code = '' ) {
  17942. /**
  17943. * The name of the code.
  17944. *
  17945. * @type {String}
  17946. */
  17947. this.name = name;
  17948. /**
  17949. * The node type.
  17950. *
  17951. * @type {String}
  17952. */
  17953. this.type = type;
  17954. /**
  17955. * The native shader code.
  17956. *
  17957. * @type {String}
  17958. * @default ''
  17959. */
  17960. this.code = code;
  17961. Object.defineProperty( this, 'isNodeCode', { value: true } );
  17962. }
  17963. }
  17964. let _id$5 = 0;
  17965. /**
  17966. * This utility class is used in {@link NodeBuilder} as an internal
  17967. * cache data structure for node data.
  17968. */
  17969. class NodeCache {
  17970. /**
  17971. * Constructs a new node cache.
  17972. *
  17973. * @param {NodeCache?} parent - A reference to a parent cache.
  17974. */
  17975. constructor( parent = null ) {
  17976. /**
  17977. * The id of the cache.
  17978. *
  17979. * @type {Number}
  17980. * @readonly
  17981. */
  17982. this.id = _id$5 ++;
  17983. /**
  17984. * A weak map for managing node data.
  17985. *
  17986. * @type {WeakMap}
  17987. */
  17988. this.nodesData = new WeakMap();
  17989. /**
  17990. * Reference to a parent node cache.
  17991. *
  17992. * @type {NodeCache?}
  17993. * @default null
  17994. */
  17995. this.parent = parent;
  17996. }
  17997. /**
  17998. * Returns the data for the given node.
  17999. *
  18000. * @param {Node} node - The node.
  18001. * @return {Object?} The data for the node.
  18002. */
  18003. getData( node ) {
  18004. let data = this.nodesData.get( node );
  18005. if ( data === undefined && this.parent !== null ) {
  18006. data = this.parent.getData( node );
  18007. }
  18008. return data;
  18009. }
  18010. /**
  18011. * Sets the data for a given node.
  18012. *
  18013. * @param {Node} node - The node.
  18014. * @param {Object} data - The data that should be cached.
  18015. */
  18016. setData( node, data ) {
  18017. this.nodesData.set( node, data );
  18018. }
  18019. }
  18020. /**
  18021. * {@link NodeBuilder} is going to create instances of this class during the build process
  18022. * of nodes. They represent the final shader struct data that are going to be generated
  18023. * by the builder. A dictionary of struct types is maintained in {@link NodeBuilder#structs}
  18024. * for this purpose.
  18025. */
  18026. class StructTypeNode extends Node {
  18027. static get type() {
  18028. return 'StructTypeNode';
  18029. }
  18030. /**
  18031. * Constructs a new struct type node.
  18032. *
  18033. * @param {String} name - The name of the struct.
  18034. * @param {Array<String>} types - An array of types.
  18035. */
  18036. constructor( name, types ) {
  18037. super();
  18038. /**
  18039. * The name of the struct.
  18040. *
  18041. * @type {String}
  18042. */
  18043. this.name = name;
  18044. /**
  18045. * An array of types.
  18046. *
  18047. * @type {Array<String>}
  18048. */
  18049. this.types = types;
  18050. /**
  18051. * This flag can be used for type testing.
  18052. *
  18053. * @type {Boolean}
  18054. * @readonly
  18055. * @default true
  18056. */
  18057. this.isStructTypeNode = true;
  18058. }
  18059. /**
  18060. * Returns the member types.
  18061. *
  18062. * @return {Array<String>} The types.
  18063. */
  18064. getMemberTypes() {
  18065. return this.types;
  18066. }
  18067. }
  18068. class Uniform {
  18069. constructor( name, value ) {
  18070. this.name = name;
  18071. this.value = value;
  18072. this.boundary = 0; // used to build the uniform buffer according to the STD140 layout
  18073. this.itemSize = 0;
  18074. this.offset = 0; // this property is set by WebGPUUniformsGroup and marks the start position in the uniform buffer
  18075. }
  18076. setValue( value ) {
  18077. this.value = value;
  18078. }
  18079. getValue() {
  18080. return this.value;
  18081. }
  18082. }
  18083. class NumberUniform extends Uniform {
  18084. constructor( name, value = 0 ) {
  18085. super( name, value );
  18086. this.isNumberUniform = true;
  18087. this.boundary = 4;
  18088. this.itemSize = 1;
  18089. }
  18090. }
  18091. class Vector2Uniform extends Uniform {
  18092. constructor( name, value = new Vector2() ) {
  18093. super( name, value );
  18094. this.isVector2Uniform = true;
  18095. this.boundary = 8;
  18096. this.itemSize = 2;
  18097. }
  18098. }
  18099. class Vector3Uniform extends Uniform {
  18100. constructor( name, value = new Vector3() ) {
  18101. super( name, value );
  18102. this.isVector3Uniform = true;
  18103. this.boundary = 16;
  18104. this.itemSize = 3;
  18105. }
  18106. }
  18107. class Vector4Uniform extends Uniform {
  18108. constructor( name, value = new Vector4() ) {
  18109. super( name, value );
  18110. this.isVector4Uniform = true;
  18111. this.boundary = 16;
  18112. this.itemSize = 4;
  18113. }
  18114. }
  18115. class ColorUniform extends Uniform {
  18116. constructor( name, value = new Color() ) {
  18117. super( name, value );
  18118. this.isColorUniform = true;
  18119. this.boundary = 16;
  18120. this.itemSize = 3;
  18121. }
  18122. }
  18123. class Matrix3Uniform extends Uniform {
  18124. constructor( name, value = new Matrix3() ) {
  18125. super( name, value );
  18126. this.isMatrix3Uniform = true;
  18127. this.boundary = 48;
  18128. this.itemSize = 12;
  18129. }
  18130. }
  18131. class Matrix4Uniform extends Uniform {
  18132. constructor( name, value = new Matrix4() ) {
  18133. super( name, value );
  18134. this.isMatrix4Uniform = true;
  18135. this.boundary = 64;
  18136. this.itemSize = 16;
  18137. }
  18138. }
  18139. class NumberNodeUniform extends NumberUniform {
  18140. constructor( nodeUniform ) {
  18141. super( nodeUniform.name, nodeUniform.value );
  18142. this.nodeUniform = nodeUniform;
  18143. }
  18144. getValue() {
  18145. return this.nodeUniform.value;
  18146. }
  18147. getType() {
  18148. return this.nodeUniform.type;
  18149. }
  18150. }
  18151. class Vector2NodeUniform extends Vector2Uniform {
  18152. constructor( nodeUniform ) {
  18153. super( nodeUniform.name, nodeUniform.value );
  18154. this.nodeUniform = nodeUniform;
  18155. }
  18156. getValue() {
  18157. return this.nodeUniform.value;
  18158. }
  18159. getType() {
  18160. return this.nodeUniform.type;
  18161. }
  18162. }
  18163. class Vector3NodeUniform extends Vector3Uniform {
  18164. constructor( nodeUniform ) {
  18165. super( nodeUniform.name, nodeUniform.value );
  18166. this.nodeUniform = nodeUniform;
  18167. }
  18168. getValue() {
  18169. return this.nodeUniform.value;
  18170. }
  18171. getType() {
  18172. return this.nodeUniform.type;
  18173. }
  18174. }
  18175. class Vector4NodeUniform extends Vector4Uniform {
  18176. constructor( nodeUniform ) {
  18177. super( nodeUniform.name, nodeUniform.value );
  18178. this.nodeUniform = nodeUniform;
  18179. }
  18180. getValue() {
  18181. return this.nodeUniform.value;
  18182. }
  18183. getType() {
  18184. return this.nodeUniform.type;
  18185. }
  18186. }
  18187. class ColorNodeUniform extends ColorUniform {
  18188. constructor( nodeUniform ) {
  18189. super( nodeUniform.name, nodeUniform.value );
  18190. this.nodeUniform = nodeUniform;
  18191. }
  18192. getValue() {
  18193. return this.nodeUniform.value;
  18194. }
  18195. getType() {
  18196. return this.nodeUniform.type;
  18197. }
  18198. }
  18199. class Matrix3NodeUniform extends Matrix3Uniform {
  18200. constructor( nodeUniform ) {
  18201. super( nodeUniform.name, nodeUniform.value );
  18202. this.nodeUniform = nodeUniform;
  18203. }
  18204. getValue() {
  18205. return this.nodeUniform.value;
  18206. }
  18207. getType() {
  18208. return this.nodeUniform.type;
  18209. }
  18210. }
  18211. class Matrix4NodeUniform extends Matrix4Uniform {
  18212. constructor( nodeUniform ) {
  18213. super( nodeUniform.name, nodeUniform.value );
  18214. this.nodeUniform = nodeUniform;
  18215. }
  18216. getValue() {
  18217. return this.nodeUniform.value;
  18218. }
  18219. getType() {
  18220. return this.nodeUniform.type;
  18221. }
  18222. }
  18223. const LOD_MIN = 4;
  18224. // The standard deviations (radians) associated with the extra mips. These are
  18225. // chosen to approximate a Trowbridge-Reitz distribution function times the
  18226. // geometric shadowing function. These sigma values squared must match the
  18227. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  18228. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  18229. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  18230. // samples and exit early, but not recompile the shader.
  18231. const MAX_SAMPLES = 20;
  18232. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  18233. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  18234. const _clearColor = /*@__PURE__*/ new Color();
  18235. let _oldTarget = null;
  18236. let _oldActiveCubeFace = 0;
  18237. let _oldActiveMipmapLevel = 0;
  18238. // Golden Ratio
  18239. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  18240. const INV_PHI = 1 / PHI;
  18241. // Vertices of a dodecahedron (except the opposites, which represent the
  18242. // same axis), used as axis directions evenly spread on a sphere.
  18243. const _axisDirections = [
  18244. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  18245. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  18246. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  18247. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  18248. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  18249. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  18250. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  18251. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  18252. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  18253. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  18254. ];
  18255. //
  18256. // WebGPU Face indices
  18257. const _faceLib = [
  18258. 3, 1, 5,
  18259. 0, 4, 2
  18260. ];
  18261. const direction = getDirection( uv(), attribute( 'faceIndex' ) ).normalize();
  18262. const outputDirection = vec3( direction.x, direction.y.negate(), direction.z );
  18263. /**
  18264. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  18265. * (PMREM) from a cubeMap environment texture. This allows different levels of
  18266. * blur to be quickly accessed based on material roughness. It is packed into a
  18267. * special CubeUV format that allows us to perform custom interpolation so that
  18268. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  18269. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  18270. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  18271. * higher roughness levels. In this way we maintain resolution to smoothly
  18272. * interpolate diffuse lighting while limiting sampling computation.
  18273. *
  18274. * Paper: Fast, Accurate Image-Based Lighting
  18275. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  18276. */
  18277. class PMREMGenerator {
  18278. constructor( renderer ) {
  18279. this._renderer = renderer;
  18280. this._pingPongRenderTarget = null;
  18281. this._lodMax = 0;
  18282. this._cubeSize = 0;
  18283. this._lodPlanes = [];
  18284. this._sizeLods = [];
  18285. this._sigmas = [];
  18286. this._lodMeshes = [];
  18287. this._blurMaterial = null;
  18288. this._cubemapMaterial = null;
  18289. this._equirectMaterial = null;
  18290. this._backgroundBox = null;
  18291. }
  18292. get _hasInitialized() {
  18293. return this._renderer.hasInitialized();
  18294. }
  18295. /**
  18296. * Generates a PMREM from a supplied Scene, which can be faster than using an
  18297. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  18298. * in radians to be applied to the scene before PMREM generation. Optional near
  18299. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  18300. * is placed at the origin).
  18301. */
  18302. fromScene( scene, sigma = 0, near = 0.1, far = 100, renderTarget = null ) {
  18303. this._setSize( 256 );
  18304. if ( this._hasInitialized === false ) {
  18305. console.warn( 'THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.' );
  18306. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  18307. this.fromSceneAsync( scene, sigma, near, far, cubeUVRenderTarget );
  18308. return cubeUVRenderTarget;
  18309. }
  18310. _oldTarget = this._renderer.getRenderTarget();
  18311. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  18312. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  18313. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  18314. cubeUVRenderTarget.depthBuffer = true;
  18315. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  18316. if ( sigma > 0 ) {
  18317. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  18318. }
  18319. this._applyPMREM( cubeUVRenderTarget );
  18320. this._cleanup( cubeUVRenderTarget );
  18321. return cubeUVRenderTarget;
  18322. }
  18323. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, renderTarget = null ) {
  18324. if ( this._hasInitialized === false ) await this._renderer.init();
  18325. return this.fromScene( scene, sigma, near, far, renderTarget );
  18326. }
  18327. /**
  18328. * Generates a PMREM from an equirectangular texture, which can be either LDR
  18329. * or HDR. The ideal input image size is 1k (1024 x 512),
  18330. * as this matches best with the 256 x 256 cubemap output.
  18331. */
  18332. fromEquirectangular( equirectangular, renderTarget = null ) {
  18333. if ( this._hasInitialized === false ) {
  18334. console.warn( 'THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead.' );
  18335. this._setSizeFromTexture( equirectangular );
  18336. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  18337. this.fromEquirectangularAsync( equirectangular, cubeUVRenderTarget );
  18338. return cubeUVRenderTarget;
  18339. }
  18340. return this._fromTexture( equirectangular, renderTarget );
  18341. }
  18342. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  18343. if ( this._hasInitialized === false ) await this._renderer.init();
  18344. return this._fromTexture( equirectangular, renderTarget );
  18345. }
  18346. /**
  18347. * Generates a PMREM from an cubemap texture, which can be either LDR
  18348. * or HDR. The ideal input cube size is 256 x 256,
  18349. * as this matches best with the 256 x 256 cubemap output.
  18350. */
  18351. fromCubemap( cubemap, renderTarget = null ) {
  18352. if ( this._hasInitialized === false ) {
  18353. console.warn( 'THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead.' );
  18354. this._setSizeFromTexture( cubemap );
  18355. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  18356. this.fromCubemapAsync( cubemap, renderTarget );
  18357. return cubeUVRenderTarget;
  18358. }
  18359. return this._fromTexture( cubemap, renderTarget );
  18360. }
  18361. async fromCubemapAsync( cubemap, renderTarget = null ) {
  18362. if ( this._hasInitialized === false ) await this._renderer.init();
  18363. return this._fromTexture( cubemap, renderTarget );
  18364. }
  18365. /**
  18366. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  18367. * your texture's network fetch for increased concurrency.
  18368. */
  18369. async compileCubemapShader() {
  18370. if ( this._cubemapMaterial === null ) {
  18371. this._cubemapMaterial = _getCubemapMaterial();
  18372. await this._compileMaterial( this._cubemapMaterial );
  18373. }
  18374. }
  18375. /**
  18376. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  18377. * your texture's network fetch for increased concurrency.
  18378. */
  18379. async compileEquirectangularShader() {
  18380. if ( this._equirectMaterial === null ) {
  18381. this._equirectMaterial = _getEquirectMaterial();
  18382. await this._compileMaterial( this._equirectMaterial );
  18383. }
  18384. }
  18385. /**
  18386. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  18387. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  18388. * one of them will cause any others to also become unusable.
  18389. */
  18390. dispose() {
  18391. this._dispose();
  18392. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  18393. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  18394. if ( this._backgroundBox !== null ) {
  18395. this._backgroundBox.geometry.dispose();
  18396. this._backgroundBox.material.dispose();
  18397. }
  18398. }
  18399. // private interface
  18400. _setSizeFromTexture( texture ) {
  18401. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  18402. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  18403. } else { // Equirectangular
  18404. this._setSize( texture.image.width / 4 );
  18405. }
  18406. }
  18407. _setSize( cubeSize ) {
  18408. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  18409. this._cubeSize = Math.pow( 2, this._lodMax );
  18410. }
  18411. _dispose() {
  18412. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  18413. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  18414. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  18415. this._lodPlanes[ i ].dispose();
  18416. }
  18417. }
  18418. _cleanup( outputTarget ) {
  18419. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  18420. outputTarget.scissorTest = false;
  18421. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  18422. }
  18423. _fromTexture( texture, renderTarget ) {
  18424. this._setSizeFromTexture( texture );
  18425. _oldTarget = this._renderer.getRenderTarget();
  18426. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  18427. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  18428. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  18429. this._textureToCubeUV( texture, cubeUVRenderTarget );
  18430. this._applyPMREM( cubeUVRenderTarget );
  18431. this._cleanup( cubeUVRenderTarget );
  18432. return cubeUVRenderTarget;
  18433. }
  18434. _allocateTargets() {
  18435. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  18436. const height = 4 * this._cubeSize;
  18437. const params = {
  18438. magFilter: LinearFilter,
  18439. minFilter: LinearFilter,
  18440. generateMipmaps: false,
  18441. type: HalfFloatType,
  18442. format: RGBAFormat,
  18443. colorSpace: LinearSRGBColorSpace,
  18444. //depthBuffer: false
  18445. };
  18446. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  18447. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  18448. if ( this._pingPongRenderTarget !== null ) {
  18449. this._dispose();
  18450. }
  18451. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  18452. const { _lodMax } = this;
  18453. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  18454. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  18455. }
  18456. return cubeUVRenderTarget;
  18457. }
  18458. async _compileMaterial( material ) {
  18459. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  18460. await this._renderer.compile( tmpMesh, _flatCamera );
  18461. }
  18462. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  18463. const cubeCamera = _cubeCamera;
  18464. cubeCamera.near = near;
  18465. cubeCamera.far = far;
  18466. // px, py, pz, nx, ny, nz
  18467. const upSign = [ - 1, 1, - 1, - 1, - 1, - 1 ];
  18468. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  18469. const renderer = this._renderer;
  18470. const originalAutoClear = renderer.autoClear;
  18471. renderer.getClearColor( _clearColor );
  18472. renderer.autoClear = false;
  18473. let backgroundBox = this._backgroundBox;
  18474. if ( backgroundBox === null ) {
  18475. const backgroundMaterial = new MeshBasicMaterial( {
  18476. name: 'PMREM.Background',
  18477. side: BackSide,
  18478. depthWrite: false,
  18479. depthTest: false
  18480. } );
  18481. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  18482. }
  18483. let useSolidColor = false;
  18484. const background = scene.background;
  18485. if ( background ) {
  18486. if ( background.isColor ) {
  18487. backgroundBox.material.color.copy( background );
  18488. scene.background = null;
  18489. useSolidColor = true;
  18490. }
  18491. } else {
  18492. backgroundBox.material.color.copy( _clearColor );
  18493. useSolidColor = true;
  18494. }
  18495. renderer.setRenderTarget( cubeUVRenderTarget );
  18496. renderer.clear();
  18497. if ( useSolidColor ) {
  18498. renderer.render( backgroundBox, cubeCamera );
  18499. }
  18500. for ( let i = 0; i < 6; i ++ ) {
  18501. const col = i % 3;
  18502. if ( col === 0 ) {
  18503. cubeCamera.up.set( 0, upSign[ i ], 0 );
  18504. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  18505. } else if ( col === 1 ) {
  18506. cubeCamera.up.set( 0, 0, upSign[ i ] );
  18507. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  18508. } else {
  18509. cubeCamera.up.set( 0, upSign[ i ], 0 );
  18510. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  18511. }
  18512. const size = this._cubeSize;
  18513. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  18514. renderer.render( scene, cubeCamera );
  18515. }
  18516. renderer.autoClear = originalAutoClear;
  18517. scene.background = background;
  18518. }
  18519. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  18520. const renderer = this._renderer;
  18521. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  18522. if ( isCubeTexture ) {
  18523. if ( this._cubemapMaterial === null ) {
  18524. this._cubemapMaterial = _getCubemapMaterial( texture );
  18525. }
  18526. } else {
  18527. if ( this._equirectMaterial === null ) {
  18528. this._equirectMaterial = _getEquirectMaterial( texture );
  18529. }
  18530. }
  18531. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  18532. material.fragmentNode.value = texture;
  18533. const mesh = this._lodMeshes[ 0 ];
  18534. mesh.material = material;
  18535. const size = this._cubeSize;
  18536. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  18537. renderer.setRenderTarget( cubeUVRenderTarget );
  18538. renderer.render( mesh, _flatCamera );
  18539. }
  18540. _applyPMREM( cubeUVRenderTarget ) {
  18541. const renderer = this._renderer;
  18542. const autoClear = renderer.autoClear;
  18543. renderer.autoClear = false;
  18544. const n = this._lodPlanes.length;
  18545. for ( let i = 1; i < n; i ++ ) {
  18546. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  18547. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  18548. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  18549. }
  18550. renderer.autoClear = autoClear;
  18551. }
  18552. /**
  18553. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  18554. * vertically and horizontally, but this breaks down on a cube. Here we apply
  18555. * the blur latitudinally (around the poles), and then longitudinally (towards
  18556. * the poles) to approximate the orthogonally-separable blur. It is least
  18557. * accurate at the poles, but still does a decent job.
  18558. */
  18559. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  18560. const pingPongRenderTarget = this._pingPongRenderTarget;
  18561. this._halfBlur(
  18562. cubeUVRenderTarget,
  18563. pingPongRenderTarget,
  18564. lodIn,
  18565. lodOut,
  18566. sigma,
  18567. 'latitudinal',
  18568. poleAxis );
  18569. this._halfBlur(
  18570. pingPongRenderTarget,
  18571. cubeUVRenderTarget,
  18572. lodOut,
  18573. lodOut,
  18574. sigma,
  18575. 'longitudinal',
  18576. poleAxis );
  18577. }
  18578. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  18579. const renderer = this._renderer;
  18580. const blurMaterial = this._blurMaterial;
  18581. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  18582. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  18583. }
  18584. // Number of standard deviations at which to cut off the discrete approximation.
  18585. const STANDARD_DEVIATIONS = 3;
  18586. const blurMesh = this._lodMeshes[ lodOut ];
  18587. blurMesh.material = blurMaterial;
  18588. const blurUniforms = blurMaterial.uniforms;
  18589. const pixels = this._sizeLods[ lodIn ] - 1;
  18590. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  18591. const sigmaPixels = sigmaRadians / radiansPerPixel;
  18592. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  18593. if ( samples > MAX_SAMPLES ) {
  18594. console.warn( `sigmaRadians, ${
  18595. sigmaRadians}, is too large and will clip, as it requested ${
  18596. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  18597. }
  18598. const weights = [];
  18599. let sum = 0;
  18600. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  18601. const x = i / sigmaPixels;
  18602. const weight = Math.exp( - x * x / 2 );
  18603. weights.push( weight );
  18604. if ( i === 0 ) {
  18605. sum += weight;
  18606. } else if ( i < samples ) {
  18607. sum += 2 * weight;
  18608. }
  18609. }
  18610. for ( let i = 0; i < weights.length; i ++ ) {
  18611. weights[ i ] = weights[ i ] / sum;
  18612. }
  18613. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  18614. blurUniforms.envMap.value = targetIn.texture;
  18615. blurUniforms.samples.value = samples;
  18616. blurUniforms.weights.array = weights;
  18617. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  18618. if ( poleAxis ) {
  18619. blurUniforms.poleAxis.value = poleAxis;
  18620. }
  18621. const { _lodMax } = this;
  18622. blurUniforms.dTheta.value = radiansPerPixel;
  18623. blurUniforms.mipInt.value = _lodMax - lodIn;
  18624. const outputSize = this._sizeLods[ lodOut ];
  18625. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  18626. const y = 4 * ( this._cubeSize - outputSize );
  18627. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  18628. renderer.setRenderTarget( targetOut );
  18629. renderer.render( blurMesh, _flatCamera );
  18630. }
  18631. }
  18632. function _createPlanes( lodMax ) {
  18633. const lodPlanes = [];
  18634. const sizeLods = [];
  18635. const sigmas = [];
  18636. const lodMeshes = [];
  18637. let lod = lodMax;
  18638. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  18639. for ( let i = 0; i < totalLods; i ++ ) {
  18640. const sizeLod = Math.pow( 2, lod );
  18641. sizeLods.push( sizeLod );
  18642. let sigma = 1.0 / sizeLod;
  18643. if ( i > lodMax - LOD_MIN ) {
  18644. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  18645. } else if ( i === 0 ) {
  18646. sigma = 0;
  18647. }
  18648. sigmas.push( sigma );
  18649. const texelSize = 1.0 / ( sizeLod - 2 );
  18650. const min = - texelSize;
  18651. const max = 1 + texelSize;
  18652. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  18653. const cubeFaces = 6;
  18654. const vertices = 6;
  18655. const positionSize = 3;
  18656. const uvSize = 2;
  18657. const faceIndexSize = 1;
  18658. const position = new Float32Array( positionSize * vertices * cubeFaces );
  18659. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  18660. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  18661. for ( let face = 0; face < cubeFaces; face ++ ) {
  18662. const x = ( face % 3 ) * 2 / 3 - 1;
  18663. const y = face > 2 ? 0 : - 1;
  18664. const coordinates = [
  18665. x, y, 0,
  18666. x + 2 / 3, y, 0,
  18667. x + 2 / 3, y + 1, 0,
  18668. x, y, 0,
  18669. x + 2 / 3, y + 1, 0,
  18670. x, y + 1, 0
  18671. ];
  18672. const faceIdx = _faceLib[ face ];
  18673. position.set( coordinates, positionSize * vertices * faceIdx );
  18674. uv.set( uv1, uvSize * vertices * faceIdx );
  18675. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  18676. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  18677. }
  18678. const planes = new BufferGeometry();
  18679. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  18680. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  18681. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  18682. lodPlanes.push( planes );
  18683. lodMeshes.push( new Mesh( planes, null ) );
  18684. if ( lod > LOD_MIN ) {
  18685. lod --;
  18686. }
  18687. }
  18688. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  18689. }
  18690. function _createRenderTarget( width, height, params ) {
  18691. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  18692. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  18693. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  18694. cubeUVRenderTarget.texture.isPMREMTexture = true;
  18695. cubeUVRenderTarget.scissorTest = true;
  18696. return cubeUVRenderTarget;
  18697. }
  18698. function _setViewport( target, x, y, width, height ) {
  18699. target.viewport.set( x, y, width, height );
  18700. target.scissor.set( x, y, width, height );
  18701. }
  18702. function _getMaterial( type ) {
  18703. const material = new NodeMaterial();
  18704. material.depthTest = false;
  18705. material.depthWrite = false;
  18706. material.blending = NoBlending;
  18707. material.name = `PMREM_${ type }`;
  18708. return material;
  18709. }
  18710. function _getBlurShader( lodMax, width, height ) {
  18711. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  18712. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  18713. const dTheta = uniform( 0 );
  18714. const n = float( MAX_SAMPLES );
  18715. const latitudinal = uniform( 0 ); // false, bool
  18716. const samples = uniform( 1 ); // int
  18717. const envMap = texture( null );
  18718. const mipInt = uniform( 0 ); // int
  18719. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  18720. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  18721. const CUBEUV_MAX_MIP = float( lodMax );
  18722. const materialUniforms = {
  18723. n,
  18724. latitudinal,
  18725. weights,
  18726. poleAxis,
  18727. outputDirection,
  18728. dTheta,
  18729. samples,
  18730. envMap,
  18731. mipInt,
  18732. CUBEUV_TEXEL_WIDTH,
  18733. CUBEUV_TEXEL_HEIGHT,
  18734. CUBEUV_MAX_MIP
  18735. };
  18736. const material = _getMaterial( 'blur' );
  18737. material.uniforms = materialUniforms; // TODO: Move to outside of the material
  18738. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  18739. return material;
  18740. }
  18741. function _getCubemapMaterial( envTexture ) {
  18742. const material = _getMaterial( 'cubemap' );
  18743. material.fragmentNode = cubeTexture( envTexture, outputDirection );
  18744. return material;
  18745. }
  18746. function _getEquirectMaterial( envTexture ) {
  18747. const material = _getMaterial( 'equirect' );
  18748. material.fragmentNode = texture( envTexture, equirectUV( outputDirection ), 0 );
  18749. return material;
  18750. }
  18751. const rendererCache = new WeakMap();
  18752. const typeFromArray = new Map( [
  18753. [ Int8Array, 'int' ],
  18754. [ Int16Array, 'int' ],
  18755. [ Int32Array, 'int' ],
  18756. [ Uint8Array, 'uint' ],
  18757. [ Uint16Array, 'uint' ],
  18758. [ Uint32Array, 'uint' ],
  18759. [ Float32Array, 'float' ]
  18760. ] );
  18761. const toFloat = ( value ) => {
  18762. if ( /e/g.test( value ) ) {
  18763. return String( value ).replace( /\+/g, '' );
  18764. } else {
  18765. value = Number( value );
  18766. return value + ( value % 1 ? '' : '.0' );
  18767. }
  18768. };
  18769. /**
  18770. * Base class for builders which generate a shader program based
  18771. * on a 3D object and its node material definition.
  18772. */
  18773. class NodeBuilder {
  18774. /**
  18775. * Constructs a new node builder.
  18776. *
  18777. * @param {Object3D} object - The 3D object.
  18778. * @param {Renderer} renderer - The current renderer.
  18779. * @param {NodeParser} parser - A reference to a node parser.
  18780. */
  18781. constructor( object, renderer, parser ) {
  18782. /**
  18783. * The 3D object.
  18784. *
  18785. * @type {Object3D}
  18786. */
  18787. this.object = object;
  18788. /**
  18789. * The material of the 3D object.
  18790. *
  18791. * @type {Material?}
  18792. */
  18793. this.material = ( object && object.material ) || null;
  18794. /**
  18795. * The geometry of the 3D object.
  18796. *
  18797. * @type {BufferGeometry?}
  18798. */
  18799. this.geometry = ( object && object.geometry ) || null;
  18800. /**
  18801. * The current renderer.
  18802. *
  18803. * @type {Renderer}
  18804. */
  18805. this.renderer = renderer;
  18806. /**
  18807. * A reference to a node parser.
  18808. *
  18809. * @type {NodeParser}
  18810. */
  18811. this.parser = parser;
  18812. /**
  18813. * The scene the 3D object belongs to.
  18814. *
  18815. * @type {Scene?}
  18816. * @default null
  18817. */
  18818. this.scene = null;
  18819. /**
  18820. * The camera the 3D object is rendered with.
  18821. *
  18822. * @type {Camera?}
  18823. * @default null
  18824. */
  18825. this.camera = null;
  18826. /**
  18827. * A list of all nodes the builder is processing
  18828. * for this 3D object.
  18829. *
  18830. * @type {Array<Node>}
  18831. */
  18832. this.nodes = [];
  18833. /**
  18834. * A list of all sequential nodes.
  18835. *
  18836. * @type {Array<Node>}
  18837. */
  18838. this.sequentialNodes = [];
  18839. /**
  18840. * A list of all nodes which {@link Node#update} method should be executed.
  18841. *
  18842. * @type {Array<Node>}
  18843. */
  18844. this.updateNodes = [];
  18845. /**
  18846. * A list of all nodes which {@link Node#updateBefore} method should be executed.
  18847. *
  18848. * @type {Array<Node>}
  18849. */
  18850. this.updateBeforeNodes = [];
  18851. /**
  18852. * A list of all nodes which {@link Node#updateAfter} method should be executed.
  18853. *
  18854. * @type {Array<Node>}
  18855. */
  18856. this.updateAfterNodes = [];
  18857. /**
  18858. * A dictionary that assigns each node to a unique hash.
  18859. *
  18860. * @type {Object<Number,Node>}
  18861. */
  18862. this.hashNodes = {};
  18863. /**
  18864. * A reference to a node material observer.
  18865. *
  18866. * @type {NodeMaterialObserver?}
  18867. * @default null
  18868. */
  18869. this.monitor = null;
  18870. /**
  18871. * A reference to the current lights node.
  18872. *
  18873. * @type {LightsNode?}
  18874. * @default null
  18875. */
  18876. this.lightsNode = null;
  18877. /**
  18878. * A reference to the current environment node.
  18879. *
  18880. * @type {Node?}
  18881. * @default null
  18882. */
  18883. this.environmentNode = null;
  18884. /**
  18885. * A reference to the current fog node.
  18886. *
  18887. * @type {FogNode?}
  18888. * @default null
  18889. */
  18890. this.fogNode = null;
  18891. /**
  18892. * The current clipping context.
  18893. *
  18894. * @type {ClippingContext?}
  18895. */
  18896. this.clippingContext = null;
  18897. /**
  18898. * The generated vertex shader.
  18899. *
  18900. * @type {String?}
  18901. */
  18902. this.vertexShader = null;
  18903. /**
  18904. * The generated fragment shader.
  18905. *
  18906. * @type {String?}
  18907. */
  18908. this.fragmentShader = null;
  18909. /**
  18910. * The generated compute shader.
  18911. *
  18912. * @type {String?}
  18913. */
  18914. this.computeShader = null;
  18915. /**
  18916. * Nodes used in the primary flow of code generation.
  18917. *
  18918. * @type {Object<String,Array<Node>>}
  18919. */
  18920. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  18921. /**
  18922. * Nodes code from `.flowNodes`.
  18923. *
  18924. * @type {Object<String,String>}
  18925. */
  18926. this.flowCode = { vertex: '', fragment: '', compute: '' };
  18927. /**
  18928. * This dictionary holds the node uniforms of the builder.
  18929. * The uniforms are maintained in an array for each shader stage.
  18930. *
  18931. * @type {Object}
  18932. */
  18933. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  18934. /**
  18935. * This dictionary holds the output structs of the builder.
  18936. * The structs are maintained in an array for each shader stage.
  18937. *
  18938. * @type {Object}
  18939. */
  18940. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  18941. /**
  18942. * This dictionary holds the bindings for each shader stage.
  18943. *
  18944. * @type {Object}
  18945. */
  18946. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  18947. /**
  18948. * This dictionary maintains the binding indices per bind group.
  18949. *
  18950. * @type {Object}
  18951. */
  18952. this.bindingsIndexes = {};
  18953. /**
  18954. * Reference to the array of bind groups.
  18955. *
  18956. * @type {Array<BindGroup>?}
  18957. */
  18958. this.bindGroups = null;
  18959. /**
  18960. * This array holds the node attributes of this builder
  18961. * created via {@link AttributeNode}.
  18962. *
  18963. * @type {Array<NodeAttribute>}
  18964. */
  18965. this.attributes = [];
  18966. /**
  18967. * This array holds the node attributes of this builder
  18968. * created via {@link BufferAttributeNode}.
  18969. *
  18970. * @type {Array<NodeAttribute>}
  18971. */
  18972. this.bufferAttributes = [];
  18973. /**
  18974. * This array holds the node varyings of this builder.
  18975. *
  18976. * @type {Array<NodeVarying>}
  18977. */
  18978. this.varyings = [];
  18979. /**
  18980. * This dictionary holds the (native) node codes of this builder.
  18981. * The codes are maintained in an array for each shader stage.
  18982. *
  18983. * @type {Object<String,Array<NodeCode>>}
  18984. */
  18985. this.codes = {};
  18986. /**
  18987. * This dictionary holds the node variables of this builder.
  18988. * The variables are maintained in an array for each shader stage.
  18989. *
  18990. * @type {Object<String,Array<NodeVar>>}
  18991. */
  18992. this.vars = {};
  18993. /**
  18994. * Current code flow.
  18995. * All code generated in this stack will be stored in `.flow`.
  18996. *
  18997. * @type {{code: String}}
  18998. */
  18999. this.flow = { code: '' };
  19000. /**
  19001. * A chain of nodes.
  19002. * Used to check recursive calls in node-graph.
  19003. *
  19004. * @type {Array<Node>}
  19005. */
  19006. this.chaining = [];
  19007. /**
  19008. * The current stack.
  19009. * This reflects the current process in the code block hierarchy,
  19010. * it is useful to know if the current process is inside a conditional for example.
  19011. *
  19012. * @type {StackNode}
  19013. */
  19014. this.stack = stack();
  19015. /**
  19016. * List of stack nodes.
  19017. * The current stack hierarchy is stored in an array.
  19018. *
  19019. * @type {Array<StackNode>}
  19020. */
  19021. this.stacks = [];
  19022. /**
  19023. * A tab value. Used for shader string generation.
  19024. *
  19025. * @type {String}
  19026. * @default '\t'
  19027. */
  19028. this.tab = '\t';
  19029. /**
  19030. * Reference to the current function node.
  19031. *
  19032. * @type {FunctionNode?}
  19033. * @default null
  19034. */
  19035. this.currentFunctionNode = null;
  19036. /**
  19037. * The builder's context.
  19038. *
  19039. * @type {Object}
  19040. */
  19041. this.context = {
  19042. material: this.material
  19043. };
  19044. /**
  19045. * The builder's cache.
  19046. *
  19047. * @type {NodeCache}
  19048. */
  19049. this.cache = new NodeCache();
  19050. /**
  19051. * Since the {@link NodeBuilder#cache} might be temporarily
  19052. * overwritten by other caches, this member retains the reference
  19053. * to the builder's own cache.
  19054. *
  19055. * @type {NodeCache}
  19056. * @default this.cache
  19057. */
  19058. this.globalCache = this.cache;
  19059. this.flowsData = new WeakMap();
  19060. /**
  19061. * The current shader stage.
  19062. *
  19063. * @type {('vertex'|'fragment'|'compute'|'any')?}
  19064. */
  19065. this.shaderStage = null;
  19066. /**
  19067. * The current build stage.
  19068. *
  19069. * @type {('setup'|'analyze'|'generate')?}
  19070. */
  19071. this.buildStage = null;
  19072. /**
  19073. * Whether comparison in shader code are generated with methods or not.
  19074. *
  19075. * @type {Boolean}
  19076. * @default false
  19077. */
  19078. this.useComparisonMethod = false;
  19079. }
  19080. /**
  19081. * Returns the bind groups of the current renderer.
  19082. *
  19083. * @return {ChainMap} The cache.
  19084. */
  19085. getBindGroupsCache() {
  19086. let bindGroupsCache = rendererCache.get( this.renderer );
  19087. if ( bindGroupsCache === undefined ) {
  19088. bindGroupsCache = new ChainMap();
  19089. rendererCache.set( this.renderer, bindGroupsCache );
  19090. }
  19091. return bindGroupsCache;
  19092. }
  19093. /**
  19094. * Factory method for creating an instance of {@link RenderTarget} with the given
  19095. * dimensions and options.
  19096. *
  19097. * @param {Number} width - The width of the render target.
  19098. * @param {Number} height - The height of the render target.
  19099. * @param {Object} options - The options of the render target.
  19100. * @return {RenderTarget} The render target.
  19101. */
  19102. createRenderTarget( width, height, options ) {
  19103. return new RenderTarget( width, height, options );
  19104. }
  19105. /**
  19106. * Factory method for creating an instance of {@link CubeRenderTarget} with the given
  19107. * dimensions and options.
  19108. *
  19109. * @param {Number} size - The size of the cube render target.
  19110. * @param {Object} options - The options of the cube render target.
  19111. * @return {CubeRenderTarget} The cube render target.
  19112. */
  19113. createCubeRenderTarget( size, options ) {
  19114. return new CubeRenderTarget( size, options );
  19115. }
  19116. /**
  19117. * Factory method for creating an instance of {@link PMREMGenerator}.
  19118. *
  19119. * @return {PMREMGenerator} The PMREM generator.
  19120. */
  19121. createPMREMGenerator() {
  19122. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  19123. return new PMREMGenerator( this.renderer );
  19124. }
  19125. /**
  19126. * Whether the given node is included in the internal array of nodes or not.
  19127. *
  19128. * @param {Node} node - The node to test.
  19129. * @return {Boolean} Whether the given node is included in the internal array of nodes or not.
  19130. */
  19131. includes( node ) {
  19132. return this.nodes.includes( node );
  19133. }
  19134. /**
  19135. * Returns a bind group for the given group name and binding.
  19136. *
  19137. * @private
  19138. * @param {String} groupName - The group name.
  19139. * @param {Array<NodeUniformsGroup>} bindings - List of bindings.
  19140. * @return {BindGroup} The bind group
  19141. */
  19142. _getBindGroup( groupName, bindings ) {
  19143. const bindGroupsCache = this.getBindGroupsCache();
  19144. //
  19145. const bindingsArray = [];
  19146. let sharedGroup = true;
  19147. for ( const binding of bindings ) {
  19148. bindingsArray.push( binding );
  19149. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  19150. }
  19151. //
  19152. let bindGroup;
  19153. if ( sharedGroup ) {
  19154. bindGroup = bindGroupsCache.get( bindingsArray );
  19155. if ( bindGroup === undefined ) {
  19156. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  19157. bindGroupsCache.set( bindingsArray, bindGroup );
  19158. }
  19159. } else {
  19160. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  19161. }
  19162. return bindGroup;
  19163. }
  19164. /**
  19165. * Returns an array of node uniform groups for the given group name and shader stage.
  19166. *
  19167. * @param {String} groupName - The group name.
  19168. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  19169. * @return {Array<NodeUniformsGroup>} The array of node uniform groups.
  19170. */
  19171. getBindGroupArray( groupName, shaderStage ) {
  19172. const bindings = this.bindings[ shaderStage ];
  19173. let bindGroup = bindings[ groupName ];
  19174. if ( bindGroup === undefined ) {
  19175. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  19176. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  19177. }
  19178. bindings[ groupName ] = bindGroup = [];
  19179. }
  19180. return bindGroup;
  19181. }
  19182. /**
  19183. * Returns a list bindings of all shader stages separated by groups.
  19184. *
  19185. * @return {Array<BindGroup>} The list of bindings.
  19186. */
  19187. getBindings() {
  19188. let bindingsGroups = this.bindGroups;
  19189. if ( bindingsGroups === null ) {
  19190. const groups = {};
  19191. const bindings = this.bindings;
  19192. for ( const shaderStage of shaderStages ) {
  19193. for ( const groupName in bindings[ shaderStage ] ) {
  19194. const uniforms = bindings[ shaderStage ][ groupName ];
  19195. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  19196. groupUniforms.push( ...uniforms );
  19197. }
  19198. }
  19199. bindingsGroups = [];
  19200. for ( const groupName in groups ) {
  19201. const group = groups[ groupName ];
  19202. const bindingsGroup = this._getBindGroup( groupName, group );
  19203. bindingsGroups.push( bindingsGroup );
  19204. }
  19205. this.bindGroups = bindingsGroups;
  19206. }
  19207. return bindingsGroups;
  19208. }
  19209. /**
  19210. * Sorts the bind groups and updates {@link NodeBuilder#bindingsIndexes}.
  19211. */
  19212. sortBindingGroups() {
  19213. const bindingsGroups = this.getBindings();
  19214. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  19215. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  19216. const bindingGroup = bindingsGroups[ i ];
  19217. this.bindingsIndexes[ bindingGroup.name ].group = i;
  19218. bindingGroup.index = i;
  19219. }
  19220. }
  19221. /**
  19222. * The builder maintains each node in a hash-based dictionary.
  19223. * This method sets the given node (value) with the given hash (key) into this dictionary.
  19224. *
  19225. * @param {Node} node - The node to add.
  19226. * @param {Number} hash - The hash of the node.
  19227. */
  19228. setHashNode( node, hash ) {
  19229. this.hashNodes[ hash ] = node;
  19230. }
  19231. /**
  19232. * Adds a node to this builder.
  19233. *
  19234. * @param {Node} node - The node to add.
  19235. */
  19236. addNode( node ) {
  19237. if ( this.nodes.includes( node ) === false ) {
  19238. this.nodes.push( node );
  19239. this.setHashNode( node, node.getHash( this ) );
  19240. }
  19241. }
  19242. /**
  19243. * It is used to add Nodes that will be used as FRAME and RENDER events,
  19244. * and need to follow a certain sequence in the calls to work correctly.
  19245. *
  19246. * @param {Node} node - The node to add.
  19247. */
  19248. addSequentialNode( node ) {
  19249. if ( this.sequentialNodes.includes( node ) === false ) {
  19250. this.sequentialNodes.push( node );
  19251. }
  19252. }
  19253. /**
  19254. * Checks the update types of nodes
  19255. */
  19256. buildUpdateNodes() {
  19257. for ( const node of this.nodes ) {
  19258. const updateType = node.getUpdateType();
  19259. if ( updateType !== NodeUpdateType.NONE ) {
  19260. this.updateNodes.push( node.getSelf() );
  19261. }
  19262. }
  19263. for ( const node of this.sequentialNodes ) {
  19264. const updateBeforeType = node.getUpdateBeforeType();
  19265. const updateAfterType = node.getUpdateAfterType();
  19266. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  19267. this.updateBeforeNodes.push( node.getSelf() );
  19268. }
  19269. if ( updateAfterType !== NodeUpdateType.NONE ) {
  19270. this.updateAfterNodes.push( node.getSelf() );
  19271. }
  19272. }
  19273. }
  19274. /**
  19275. * A reference the current node which is the
  19276. * last node in the chain of nodes.
  19277. *
  19278. * @type {Node}
  19279. */
  19280. get currentNode() {
  19281. return this.chaining[ this.chaining.length - 1 ];
  19282. }
  19283. /**
  19284. * Whether the given texture is filtered or not.
  19285. *
  19286. * @param {Texture} texture - The texture to check.
  19287. * @return {Boolean} Whether the given texture is filtered or not.
  19288. */
  19289. isFilteredTexture( texture ) {
  19290. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  19291. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  19292. }
  19293. /**
  19294. * Adds the given node to the internal node chain.
  19295. * This is used to check recursive calls in node-graph.
  19296. *
  19297. * @param {Node} node - The node to add.
  19298. */
  19299. addChain( node ) {
  19300. /*
  19301. if ( this.chaining.indexOf( node ) !== - 1 ) {
  19302. console.warn( 'Recursive node: ', node );
  19303. }
  19304. */
  19305. this.chaining.push( node );
  19306. }
  19307. /**
  19308. * Removes the given node from the internal node chain.
  19309. *
  19310. * @param {Node} node - The node to remove.
  19311. */
  19312. removeChain( node ) {
  19313. const lastChain = this.chaining.pop();
  19314. if ( lastChain !== node ) {
  19315. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  19316. }
  19317. }
  19318. /**
  19319. * Returns the native shader method name for a given generic name. E.g.
  19320. * the method name `textureDimensions` matches the WGSL name but must be
  19321. * resolved to `textureSize` in GLSL.
  19322. *
  19323. * @abstract
  19324. * @param {String} name - The method name to resolve.
  19325. * @return {String} The resolved method name.
  19326. */
  19327. getMethod( method ) {
  19328. return method;
  19329. }
  19330. /**
  19331. * Returns a node for the given hash, see {@link NodeBuilder#setHashNode}.
  19332. *
  19333. * @param {Number} hash - The hash of the node.
  19334. * @return {Node} The found node.
  19335. */
  19336. getNodeFromHash( hash ) {
  19337. return this.hashNodes[ hash ];
  19338. }
  19339. /**
  19340. * Adds the Node to a target flow so that it can generate code in the 'generate' process.
  19341. *
  19342. * @param {('vertex'|'fragment'|'compute')} shaderStage - The shader stage.
  19343. * @param {Node} node - The node to add.
  19344. * @return {Node} The node.
  19345. */
  19346. addFlow( shaderStage, node ) {
  19347. this.flowNodes[ shaderStage ].push( node );
  19348. return node;
  19349. }
  19350. /**
  19351. * Sets builder's context.
  19352. *
  19353. * @param {Object} context - The context to set.
  19354. */
  19355. setContext( context ) {
  19356. this.context = context;
  19357. }
  19358. /**
  19359. * Returns the builder's current context.
  19360. *
  19361. * @return {Object} The builder's current context.
  19362. */
  19363. getContext() {
  19364. return this.context;
  19365. }
  19366. /**
  19367. * Gets a context used in shader construction that can be shared across different materials.
  19368. * This is necessary since the renderer cache can reuse shaders generated in one material and use them in another.
  19369. *
  19370. * @return {Object} The builder's current context without material.
  19371. */
  19372. getSharedContext() {
  19373. ({ ...this.context });
  19374. return this.context;
  19375. }
  19376. /**
  19377. * Sets builder's cache.
  19378. *
  19379. * @param {NodeCache} cache - The cache to set.
  19380. */
  19381. setCache( cache ) {
  19382. this.cache = cache;
  19383. }
  19384. /**
  19385. * Returns the builder's current cache.
  19386. *
  19387. * @return {NodeCache} The builder's current cache.
  19388. */
  19389. getCache() {
  19390. return this.cache;
  19391. }
  19392. /**
  19393. * Returns a cache for the given node.
  19394. *
  19395. * @param {Node} Node - The node.
  19396. * @param {Boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  19397. * @return {NodeCache} The cache.
  19398. */
  19399. getCacheFromNode( node, parent = true ) {
  19400. const data = this.getDataFromNode( node );
  19401. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  19402. return data.cache;
  19403. }
  19404. /**
  19405. * Whether the requested feature is available or not.
  19406. *
  19407. * @abstract
  19408. * @param {String} name - The requested feature.
  19409. * @return {Boolean} Whether the requested feature is supported or not.
  19410. */
  19411. isAvailable( /*name*/ ) {
  19412. return false;
  19413. }
  19414. /**
  19415. * Returns the vertexIndex input variable as a native shader string.
  19416. *
  19417. * @abstract
  19418. * @return {String} The instanceIndex shader string.
  19419. */
  19420. getVertexIndex() {
  19421. console.warn( 'Abstract function.' );
  19422. }
  19423. /**
  19424. * Returns the instanceIndex input variable as a native shader string.
  19425. *
  19426. * @abstract
  19427. * @return {String} The instanceIndex shader string.
  19428. */
  19429. getInstanceIndex() {
  19430. console.warn( 'Abstract function.' );
  19431. }
  19432. /**
  19433. * Returns the drawIndex input variable as a native shader string.
  19434. * Only relevant for WebGL and its `WEBGL_multi_draw` extension.
  19435. *
  19436. * @abstract
  19437. * @return {String} The drawIndex shader string.
  19438. */
  19439. getDrawIndex() {
  19440. console.warn( 'Abstract function.' );
  19441. }
  19442. /**
  19443. * Returns the frontFacing input variable as a native shader string.
  19444. *
  19445. * @abstract
  19446. * @return {String} The frontFacing shader string.
  19447. */
  19448. getFrontFacing() {
  19449. console.warn( 'Abstract function.' );
  19450. }
  19451. /**
  19452. * Returns the fragCoord input variable as a native shader string.
  19453. *
  19454. * @abstract
  19455. * @return {String} The fragCoord shader string.
  19456. */
  19457. getFragCoord() {
  19458. console.warn( 'Abstract function.' );
  19459. }
  19460. /**
  19461. * Whether to flip texture data along its vertical axis or not. WebGL needs
  19462. * this method evaluate to `true`, WebGPU to `false`.
  19463. *
  19464. * @abstract
  19465. * @return {Boolean} Whether to flip texture data along its vertical axis or not.
  19466. */
  19467. isFlipY() {
  19468. return false;
  19469. }
  19470. /**
  19471. * Calling this method increases the usage count for the given node by one.
  19472. *
  19473. * @param {Node} Node - The node to increase the usage count for.
  19474. * @return {Number} The updated usage count.
  19475. */
  19476. increaseUsage( node ) {
  19477. const nodeData = this.getDataFromNode( node );
  19478. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  19479. return nodeData.usageCount;
  19480. }
  19481. /**
  19482. * Generates a texture sample shader string for the given texture data.
  19483. *
  19484. * @abstract
  19485. * @param {Texture} texture - The texture.
  19486. * @param {String} textureProperty - The texture property name.
  19487. * @param {String} uvSnippet - Snippet defining the texture coordinates.
  19488. * @return {String} The generated shader string.
  19489. */
  19490. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  19491. console.warn( 'Abstract function.' );
  19492. }
  19493. /**
  19494. * Generates a texture LOD shader string for the given texture data.
  19495. *
  19496. * @abstract
  19497. * @param {Texture} texture - The texture.
  19498. * @param {String} textureProperty - The texture property name.
  19499. * @param {String} uvSnippet - Snippet defining the texture coordinates.
  19500. * @param {String} levelSnippet - Snippet defining the mip level.
  19501. * @return {String} The generated shader string.
  19502. */
  19503. generateTextureLod( /* texture, textureProperty, uvSnippet, levelSnippet */ ) {
  19504. console.warn( 'Abstract function.' );
  19505. }
  19506. /**
  19507. * Generates the shader string for the given type and value.
  19508. *
  19509. * @param {String} type - The type.
  19510. * @param {Any?} [value=null] - The value.
  19511. * @return {String} The generated value as a shader string.
  19512. */
  19513. generateConst( type, value = null ) {
  19514. if ( value === null ) {
  19515. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  19516. else if ( type === 'bool' ) value = false;
  19517. else if ( type === 'color' ) value = new Color();
  19518. else if ( type === 'vec2' ) value = new Vector2();
  19519. else if ( type === 'vec3' ) value = new Vector3();
  19520. else if ( type === 'vec4' ) value = new Vector4();
  19521. }
  19522. if ( type === 'float' ) return toFloat( value );
  19523. if ( type === 'int' ) return `${ Math.round( value ) }`;
  19524. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  19525. if ( type === 'bool' ) return value ? 'true' : 'false';
  19526. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  19527. const typeLength = this.getTypeLength( type );
  19528. const componentType = this.getComponentType( type );
  19529. const generateConst = value => this.generateConst( componentType, value );
  19530. if ( typeLength === 2 ) {
  19531. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  19532. } else if ( typeLength === 3 ) {
  19533. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  19534. } else if ( typeLength === 4 ) {
  19535. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  19536. } else if ( typeLength > 4 && value && ( value.isMatrix3 || value.isMatrix4 ) ) {
  19537. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  19538. } else if ( typeLength > 4 ) {
  19539. return `${ this.getType( type ) }()`;
  19540. }
  19541. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  19542. }
  19543. /**
  19544. * It might be necessary to convert certain data types to different ones
  19545. * so this method can be used to hide the conversion.
  19546. *
  19547. * @param {String} type - The type.
  19548. * @return {String} The updated type.
  19549. */
  19550. getType( type ) {
  19551. if ( type === 'color' ) return 'vec3';
  19552. return type;
  19553. }
  19554. /**
  19555. * Whether the given attribute name is defined in the geometry or not.
  19556. *
  19557. * @param {String} name - The attribute name.
  19558. * @return {Boolean} Whether the given attribute name is defined in the geometry.
  19559. */
  19560. hasGeometryAttribute( name ) {
  19561. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  19562. }
  19563. /**
  19564. * Returns a node attribute for the given name and type.
  19565. *
  19566. * @param {String} name - The attribute's name.
  19567. * @param {String} type - The attribute's type.
  19568. * @return {NodeAttribute} The node attribute.
  19569. */
  19570. getAttribute( name, type ) {
  19571. const attributes = this.attributes;
  19572. // find attribute
  19573. for ( const attribute of attributes ) {
  19574. if ( attribute.name === name ) {
  19575. return attribute;
  19576. }
  19577. }
  19578. // create a new if no exist
  19579. const attribute = new NodeAttribute( name, type );
  19580. attributes.push( attribute );
  19581. return attribute;
  19582. }
  19583. /**
  19584. * Returns for the given node and shader stage the property name for the shader.
  19585. *
  19586. * @param {Node} node - The node.
  19587. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  19588. * @return {String} The property name.
  19589. */
  19590. getPropertyName( node/*, shaderStage*/ ) {
  19591. return node.name;
  19592. }
  19593. /**
  19594. * Whether the given type is a vector type or not.
  19595. *
  19596. * @param {String} type - The type to check.
  19597. * @return {Boolean} Whether the given type is a vector type or not.
  19598. */
  19599. isVector( type ) {
  19600. return /vec\d/.test( type );
  19601. }
  19602. /**
  19603. * Whether the given type is a matrix type or not.
  19604. *
  19605. * @param {String} type - The type to check.
  19606. * @return {Boolean} Whether the given type is a matrix type or not.
  19607. */
  19608. isMatrix( type ) {
  19609. return /mat\d/.test( type );
  19610. }
  19611. /**
  19612. * Whether the given type is a reference type or not.
  19613. *
  19614. * @param {String} type - The type to check.
  19615. * @return {Boolean} Whether the given type is a reference type or not.
  19616. */
  19617. isReference( type ) {
  19618. return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  19619. }
  19620. /**
  19621. * Whether the given texture needs a conversion to working color space.
  19622. *
  19623. * @abstract
  19624. * @param {Texture} texture - The texture to check.
  19625. * @return {Boolean} Whether a color space conversion is required or not.
  19626. */
  19627. needsToWorkingColorSpace( /*texture*/ ) {
  19628. return false;
  19629. }
  19630. /**
  19631. * Returns the component type of a given texture.
  19632. *
  19633. * @param {Texture} texture - The texture.
  19634. * @return {String} The component type.
  19635. */
  19636. getComponentTypeFromTexture( texture ) {
  19637. const type = texture.type;
  19638. if ( texture.isDataTexture ) {
  19639. if ( type === IntType ) return 'int';
  19640. if ( type === UnsignedIntType ) return 'uint';
  19641. }
  19642. return 'float';
  19643. }
  19644. /**
  19645. * Returns the element type for a given type.
  19646. *
  19647. * @param {String} type - The type.
  19648. * @return {String} The element type.
  19649. */
  19650. getElementType( type ) {
  19651. if ( type === 'mat2' ) return 'vec2';
  19652. if ( type === 'mat3' ) return 'vec3';
  19653. if ( type === 'mat4' ) return 'vec4';
  19654. return this.getComponentType( type );
  19655. }
  19656. /**
  19657. * Returns the component type for a given type.
  19658. *
  19659. * @param {String} type - The type.
  19660. * @return {String} The component type.
  19661. */
  19662. getComponentType( type ) {
  19663. type = this.getVectorType( type );
  19664. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  19665. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  19666. if ( componentType === null ) return null;
  19667. if ( componentType[ 1 ] === 'b' ) return 'bool';
  19668. if ( componentType[ 1 ] === 'i' ) return 'int';
  19669. if ( componentType[ 1 ] === 'u' ) return 'uint';
  19670. return 'float';
  19671. }
  19672. /**
  19673. * Returns the vector type for a given type.
  19674. *
  19675. * @param {String} type - The type.
  19676. * @return {String} The vector type.
  19677. */
  19678. getVectorType( type ) {
  19679. if ( type === 'color' ) return 'vec3';
  19680. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  19681. return type;
  19682. }
  19683. /**
  19684. * Returns the data type for the given the length and component type.
  19685. *
  19686. * @param {Number} length - The length.
  19687. * @param {String} [componentType='float'] - The component type.
  19688. * @return {String} The type.
  19689. */
  19690. getTypeFromLength( length, componentType = 'float' ) {
  19691. if ( length === 1 ) return componentType;
  19692. const baseType = getTypeFromLength( length );
  19693. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  19694. return prefix + baseType;
  19695. }
  19696. /**
  19697. * Returns the type for a given typed array.
  19698. *
  19699. * @param {TypedArray} type - The typed array.
  19700. * @return {String} The type.
  19701. */
  19702. getTypeFromArray( array ) {
  19703. return typeFromArray.get( array.constructor );
  19704. }
  19705. /**
  19706. * Returns the type for a given buffer attribute.
  19707. *
  19708. * @param {BufferAttribute} attribute - The buffer attribute.
  19709. * @return {String} The type.
  19710. */
  19711. getTypeFromAttribute( attribute ) {
  19712. let dataAttribute = attribute;
  19713. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  19714. const array = dataAttribute.array;
  19715. const itemSize = attribute.itemSize;
  19716. const normalized = attribute.normalized;
  19717. let arrayType;
  19718. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  19719. arrayType = this.getTypeFromArray( array );
  19720. }
  19721. return this.getTypeFromLength( itemSize, arrayType );
  19722. }
  19723. /**
  19724. * Returns the length for the given data type.
  19725. *
  19726. * @param {String} type - The data type.
  19727. * @return {Number} The length.
  19728. */
  19729. getTypeLength( type ) {
  19730. const vecType = this.getVectorType( type );
  19731. const vecNum = /vec([2-4])/.exec( vecType );
  19732. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  19733. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  19734. if ( /mat2/.test( type ) === true ) return 4;
  19735. if ( /mat3/.test( type ) === true ) return 9;
  19736. if ( /mat4/.test( type ) === true ) return 16;
  19737. return 0;
  19738. }
  19739. /**
  19740. * Returns the vector type for a given matrix type.
  19741. *
  19742. * @param {String} type - The matrix type.
  19743. * @return {String} The vector type.
  19744. */
  19745. getVectorFromMatrix( type ) {
  19746. return type.replace( 'mat', 'vec' );
  19747. }
  19748. /**
  19749. * For a given type this method changes the component type to the
  19750. * given value. E.g. `vec4` should be changed to the new component type
  19751. * `uint` which results in `uvec4`.
  19752. *
  19753. * @param {String} type - The type.
  19754. * @param {String} newComponentType - The new component type.
  19755. * @return {String} The new type.
  19756. */
  19757. changeComponentType( type, newComponentType ) {
  19758. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  19759. }
  19760. /**
  19761. * Returns the integer type pendant for the given type.
  19762. *
  19763. * @param {String} type - The type.
  19764. * @return {String} The integer type.
  19765. */
  19766. getIntegerType( type ) {
  19767. const componentType = this.getComponentType( type );
  19768. if ( componentType === 'int' || componentType === 'uint' ) return type;
  19769. return this.changeComponentType( type, 'int' );
  19770. }
  19771. /**
  19772. * Adds a stack node to the internal stack.
  19773. *
  19774. * @return {StackNode} The added stack node.
  19775. */
  19776. addStack() {
  19777. this.stack = stack( this.stack );
  19778. this.stacks.push( getCurrentStack() || this.stack );
  19779. setCurrentStack( this.stack );
  19780. return this.stack;
  19781. }
  19782. /**
  19783. * Removes the last stack node from the internal stack.
  19784. *
  19785. * @return {StackNode} The removed stack node.
  19786. */
  19787. removeStack() {
  19788. const lastStack = this.stack;
  19789. this.stack = lastStack.parent;
  19790. setCurrentStack( this.stacks.pop() );
  19791. return lastStack;
  19792. }
  19793. /**
  19794. * The builder maintains (cached) data for each node during the building process. This method
  19795. * can be used to get these data for a specific shader stage and cache.
  19796. *
  19797. * @param {Node} node - The node to get the data for.
  19798. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  19799. * @param {NodeCache?} cache - An optional cache.
  19800. * @return {Object} The node data.
  19801. */
  19802. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  19803. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  19804. let nodeData = cache.getData( node );
  19805. if ( nodeData === undefined ) {
  19806. nodeData = {};
  19807. cache.setData( node, nodeData );
  19808. }
  19809. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  19810. return nodeData[ shaderStage ];
  19811. }
  19812. /**
  19813. * Returns the properties for the given node and shader stage.
  19814. *
  19815. * @param {Node} node - The node to get the properties for.
  19816. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage='any'] - The shader stage.
  19817. * @return {Object} The node properties.
  19818. */
  19819. getNodeProperties( node, shaderStage = 'any' ) {
  19820. const nodeData = this.getDataFromNode( node, shaderStage );
  19821. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  19822. }
  19823. /**
  19824. * Returns an instance of {@link NodeAttribute} for the given buffer attribute node.
  19825. *
  19826. * @param {BufferAttributeNode} node - The buffer attribute node.
  19827. * @param {String} type - The node type.
  19828. * @return {NodeAttribute} The node attribute.
  19829. */
  19830. getBufferAttributeFromNode( node, type ) {
  19831. const nodeData = this.getDataFromNode( node );
  19832. let bufferAttribute = nodeData.bufferAttribute;
  19833. if ( bufferAttribute === undefined ) {
  19834. const index = this.uniforms.index ++;
  19835. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  19836. this.bufferAttributes.push( bufferAttribute );
  19837. nodeData.bufferAttribute = bufferAttribute;
  19838. }
  19839. return bufferAttribute;
  19840. }
  19841. /**
  19842. * Returns an instance of {@link StructTypeNode} for the given output struct node.
  19843. *
  19844. * @param {OutputStructNode} node - The output struct node.
  19845. * @param {Array<String>} types - The output struct types.
  19846. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  19847. * @return {StructTypeNode} The struct type attribute.
  19848. */
  19849. getStructTypeFromNode( node, types, shaderStage = this.shaderStage ) {
  19850. const nodeData = this.getDataFromNode( node, shaderStage );
  19851. let structType = nodeData.structType;
  19852. if ( structType === undefined ) {
  19853. const index = this.structs.index ++;
  19854. structType = new StructTypeNode( 'StructType' + index, types );
  19855. this.structs[ shaderStage ].push( structType );
  19856. nodeData.structType = structType;
  19857. }
  19858. return structType;
  19859. }
  19860. /**
  19861. * Returns an instance of {@link NodeUniform} for the given uniform node.
  19862. *
  19863. * @param {UniformNode} node - The uniform node.
  19864. * @param {String} type - The uniform type.
  19865. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  19866. * @param {String?} name - The name of the uniform.
  19867. * @return {NodeUniform} The node uniform.
  19868. */
  19869. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  19870. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  19871. let nodeUniform = nodeData.uniform;
  19872. if ( nodeUniform === undefined ) {
  19873. const index = this.uniforms.index ++;
  19874. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  19875. this.uniforms[ shaderStage ].push( nodeUniform );
  19876. nodeData.uniform = nodeUniform;
  19877. }
  19878. return nodeUniform;
  19879. }
  19880. /**
  19881. * Returns an instance of {@link NodeVar} for the given variable node.
  19882. *
  19883. * @param {VarNode} node - The variable node.
  19884. * @param {String?} name - The variable's name.
  19885. * @param {String} [type=node.getNodeType( this )] - The variable's type.
  19886. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  19887. * @return {NodeVar} The node variable.
  19888. */
  19889. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage ) {
  19890. const nodeData = this.getDataFromNode( node, shaderStage );
  19891. let nodeVar = nodeData.variable;
  19892. if ( nodeVar === undefined ) {
  19893. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  19894. if ( name === null ) name = 'nodeVar' + vars.length;
  19895. nodeVar = new NodeVar( name, type );
  19896. vars.push( nodeVar );
  19897. nodeData.variable = nodeVar;
  19898. }
  19899. return nodeVar;
  19900. }
  19901. /**
  19902. * Returns an instance of {@link NodeVarying} for the given varying node.
  19903. *
  19904. * @param {(VaryingNode|PropertyNode)} node - The varying node.
  19905. * @param {String?} name - The varying's name.
  19906. * @param {String} [type=node.getNodeType( this )] - The varying's type.
  19907. * @return {NodeVar} The node varying.
  19908. */
  19909. getVaryingFromNode( node, name = null, type = node.getNodeType( this ) ) {
  19910. const nodeData = this.getDataFromNode( node, 'any' );
  19911. let nodeVarying = nodeData.varying;
  19912. if ( nodeVarying === undefined ) {
  19913. const varyings = this.varyings;
  19914. const index = varyings.length;
  19915. if ( name === null ) name = 'nodeVarying' + index;
  19916. nodeVarying = new NodeVarying( name, type );
  19917. varyings.push( nodeVarying );
  19918. nodeData.varying = nodeVarying;
  19919. }
  19920. return nodeVarying;
  19921. }
  19922. /**
  19923. * Returns an instance of {@link NodeCode} for the given code node.
  19924. *
  19925. * @param {CodeNode} node - The code node.
  19926. * @param {String} type - The node type.
  19927. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  19928. * @return {NodeCode} The node code.
  19929. */
  19930. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  19931. const nodeData = this.getDataFromNode( node );
  19932. let nodeCode = nodeData.code;
  19933. if ( nodeCode === undefined ) {
  19934. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  19935. const index = codes.length;
  19936. nodeCode = new NodeCode( 'nodeCode' + index, type );
  19937. codes.push( nodeCode );
  19938. nodeData.code = nodeCode;
  19939. }
  19940. return nodeCode;
  19941. }
  19942. /**
  19943. * Adds a code flow based on the code-block hierarchy.
  19944. * This is used so that code-blocks like If,Else create their variables locally if the Node
  19945. * is only used inside one of these conditionals in the current shader stage.
  19946. *
  19947. * @param {Node} node - The node to add.
  19948. * @param {Node} nodeBlock - Node-based code-block. Usually 'ConditionalNode'.
  19949. */
  19950. addFlowCodeHierarchy( node, nodeBlock ) {
  19951. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  19952. let needsFlowCode = true;
  19953. let nodeBlockHierarchy = nodeBlock;
  19954. while ( nodeBlockHierarchy ) {
  19955. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  19956. needsFlowCode = false;
  19957. break;
  19958. }
  19959. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  19960. }
  19961. if ( needsFlowCode ) {
  19962. for ( const flowCode of flowCodes ) {
  19963. this.addLineFlowCode( flowCode );
  19964. }
  19965. }
  19966. }
  19967. /**
  19968. * Add a inline-code to the current flow code-block.
  19969. *
  19970. * @param {Node} node - The node to add.
  19971. * @param {String} code - The code to add.
  19972. * @param {Node} nodeBlock - Current ConditionalNode
  19973. */
  19974. addLineFlowCodeBlock( node, code, nodeBlock ) {
  19975. const nodeData = this.getDataFromNode( node );
  19976. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  19977. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  19978. flowCodes.push( code );
  19979. codeBlock.set( nodeBlock, true );
  19980. }
  19981. /**
  19982. * Add a inline-code to the current flow.
  19983. *
  19984. * @param {String} code - The code to add.
  19985. * @param {Node?} [node= null] - Optional Node, can help the system understand if the Node is part of a code-block.
  19986. * @return {NodeBuilder} A reference to this node builder.
  19987. */
  19988. addLineFlowCode( code, node = null ) {
  19989. if ( code === '' ) return this;
  19990. if ( node !== null && this.context.nodeBlock ) {
  19991. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  19992. }
  19993. code = this.tab + code;
  19994. if ( ! /;\s*$/.test( code ) ) {
  19995. code = code + ';\n';
  19996. }
  19997. this.flow.code += code;
  19998. return this;
  19999. }
  20000. /**
  20001. * Adds a code to the current code flow.
  20002. *
  20003. * @param {String} code - Shader code.
  20004. * @return {NodeBuilder} A reference to this node builder.
  20005. */
  20006. addFlowCode( code ) {
  20007. this.flow.code += code;
  20008. return this;
  20009. }
  20010. /**
  20011. * Add tab in the code that will be generated so that other snippets respect the current tabulation.
  20012. * Typically used in codes with If,Else.
  20013. *
  20014. * @return {NodeBuilder} A reference to this node builder.
  20015. */
  20016. addFlowTab() {
  20017. this.tab += '\t';
  20018. return this;
  20019. }
  20020. /**
  20021. * Removes a tab.
  20022. *
  20023. * @return {NodeBuilder} A reference to this node builder.
  20024. */
  20025. removeFlowTab() {
  20026. this.tab = this.tab.slice( 0, - 1 );
  20027. return this;
  20028. }
  20029. /**
  20030. * Gets the current flow data based on a Node.
  20031. *
  20032. * @param {Node} node - Node that the flow was started.
  20033. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  20034. * @return {Object} The flow data.
  20035. */
  20036. getFlowData( node/*, shaderStage*/ ) {
  20037. return this.flowsData.get( node );
  20038. }
  20039. /**
  20040. * Executes the node flow based on a root node to generate the final shader code.
  20041. *
  20042. * @param {Node} node - The node to execute.
  20043. * @return {Object} The code flow.
  20044. */
  20045. flowNode( node ) {
  20046. const output = node.getNodeType( this );
  20047. const flowData = this.flowChildNode( node, output );
  20048. this.flowsData.set( node, flowData );
  20049. return flowData;
  20050. }
  20051. /**
  20052. * Returns the native shader operator name for a given generic name.
  20053. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  20054. *
  20055. * @param {ShaderNodeInternal} shaderNode - The shader node to build the function node with.
  20056. * @return {FunctionNode} The build function node.
  20057. */
  20058. buildFunctionNode( shaderNode ) {
  20059. const fn = new FunctionNode();
  20060. const previous = this.currentFunctionNode;
  20061. this.currentFunctionNode = fn;
  20062. fn.code = this.buildFunctionCode( shaderNode );
  20063. this.currentFunctionNode = previous;
  20064. return fn;
  20065. }
  20066. /**
  20067. * Generates a code flow based on a TSL function: Fn().
  20068. *
  20069. * @param {ShaderNodeInternal} node - A function code will be generated based on the input.
  20070. * @return {Object}
  20071. */
  20072. flowShaderNode( shaderNode ) {
  20073. const layout = shaderNode.layout;
  20074. const inputs = {
  20075. [ Symbol.iterator ]() {
  20076. let index = 0;
  20077. const values = Object.values( this );
  20078. return {
  20079. next: () => ( {
  20080. value: values[ index ],
  20081. done: index ++ >= values.length
  20082. } )
  20083. };
  20084. }
  20085. };
  20086. for ( const input of layout.inputs ) {
  20087. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  20088. }
  20089. //
  20090. shaderNode.layout = null;
  20091. const callNode = shaderNode.call( inputs );
  20092. const flowData = this.flowStagesNode( callNode, layout.type );
  20093. shaderNode.layout = layout;
  20094. return flowData;
  20095. }
  20096. /**
  20097. * Runs the node flow through all the steps of creation, 'setup', 'analyze', 'generate'.
  20098. *
  20099. * @param {Node} node - The node to execute.
  20100. * @param {String?} output - Expected output type. For example 'vec3'.
  20101. * @return {Object}
  20102. */
  20103. flowStagesNode( node, output = null ) {
  20104. const previousFlow = this.flow;
  20105. const previousVars = this.vars;
  20106. const previousCache = this.cache;
  20107. const previousBuildStage = this.buildStage;
  20108. const previousStack = this.stack;
  20109. const flow = {
  20110. code: ''
  20111. };
  20112. this.flow = flow;
  20113. this.vars = {};
  20114. this.cache = new NodeCache();
  20115. this.stack = stack();
  20116. for ( const buildStage of defaultBuildStages ) {
  20117. this.setBuildStage( buildStage );
  20118. flow.result = node.build( this, output );
  20119. }
  20120. flow.vars = this.getVars( this.shaderStage );
  20121. this.flow = previousFlow;
  20122. this.vars = previousVars;
  20123. this.cache = previousCache;
  20124. this.stack = previousStack;
  20125. this.setBuildStage( previousBuildStage );
  20126. return flow;
  20127. }
  20128. /**
  20129. * Returns the native shader operator name for a given generic name.
  20130. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  20131. *
  20132. * @abstract
  20133. * @param {String} op - The operator name to resolve.
  20134. * @return {String} The resolved operator name.
  20135. */
  20136. getFunctionOperator( /* op */ ) {
  20137. return null;
  20138. }
  20139. /**
  20140. * Generates a code flow based on a child Node.
  20141. *
  20142. * @param {Node} node - The node to execute.
  20143. * @param {String?} output - Expected output type. For example 'vec3'.
  20144. * @return {Object} The code flow.
  20145. */
  20146. flowChildNode( node, output = null ) {
  20147. const previousFlow = this.flow;
  20148. const flow = {
  20149. code: ''
  20150. };
  20151. this.flow = flow;
  20152. flow.result = node.build( this, output );
  20153. this.flow = previousFlow;
  20154. return flow;
  20155. }
  20156. /**
  20157. * Executes a flow of code in a different stage.
  20158. *
  20159. * Some nodes like `varying()` have the ability to compute code in vertex-stage and
  20160. * return the value in fragment-stage even if it is being executed in an input fragment.
  20161. *
  20162. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  20163. * @param {Node} node - The node to execute.
  20164. * @param {String?} output - Expected output type. For example 'vec3'.
  20165. * @param {String?} propertyName - The property name to assign the result.
  20166. * @return {Object}
  20167. */
  20168. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  20169. const previousShaderStage = this.shaderStage;
  20170. this.setShaderStage( shaderStage );
  20171. const flowData = this.flowChildNode( node, output );
  20172. if ( propertyName !== null ) {
  20173. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  20174. }
  20175. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  20176. this.setShaderStage( previousShaderStage );
  20177. return flowData;
  20178. }
  20179. /**
  20180. * Returns an array holding all node attributes of this node builder.
  20181. *
  20182. * @return {Array<NodeAttribute>} The node attributes of this builder.
  20183. */
  20184. getAttributesArray() {
  20185. return this.attributes.concat( this.bufferAttributes );
  20186. }
  20187. /**
  20188. * Returns the attribute definitions as a shader string for the given shader stage.
  20189. *
  20190. * @abstract
  20191. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  20192. * @return {String} The attribute code section.
  20193. */
  20194. getAttributes( /*shaderStage*/ ) {
  20195. console.warn( 'Abstract function.' );
  20196. }
  20197. /**
  20198. * Returns the varying definitions as a shader string for the given shader stage.
  20199. *
  20200. * @abstract
  20201. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  20202. * @return {String} The varying code section.
  20203. */
  20204. getVaryings( /*shaderStage*/ ) {
  20205. console.warn( 'Abstract function.' );
  20206. }
  20207. /**
  20208. * Returns a single variable definition as a shader string for the given variable type and name.
  20209. *
  20210. * @param {String} type - The variable's type.
  20211. * @param {String} name - The variable's name.
  20212. * @return {String} The shader string.
  20213. */
  20214. getVar( type, name ) {
  20215. return `${ this.getType( type ) } ${ name }`;
  20216. }
  20217. /**
  20218. * Returns the variable definitions as a shader string for the given shader stage.
  20219. *
  20220. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  20221. * @return {String} The variable code section.
  20222. */
  20223. getVars( shaderStage ) {
  20224. let snippet = '';
  20225. const vars = this.vars[ shaderStage ];
  20226. if ( vars !== undefined ) {
  20227. for ( const variable of vars ) {
  20228. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  20229. }
  20230. }
  20231. return snippet;
  20232. }
  20233. /**
  20234. * Returns the uniform definitions as a shader string for the given shader stage.
  20235. *
  20236. * @abstract
  20237. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  20238. * @return {String} The uniform code section.
  20239. */
  20240. getUniforms( /*shaderStage*/ ) {
  20241. console.warn( 'Abstract function.' );
  20242. }
  20243. /**
  20244. * Returns the native code definitions as a shader string for the given shader stage.
  20245. *
  20246. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  20247. * @return {String} The native code section.
  20248. */
  20249. getCodes( shaderStage ) {
  20250. const codes = this.codes[ shaderStage ];
  20251. let code = '';
  20252. if ( codes !== undefined ) {
  20253. for ( const nodeCode of codes ) {
  20254. code += nodeCode.code + '\n';
  20255. }
  20256. }
  20257. return code;
  20258. }
  20259. /**
  20260. * Returns the hash of this node builder.
  20261. *
  20262. * @return {String} The hash.
  20263. */
  20264. getHash() {
  20265. return this.vertexShader + this.fragmentShader + this.computeShader;
  20266. }
  20267. /**
  20268. * Sets the current shader stage.
  20269. *
  20270. * @param {('vertex'|'fragment'|'compute'|'any')?} shaderStage - The shader stage to set.
  20271. */
  20272. setShaderStage( shaderStage ) {
  20273. this.shaderStage = shaderStage;
  20274. }
  20275. /**
  20276. * Returns the current shader stage.
  20277. *
  20278. * @return {('vertex'|'fragment'|'compute'|'any')?} The current shader stage.
  20279. */
  20280. getShaderStage() {
  20281. return this.shaderStage;
  20282. }
  20283. /**
  20284. * Sets the current build stage.
  20285. *
  20286. * @param {('setup'|'analyze'|'generate')?} buildStage - The build stage to set.
  20287. */
  20288. setBuildStage( buildStage ) {
  20289. this.buildStage = buildStage;
  20290. }
  20291. /**
  20292. * Returns the current build stage.
  20293. *
  20294. * @return {('setup'|'analyze'|'generate')?} The current build stage.
  20295. */
  20296. getBuildStage() {
  20297. return this.buildStage;
  20298. }
  20299. /**
  20300. * Controls the code build of the shader stages.
  20301. *
  20302. * @abstract
  20303. */
  20304. buildCode() {
  20305. console.warn( 'Abstract function.' );
  20306. }
  20307. /**
  20308. * Central build method which controls the build for the given object.
  20309. *
  20310. * @return {NodeBuilder} A reference to this node builder.
  20311. */
  20312. build() {
  20313. const { object, material, renderer } = this;
  20314. if ( material !== null ) {
  20315. let nodeMaterial = renderer.library.fromMaterial( material );
  20316. if ( nodeMaterial === null ) {
  20317. console.error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  20318. nodeMaterial = new NodeMaterial();
  20319. }
  20320. nodeMaterial.build( this );
  20321. } else {
  20322. this.addFlow( 'compute', object );
  20323. }
  20324. // setup() -> stage 1: create possible new nodes and returns an output reference node
  20325. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  20326. // generate() -> stage 3: generate shader
  20327. for ( const buildStage of defaultBuildStages ) {
  20328. this.setBuildStage( buildStage );
  20329. if ( this.context.vertex && this.context.vertex.isNode ) {
  20330. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  20331. }
  20332. for ( const shaderStage of shaderStages ) {
  20333. this.setShaderStage( shaderStage );
  20334. const flowNodes = this.flowNodes[ shaderStage ];
  20335. for ( const node of flowNodes ) {
  20336. if ( buildStage === 'generate' ) {
  20337. this.flowNode( node );
  20338. } else {
  20339. node.build( this );
  20340. }
  20341. }
  20342. }
  20343. }
  20344. this.setBuildStage( null );
  20345. this.setShaderStage( null );
  20346. // stage 4: build code for a specific output
  20347. this.buildCode();
  20348. this.buildUpdateNodes();
  20349. return this;
  20350. }
  20351. /**
  20352. * Returns a uniform representation which is later used for UBO generation and rendering.
  20353. *
  20354. * @param {NodeUniform} uniformNode - The uniform node.
  20355. * @param {String} type - The requested type.
  20356. * @return {Uniform} The uniform.
  20357. */
  20358. getNodeUniform( uniformNode, type ) {
  20359. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  20360. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  20361. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  20362. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  20363. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  20364. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  20365. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  20366. throw new Error( `Uniform "${type}" not declared.` );
  20367. }
  20368. /**
  20369. * Formats the given shader snippet from a given type into another one. E.g.
  20370. * this method might be used to convert a simple float string `"1.0"` into a
  20371. * `vec3` representation: `"vec3<f32>( 1.0 )"`.
  20372. *
  20373. * @param {String} snippet - The shader snippet.
  20374. * @param {String} fromType - The source type.
  20375. * @param {String} toType - The target type.
  20376. * @return {String} The updated shader string.
  20377. */
  20378. format( snippet, fromType, toType ) {
  20379. fromType = this.getVectorType( fromType );
  20380. toType = this.getVectorType( toType );
  20381. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  20382. return snippet;
  20383. }
  20384. const fromTypeLength = this.getTypeLength( fromType );
  20385. const toTypeLength = this.getTypeLength( toType );
  20386. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  20387. return `${ this.getType( toType ) }(${ snippet }[0].xyz, ${ snippet }[1].xyz, ${ snippet }[2].xyz)`;
  20388. }
  20389. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  20390. return `${ this.getType( toType ) }(${ snippet }[0].xy, ${ snippet }[1].xy)`;
  20391. }
  20392. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  20393. // @TODO: ignore for now
  20394. return snippet;
  20395. }
  20396. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  20397. // @TODO: ignore for now
  20398. return snippet;
  20399. }
  20400. if ( fromTypeLength === toTypeLength ) {
  20401. return `${ this.getType( toType ) }( ${ snippet } )`;
  20402. }
  20403. if ( fromTypeLength > toTypeLength ) {
  20404. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  20405. }
  20406. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  20407. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  20408. }
  20409. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  20410. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  20411. }
  20412. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  20413. // convert a number value to vector type, e.g:
  20414. // vec3( 1u ) -> vec3( float( 1u ) )
  20415. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  20416. }
  20417. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  20418. }
  20419. /**
  20420. * Returns a signature with the engine's current revision.
  20421. *
  20422. * @return {String} The signature.
  20423. */
  20424. getSignature() {
  20425. return `// Three.js r${ REVISION } - Node System\n`;
  20426. }
  20427. // deprecated
  20428. createNodeMaterial( type = 'NodeMaterial' ) { // @deprecated, r168
  20429. throw new Error( `THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${ type }() instead.` );
  20430. }
  20431. }
  20432. /**
  20433. * Management class for updating nodes. The module tracks metrics like
  20434. * the elapsed time, delta time, the render and frame ID to correctly
  20435. * call the node update methods {@link Node#updateBefore}, {@link Node#update}
  20436. * and {@link Node#updateAfter} depending on the node's configuration.
  20437. */
  20438. class NodeFrame {
  20439. /**
  20440. * Constructs a new node fame.
  20441. */
  20442. constructor() {
  20443. /**
  20444. * The elapsed time in seconds.
  20445. *
  20446. * @type {Number}
  20447. * @default 0
  20448. */
  20449. this.time = 0;
  20450. /**
  20451. * The delta time in seconds.
  20452. *
  20453. * @type {Number}
  20454. * @default 0
  20455. */
  20456. this.deltaTime = 0;
  20457. /**
  20458. * The frame ID.
  20459. *
  20460. * @type {Number}
  20461. * @default 0
  20462. */
  20463. this.frameId = 0;
  20464. /**
  20465. * The render ID.
  20466. *
  20467. * @type {Number}
  20468. * @default 0
  20469. */
  20470. this.renderId = 0;
  20471. /**
  20472. * Used to control the {@link Node#update} call.
  20473. *
  20474. * @type {WeakMap}
  20475. */
  20476. this.updateMap = new WeakMap();
  20477. /**
  20478. * Used to control the {@link Node#updateBefore} call.
  20479. *
  20480. * @type {WeakMap}
  20481. */
  20482. this.updateBeforeMap = new WeakMap();
  20483. /**
  20484. * Used to control the {@link Node#updateAfter} call.
  20485. *
  20486. * @type {WeakMap}
  20487. */
  20488. this.updateAfterMap = new WeakMap();
  20489. /**
  20490. * A reference to the current renderer.
  20491. *
  20492. * @type {Renderer?}
  20493. * @default null
  20494. */
  20495. this.renderer = null;
  20496. /**
  20497. * A reference to the current material.
  20498. *
  20499. * @type {Material?}
  20500. * @default null
  20501. */
  20502. this.material = null;
  20503. /**
  20504. * A reference to the current camera.
  20505. *
  20506. * @type {Camera?}
  20507. * @default null
  20508. */
  20509. this.camera = null;
  20510. /**
  20511. * A reference to the current 3D object.
  20512. *
  20513. * @type {Object3D?}
  20514. * @default null
  20515. */
  20516. this.object = null;
  20517. /**
  20518. * A reference to the current scene.
  20519. *
  20520. * @type {Scene?}
  20521. * @default null
  20522. */
  20523. this.scene = null;
  20524. }
  20525. /**
  20526. * Returns a dictionary for a given node and update map which
  20527. * is used to correctly call node update methods per frame or render.
  20528. *
  20529. * @private
  20530. * @param {WeakMap} referenceMap - The reference weak map.
  20531. * @param {Node} nodeRef - The reference to the current node.
  20532. * @return {Object<String,WeakMap>} The dictionary.
  20533. */
  20534. _getMaps( referenceMap, nodeRef ) {
  20535. let maps = referenceMap.get( nodeRef );
  20536. if ( maps === undefined ) {
  20537. maps = {
  20538. renderMap: new WeakMap(),
  20539. frameMap: new WeakMap()
  20540. };
  20541. referenceMap.set( nodeRef, maps );
  20542. }
  20543. return maps;
  20544. }
  20545. /**
  20546. * This method executes the {@link Node#updateBefore} for the given node.
  20547. * It makes sure {@link Node#updateBeforeType} is honored meaning the update
  20548. * is only executed once per frame, render or object depending on the update
  20549. * type.
  20550. *
  20551. * @param {Node} node - The node that should be updated.
  20552. */
  20553. updateBeforeNode( node ) {
  20554. const updateType = node.getUpdateBeforeType();
  20555. const reference = node.updateReference( this );
  20556. if ( updateType === NodeUpdateType.FRAME ) {
  20557. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  20558. if ( frameMap.get( reference ) !== this.frameId ) {
  20559. if ( node.updateBefore( this ) !== false ) {
  20560. frameMap.set( reference, this.frameId );
  20561. }
  20562. }
  20563. } else if ( updateType === NodeUpdateType.RENDER ) {
  20564. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  20565. if ( renderMap.get( reference ) !== this.renderId ) {
  20566. if ( node.updateBefore( this ) !== false ) {
  20567. renderMap.set( reference, this.renderId );
  20568. }
  20569. }
  20570. } else if ( updateType === NodeUpdateType.OBJECT ) {
  20571. node.updateBefore( this );
  20572. }
  20573. }
  20574. /**
  20575. * This method executes the {@link Node#updateAfter} for the given node.
  20576. * It makes sure {@link Node#updateAfterType} is honored meaning the update
  20577. * is only executed once per frame, render or object depending on the update
  20578. * type.
  20579. *
  20580. * @param {Node} node - The node that should be updated.
  20581. */
  20582. updateAfterNode( node ) {
  20583. const updateType = node.getUpdateAfterType();
  20584. const reference = node.updateReference( this );
  20585. if ( updateType === NodeUpdateType.FRAME ) {
  20586. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  20587. if ( frameMap.get( reference ) !== this.frameId ) {
  20588. if ( node.updateAfter( this ) !== false ) {
  20589. frameMap.set( reference, this.frameId );
  20590. }
  20591. }
  20592. } else if ( updateType === NodeUpdateType.RENDER ) {
  20593. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  20594. if ( renderMap.get( reference ) !== this.renderId ) {
  20595. if ( node.updateAfter( this ) !== false ) {
  20596. renderMap.set( reference, this.renderId );
  20597. }
  20598. }
  20599. } else if ( updateType === NodeUpdateType.OBJECT ) {
  20600. node.updateAfter( this );
  20601. }
  20602. }
  20603. /**
  20604. * This method executes the {@link Node#update} for the given node.
  20605. * It makes sure {@link Node#updateType} is honored meaning the update
  20606. * is only executed once per frame, render or object depending on the update
  20607. * type.
  20608. *
  20609. * @param {Node} node - The node that should be updated.
  20610. */
  20611. updateNode( node ) {
  20612. const updateType = node.getUpdateType();
  20613. const reference = node.updateReference( this );
  20614. if ( updateType === NodeUpdateType.FRAME ) {
  20615. const { frameMap } = this._getMaps( this.updateMap, reference );
  20616. if ( frameMap.get( reference ) !== this.frameId ) {
  20617. if ( node.update( this ) !== false ) {
  20618. frameMap.set( reference, this.frameId );
  20619. }
  20620. }
  20621. } else if ( updateType === NodeUpdateType.RENDER ) {
  20622. const { renderMap } = this._getMaps( this.updateMap, reference );
  20623. if ( renderMap.get( reference ) !== this.renderId ) {
  20624. if ( node.update( this ) !== false ) {
  20625. renderMap.set( reference, this.renderId );
  20626. }
  20627. }
  20628. } else if ( updateType === NodeUpdateType.OBJECT ) {
  20629. node.update( this );
  20630. }
  20631. }
  20632. /**
  20633. * Updates the internal state of the node frame. This method is
  20634. * called by the renderer in its internal animation loop.
  20635. */
  20636. update() {
  20637. this.frameId ++;
  20638. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  20639. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  20640. this.lastTime = performance.now();
  20641. this.time += this.deltaTime;
  20642. }
  20643. }
  20644. /**
  20645. * Describes the input of a {@link NodeFunction}.
  20646. */
  20647. class NodeFunctionInput {
  20648. /**
  20649. * Constructs a new node function input.
  20650. *
  20651. * @param {String} type - The input type.
  20652. * @param {String} name - The input name.
  20653. * @param {Number?} [count=null] - If the input is an Array, count will be the length.
  20654. * @param {('in'|'out'|'inout')} [qualifier=''] - The parameter qualifier (only relevant for GLSL).
  20655. * @param {Boolean} [isConst=false] - Whether the input uses a const qualifier or not (only relevant for GLSL).
  20656. */
  20657. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  20658. /**
  20659. * The input type.
  20660. *
  20661. * @type {String}
  20662. */
  20663. this.type = type;
  20664. /**
  20665. * The input name.
  20666. *
  20667. * @type {String}
  20668. */
  20669. this.name = name;
  20670. /**
  20671. * If the input is an Array, count will be the length.
  20672. *
  20673. * @type {Number?}
  20674. * @default null
  20675. */
  20676. this.count = count;
  20677. /**
  20678. *The parameter qualifier (only relevant for GLSL).
  20679. *
  20680. * @type {('in'|'out'|'inout')}
  20681. * @default ''
  20682. */
  20683. this.qualifier = qualifier;
  20684. /**
  20685. * Whether the input uses a const qualifier or not (only relevant for GLSL).
  20686. *
  20687. * @type {Boolean}
  20688. * @default false
  20689. */
  20690. this.isConst = isConst;
  20691. }
  20692. }
  20693. NodeFunctionInput.isNodeFunctionInput = true;
  20694. class DirectionalLightNode extends AnalyticLightNode {
  20695. static get type() {
  20696. return 'DirectionalLightNode';
  20697. }
  20698. constructor( light = null ) {
  20699. super( light );
  20700. }
  20701. setup( builder ) {
  20702. super.setup( builder );
  20703. const lightingModel = builder.context.lightingModel;
  20704. const lightColor = this.colorNode;
  20705. const lightDirection = lightTargetDirection( this.light );
  20706. const reflectedLight = builder.context.reflectedLight;
  20707. lightingModel.direct( {
  20708. lightDirection,
  20709. lightColor,
  20710. reflectedLight
  20711. }, builder.stack, builder );
  20712. }
  20713. }
  20714. const _matrix41 = /*@__PURE__*/ new Matrix4();
  20715. const _matrix42 = /*@__PURE__*/ new Matrix4();
  20716. let ltcLib = null;
  20717. class RectAreaLightNode extends AnalyticLightNode {
  20718. static get type() {
  20719. return 'RectAreaLightNode';
  20720. }
  20721. constructor( light = null ) {
  20722. super( light );
  20723. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  20724. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  20725. this.updateType = NodeUpdateType.RENDER;
  20726. }
  20727. update( frame ) {
  20728. super.update( frame );
  20729. const { light } = this;
  20730. const viewMatrix = frame.camera.matrixWorldInverse;
  20731. _matrix42.identity();
  20732. _matrix41.copy( light.matrixWorld );
  20733. _matrix41.premultiply( viewMatrix );
  20734. _matrix42.extractRotation( _matrix41 );
  20735. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  20736. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  20737. this.halfWidth.value.applyMatrix4( _matrix42 );
  20738. this.halfHeight.value.applyMatrix4( _matrix42 );
  20739. }
  20740. setup( builder ) {
  20741. super.setup( builder );
  20742. let ltc_1, ltc_2;
  20743. if ( builder.isAvailable( 'float32Filterable' ) ) {
  20744. ltc_1 = texture( ltcLib.LTC_FLOAT_1 );
  20745. ltc_2 = texture( ltcLib.LTC_FLOAT_2 );
  20746. } else {
  20747. ltc_1 = texture( ltcLib.LTC_HALF_1 );
  20748. ltc_2 = texture( ltcLib.LTC_HALF_2 );
  20749. }
  20750. const { colorNode, light } = this;
  20751. const lightingModel = builder.context.lightingModel;
  20752. const lightPosition = lightViewPosition( light );
  20753. const reflectedLight = builder.context.reflectedLight;
  20754. lightingModel.directRectArea( {
  20755. lightColor: colorNode,
  20756. lightPosition,
  20757. halfWidth: this.halfWidth,
  20758. halfHeight: this.halfHeight,
  20759. reflectedLight,
  20760. ltc_1,
  20761. ltc_2
  20762. }, builder.stack, builder );
  20763. }
  20764. static setLTC( ltc ) {
  20765. ltcLib = ltc;
  20766. }
  20767. }
  20768. class SpotLightNode extends AnalyticLightNode {
  20769. static get type() {
  20770. return 'SpotLightNode';
  20771. }
  20772. constructor( light = null ) {
  20773. super( light );
  20774. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  20775. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  20776. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  20777. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  20778. }
  20779. update( frame ) {
  20780. super.update( frame );
  20781. const { light } = this;
  20782. this.coneCosNode.value = Math.cos( light.angle );
  20783. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  20784. this.cutoffDistanceNode.value = light.distance;
  20785. this.decayExponentNode.value = light.decay;
  20786. }
  20787. getSpotAttenuation( angleCosine ) {
  20788. const { coneCosNode, penumbraCosNode } = this;
  20789. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  20790. }
  20791. setup( builder ) {
  20792. super.setup( builder );
  20793. const lightingModel = builder.context.lightingModel;
  20794. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  20795. const lVector = lightViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  20796. const lightDirection = lVector.normalize();
  20797. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  20798. const spotAttenuation = this.getSpotAttenuation( angleCos );
  20799. const lightDistance = lVector.length();
  20800. const lightAttenuation = getDistanceAttenuation( {
  20801. lightDistance,
  20802. cutoffDistance: cutoffDistanceNode,
  20803. decayExponent: decayExponentNode
  20804. } );
  20805. let lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  20806. if ( light.map ) {
  20807. const spotLightCoord = lightProjectionUV( light );
  20808. const projectedTexture = texture( light.map, spotLightCoord.xy ).onRenderUpdate( () => light.map );
  20809. const inSpotLightMap = spotLightCoord.mul( 2. ).sub( 1. ).abs().lessThan( 1. ).all();
  20810. lightColor = inSpotLightMap.select( lightColor.mul( projectedTexture ), lightColor );
  20811. }
  20812. const reflectedLight = builder.context.reflectedLight;
  20813. lightingModel.direct( {
  20814. lightDirection,
  20815. lightColor,
  20816. reflectedLight
  20817. }, builder.stack, builder );
  20818. }
  20819. }
  20820. class IESSpotLightNode extends SpotLightNode {
  20821. static get type() {
  20822. return 'IESSpotLightNode';
  20823. }
  20824. getSpotAttenuation( angleCosine ) {
  20825. const iesMap = this.light.iesMap;
  20826. let spotAttenuation = null;
  20827. if ( iesMap && iesMap.isTexture === true ) {
  20828. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  20829. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  20830. } else {
  20831. spotAttenuation = super.getSpotAttenuation( angleCosine );
  20832. }
  20833. return spotAttenuation;
  20834. }
  20835. }
  20836. class AmbientLightNode extends AnalyticLightNode {
  20837. static get type() {
  20838. return 'AmbientLightNode';
  20839. }
  20840. constructor( light = null ) {
  20841. super( light );
  20842. }
  20843. setup( { context } ) {
  20844. context.irradiance.addAssign( this.colorNode );
  20845. }
  20846. }
  20847. class HemisphereLightNode extends AnalyticLightNode {
  20848. static get type() {
  20849. return 'HemisphereLightNode';
  20850. }
  20851. constructor( light = null ) {
  20852. super( light );
  20853. this.lightPositionNode = lightPosition( light );
  20854. this.lightDirectionNode = this.lightPositionNode.normalize();
  20855. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  20856. }
  20857. update( frame ) {
  20858. const { light } = this;
  20859. super.update( frame );
  20860. this.lightPositionNode.object3d = light;
  20861. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  20862. }
  20863. setup( builder ) {
  20864. const { colorNode, groundColorNode, lightDirectionNode } = this;
  20865. const dotNL = normalView.dot( lightDirectionNode );
  20866. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  20867. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  20868. builder.context.irradiance.addAssign( irradiance );
  20869. }
  20870. }
  20871. class LightProbeNode extends AnalyticLightNode {
  20872. static get type() {
  20873. return 'LightProbeNode';
  20874. }
  20875. constructor( light = null ) {
  20876. super( light );
  20877. const array = [];
  20878. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  20879. this.lightProbe = uniformArray( array );
  20880. }
  20881. update( frame ) {
  20882. const { light } = this;
  20883. super.update( frame );
  20884. //
  20885. for ( let i = 0; i < 9; i ++ ) {
  20886. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  20887. }
  20888. }
  20889. setup( builder ) {
  20890. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  20891. builder.context.irradiance.addAssign( irradiance );
  20892. }
  20893. }
  20894. /**
  20895. * Base class for node parsers. A derived parser must be implemented
  20896. * for each supported native shader language.
  20897. */
  20898. class NodeParser {
  20899. /**
  20900. * The method parses the given native code an returns a node function.
  20901. *
  20902. * @abstract
  20903. * @param {String} source - The native shader code.
  20904. * @return {NodeFunction} A node function.
  20905. */
  20906. parseFunction( /*source*/ ) {
  20907. console.warn( 'Abstract function.' );
  20908. }
  20909. }
  20910. /**
  20911. * Base class for node functions. A derived module must be implemented
  20912. * for each supported native shader language. Similar to other `Node*` modules,
  20913. * this class is only relevant during the building process and not used
  20914. * in user-level code.
  20915. */
  20916. class NodeFunction {
  20917. /**
  20918. * Constructs a new node function.
  20919. *
  20920. * @param {String} type - The node type. This type is the return type of the node function.
  20921. * @param {Array<NodeFunctionInput>} inputs - The function's inputs.
  20922. * @param {String} [name=''] - The function's name.
  20923. * @param {String} [precision=''] - The precision qualifier.
  20924. */
  20925. constructor( type, inputs, name = '', precision = '' ) {
  20926. /**
  20927. * The node type. This type is the return type of the node function.
  20928. *
  20929. * @type {String}
  20930. */
  20931. this.type = type;
  20932. /**
  20933. * The function's inputs.
  20934. *
  20935. * @type {Array<NodeFunctionInput>}
  20936. */
  20937. this.inputs = inputs;
  20938. /**
  20939. * The name of the uniform.
  20940. *
  20941. * @type {String}
  20942. * @default ''
  20943. */
  20944. this.name = name;
  20945. /**
  20946. * The precision qualifier.
  20947. *
  20948. * @type {String}
  20949. * @default ''
  20950. */
  20951. this.precision = precision;
  20952. }
  20953. /**
  20954. * This method returns the native code of the node function.
  20955. *
  20956. * @abstract
  20957. * @param {String} name - The function's name.
  20958. * @return {String} A shader code.
  20959. */
  20960. getCode( /*name = this.name*/ ) {
  20961. console.warn( 'Abstract function.' );
  20962. }
  20963. }
  20964. NodeFunction.isNodeFunction = true;
  20965. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  20966. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  20967. const pragmaMain = '#pragma main';
  20968. const parse$1 = ( source ) => {
  20969. source = source.trim();
  20970. const pragmaMainIndex = source.indexOf( pragmaMain );
  20971. const mainCode = pragmaMainIndex !== - 1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  20972. const declaration = mainCode.match( declarationRegexp$1 );
  20973. if ( declaration !== null && declaration.length === 5 ) {
  20974. // tokenizer
  20975. const inputsCode = declaration[ 4 ];
  20976. const propsMatches = [];
  20977. let nameMatch = null;
  20978. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  20979. propsMatches.push( nameMatch );
  20980. }
  20981. // parser
  20982. const inputs = [];
  20983. let i = 0;
  20984. while ( i < propsMatches.length ) {
  20985. const isConst = propsMatches[ i ][ 0 ] === 'const';
  20986. if ( isConst === true ) {
  20987. i ++;
  20988. }
  20989. let qualifier = propsMatches[ i ][ 0 ];
  20990. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  20991. i ++;
  20992. } else {
  20993. qualifier = '';
  20994. }
  20995. const type = propsMatches[ i ++ ][ 0 ];
  20996. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  20997. if ( Number.isNaN( count ) === false ) i ++;
  20998. else count = null;
  20999. const name = propsMatches[ i ++ ][ 0 ];
  21000. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  21001. }
  21002. //
  21003. const blockCode = mainCode.substring( declaration[ 0 ].length );
  21004. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  21005. const type = declaration[ 2 ];
  21006. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  21007. const headerCode = pragmaMainIndex !== - 1 ? source.slice( 0, pragmaMainIndex ) : '';
  21008. return {
  21009. type,
  21010. inputs,
  21011. name,
  21012. precision,
  21013. inputsCode,
  21014. blockCode,
  21015. headerCode
  21016. };
  21017. } else {
  21018. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  21019. }
  21020. };
  21021. /**
  21022. * This class represents a GLSL node function.
  21023. *
  21024. * @augments NodeFunction
  21025. */
  21026. class GLSLNodeFunction extends NodeFunction {
  21027. /**
  21028. * Constructs a new GLSL node function.
  21029. *
  21030. * @param {String} source - The GLSL source.
  21031. */
  21032. constructor( source ) {
  21033. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  21034. super( type, inputs, name, precision );
  21035. this.inputsCode = inputsCode;
  21036. this.blockCode = blockCode;
  21037. this.headerCode = headerCode;
  21038. }
  21039. /**
  21040. * This method returns the GLSL code of the node function.
  21041. *
  21042. * @param {String} [name=this.name] - The function's name.
  21043. * @return {String} The shader code.
  21044. */
  21045. getCode( name = this.name ) {
  21046. let code;
  21047. const blockCode = this.blockCode;
  21048. if ( blockCode !== '' ) {
  21049. const { type, inputsCode, headerCode, precision } = this;
  21050. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  21051. if ( precision !== '' ) {
  21052. declarationCode = `${ precision } ${ declarationCode }`;
  21053. }
  21054. code = headerCode + declarationCode + blockCode;
  21055. } else {
  21056. // interface function
  21057. code = '';
  21058. }
  21059. return code;
  21060. }
  21061. }
  21062. /**
  21063. * A GLSL node parser.
  21064. *
  21065. * @augments NodeParser
  21066. */
  21067. class GLSLNodeParser extends NodeParser {
  21068. /**
  21069. * The method parses the given GLSL code an returns a node function.
  21070. *
  21071. * @param {String} source - The GLSL code.
  21072. * @return {GLSLNodeFunction} A node function.
  21073. */
  21074. parseFunction( source ) {
  21075. return new GLSLNodeFunction( source );
  21076. }
  21077. }
  21078. const outputNodeMap = new WeakMap();
  21079. class Nodes extends DataMap {
  21080. constructor( renderer, backend ) {
  21081. super();
  21082. this.renderer = renderer;
  21083. this.backend = backend;
  21084. this.nodeFrame = new NodeFrame();
  21085. this.nodeBuilderCache = new Map();
  21086. this.callHashCache = new ChainMap();
  21087. this.groupsData = new ChainMap();
  21088. }
  21089. updateGroup( nodeUniformsGroup ) {
  21090. const groupNode = nodeUniformsGroup.groupNode;
  21091. const name = groupNode.name;
  21092. // objectGroup is every updated
  21093. if ( name === objectGroup.name ) return true;
  21094. // renderGroup is updated once per render/compute call
  21095. if ( name === renderGroup.name ) {
  21096. const uniformsGroupData = this.get( nodeUniformsGroup );
  21097. const renderId = this.nodeFrame.renderId;
  21098. if ( uniformsGroupData.renderId !== renderId ) {
  21099. uniformsGroupData.renderId = renderId;
  21100. return true;
  21101. }
  21102. return false;
  21103. }
  21104. // frameGroup is updated once per frame
  21105. if ( name === frameGroup.name ) {
  21106. const uniformsGroupData = this.get( nodeUniformsGroup );
  21107. const frameId = this.nodeFrame.frameId;
  21108. if ( uniformsGroupData.frameId !== frameId ) {
  21109. uniformsGroupData.frameId = frameId;
  21110. return true;
  21111. }
  21112. return false;
  21113. }
  21114. // other groups are updated just when groupNode.needsUpdate is true
  21115. const groupChain = [ groupNode, nodeUniformsGroup ];
  21116. let groupData = this.groupsData.get( groupChain );
  21117. if ( groupData === undefined ) this.groupsData.set( groupChain, groupData = {} );
  21118. if ( groupData.version !== groupNode.version ) {
  21119. groupData.version = groupNode.version;
  21120. return true;
  21121. }
  21122. return false;
  21123. }
  21124. getForRenderCacheKey( renderObject ) {
  21125. return renderObject.initialCacheKey;
  21126. }
  21127. getForRender( renderObject ) {
  21128. const renderObjectData = this.get( renderObject );
  21129. let nodeBuilderState = renderObjectData.nodeBuilderState;
  21130. if ( nodeBuilderState === undefined ) {
  21131. const { nodeBuilderCache } = this;
  21132. const cacheKey = this.getForRenderCacheKey( renderObject );
  21133. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  21134. if ( nodeBuilderState === undefined ) {
  21135. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  21136. nodeBuilder.scene = renderObject.scene;
  21137. nodeBuilder.material = renderObject.material;
  21138. nodeBuilder.camera = renderObject.camera;
  21139. nodeBuilder.context.material = renderObject.material;
  21140. nodeBuilder.lightsNode = renderObject.lightsNode;
  21141. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  21142. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  21143. nodeBuilder.clippingContext = renderObject.clippingContext;
  21144. nodeBuilder.build();
  21145. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  21146. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  21147. }
  21148. nodeBuilderState.usedTimes ++;
  21149. renderObjectData.nodeBuilderState = nodeBuilderState;
  21150. }
  21151. return nodeBuilderState;
  21152. }
  21153. delete( object ) {
  21154. if ( object.isRenderObject ) {
  21155. const nodeBuilderState = this.get( object ).nodeBuilderState;
  21156. nodeBuilderState.usedTimes --;
  21157. if ( nodeBuilderState.usedTimes === 0 ) {
  21158. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  21159. }
  21160. }
  21161. return super.delete( object );
  21162. }
  21163. getForCompute( computeNode ) {
  21164. const computeData = this.get( computeNode );
  21165. let nodeBuilderState = computeData.nodeBuilderState;
  21166. if ( nodeBuilderState === undefined ) {
  21167. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  21168. nodeBuilder.build();
  21169. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  21170. computeData.nodeBuilderState = nodeBuilderState;
  21171. }
  21172. return nodeBuilderState;
  21173. }
  21174. _createNodeBuilderState( nodeBuilder ) {
  21175. return new NodeBuilderState(
  21176. nodeBuilder.vertexShader,
  21177. nodeBuilder.fragmentShader,
  21178. nodeBuilder.computeShader,
  21179. nodeBuilder.getAttributesArray(),
  21180. nodeBuilder.getBindings(),
  21181. nodeBuilder.updateNodes,
  21182. nodeBuilder.updateBeforeNodes,
  21183. nodeBuilder.updateAfterNodes,
  21184. nodeBuilder.monitor,
  21185. nodeBuilder.transforms
  21186. );
  21187. }
  21188. getEnvironmentNode( scene ) {
  21189. return scene.environmentNode || this.get( scene ).environmentNode || null;
  21190. }
  21191. getBackgroundNode( scene ) {
  21192. return scene.backgroundNode || this.get( scene ).backgroundNode || null;
  21193. }
  21194. getFogNode( scene ) {
  21195. return scene.fogNode || this.get( scene ).fogNode || null;
  21196. }
  21197. getCacheKey( scene, lightsNode ) {
  21198. const chain = [ scene, lightsNode ];
  21199. const callId = this.renderer.info.calls;
  21200. let cacheKeyData = this.callHashCache.get( chain );
  21201. if ( cacheKeyData === undefined || cacheKeyData.callId !== callId ) {
  21202. const environmentNode = this.getEnvironmentNode( scene );
  21203. const fogNode = this.getFogNode( scene );
  21204. const values = [];
  21205. if ( lightsNode ) values.push( lightsNode.getCacheKey( true ) );
  21206. if ( environmentNode ) values.push( environmentNode.getCacheKey() );
  21207. if ( fogNode ) values.push( fogNode.getCacheKey() );
  21208. values.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  21209. cacheKeyData = {
  21210. callId,
  21211. cacheKey: hashArray( values )
  21212. };
  21213. this.callHashCache.set( chain, cacheKeyData );
  21214. }
  21215. return cacheKeyData.cacheKey;
  21216. }
  21217. updateScene( scene ) {
  21218. this.updateEnvironment( scene );
  21219. this.updateFog( scene );
  21220. this.updateBackground( scene );
  21221. }
  21222. get isToneMappingState() {
  21223. return this.renderer.getRenderTarget() ? false : true;
  21224. }
  21225. updateBackground( scene ) {
  21226. const sceneData = this.get( scene );
  21227. const background = scene.background;
  21228. if ( background ) {
  21229. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  21230. if ( sceneData.background !== background || forceUpdate ) {
  21231. let backgroundNode = null;
  21232. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  21233. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  21234. backgroundNode = pmremTexture( background );
  21235. } else {
  21236. let envMap;
  21237. if ( background.isCubeTexture === true ) {
  21238. envMap = cubeTexture( background );
  21239. } else {
  21240. envMap = texture( background );
  21241. }
  21242. backgroundNode = cubeMapNode( envMap );
  21243. }
  21244. } else if ( background.isTexture === true ) {
  21245. backgroundNode = texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  21246. } else if ( background.isColor !== true ) {
  21247. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  21248. }
  21249. sceneData.backgroundNode = backgroundNode;
  21250. sceneData.background = background;
  21251. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  21252. }
  21253. } else if ( sceneData.backgroundNode ) {
  21254. delete sceneData.backgroundNode;
  21255. delete sceneData.background;
  21256. }
  21257. }
  21258. updateFog( scene ) {
  21259. const sceneData = this.get( scene );
  21260. const fog = scene.fog;
  21261. if ( fog ) {
  21262. if ( sceneData.fog !== fog ) {
  21263. let fogNode = null;
  21264. if ( fog.isFogExp2 ) {
  21265. const color = reference( 'color', 'color', fog ).setGroup( renderGroup );
  21266. const density = reference( 'density', 'float', fog ).setGroup( renderGroup );
  21267. fogNode = densityFog( color, density );
  21268. } else if ( fog.isFog ) {
  21269. const color = reference( 'color', 'color', fog ).setGroup( renderGroup );
  21270. const near = reference( 'near', 'float', fog ).setGroup( renderGroup );
  21271. const far = reference( 'far', 'float', fog ).setGroup( renderGroup );
  21272. fogNode = rangeFog( color, near, far );
  21273. } else {
  21274. console.error( 'WebGPUNodes: Unsupported fog configuration.', fog );
  21275. }
  21276. sceneData.fogNode = fogNode;
  21277. sceneData.fog = fog;
  21278. }
  21279. } else {
  21280. delete sceneData.fogNode;
  21281. delete sceneData.fog;
  21282. }
  21283. }
  21284. updateEnvironment( scene ) {
  21285. const sceneData = this.get( scene );
  21286. const environment = scene.environment;
  21287. if ( environment ) {
  21288. if ( sceneData.environment !== environment ) {
  21289. let environmentNode = null;
  21290. if ( environment.isCubeTexture === true ) {
  21291. environmentNode = cubeTexture( environment );
  21292. } else if ( environment.isTexture === true ) {
  21293. environmentNode = texture( environment );
  21294. } else {
  21295. console.error( 'Nodes: Unsupported environment configuration.', environment );
  21296. }
  21297. sceneData.environmentNode = environmentNode;
  21298. sceneData.environment = environment;
  21299. }
  21300. } else if ( sceneData.environmentNode ) {
  21301. delete sceneData.environmentNode;
  21302. delete sceneData.environment;
  21303. }
  21304. }
  21305. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  21306. const nodeFrame = this.nodeFrame;
  21307. nodeFrame.renderer = renderer;
  21308. nodeFrame.scene = scene;
  21309. nodeFrame.object = object;
  21310. nodeFrame.camera = camera;
  21311. nodeFrame.material = material;
  21312. return nodeFrame;
  21313. }
  21314. getNodeFrameForRender( renderObject ) {
  21315. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  21316. }
  21317. getOutputCacheKey() {
  21318. const renderer = this.renderer;
  21319. return renderer.toneMapping + ',' + renderer.currentColorSpace;
  21320. }
  21321. hasOutputChange( outputTarget ) {
  21322. const cacheKey = outputNodeMap.get( outputTarget );
  21323. return cacheKey !== this.getOutputCacheKey();
  21324. }
  21325. getOutputNode( outputTexture ) {
  21326. const renderer = this.renderer;
  21327. const cacheKey = this.getOutputCacheKey();
  21328. const output = texture( outputTexture, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  21329. outputNodeMap.set( outputTexture, cacheKey );
  21330. return output;
  21331. }
  21332. updateBefore( renderObject ) {
  21333. const nodeBuilder = renderObject.getNodeBuilderState();
  21334. for ( const node of nodeBuilder.updateBeforeNodes ) {
  21335. // update frame state for each node
  21336. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  21337. }
  21338. }
  21339. updateAfter( renderObject ) {
  21340. const nodeBuilder = renderObject.getNodeBuilderState();
  21341. for ( const node of nodeBuilder.updateAfterNodes ) {
  21342. // update frame state for each node
  21343. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  21344. }
  21345. }
  21346. updateForCompute( computeNode ) {
  21347. const nodeFrame = this.getNodeFrame();
  21348. const nodeBuilder = this.getForCompute( computeNode );
  21349. for ( const node of nodeBuilder.updateNodes ) {
  21350. nodeFrame.updateNode( node );
  21351. }
  21352. }
  21353. updateForRender( renderObject ) {
  21354. const nodeFrame = this.getNodeFrameForRender( renderObject );
  21355. const nodeBuilder = renderObject.getNodeBuilderState();
  21356. for ( const node of nodeBuilder.updateNodes ) {
  21357. nodeFrame.updateNode( node );
  21358. }
  21359. }
  21360. needsRefresh( renderObject ) {
  21361. const nodeFrame = this.getNodeFrameForRender( renderObject );
  21362. const monitor = renderObject.getMonitor();
  21363. return monitor.needsRefresh( renderObject, nodeFrame );
  21364. }
  21365. dispose() {
  21366. super.dispose();
  21367. this.nodeFrame = new NodeFrame();
  21368. this.nodeBuilderCache = new Map();
  21369. }
  21370. }
  21371. const _plane = /*@__PURE__*/ new Plane();
  21372. class ClippingContext {
  21373. constructor( parentContext = null ) {
  21374. this.version = 0;
  21375. this.clipIntersection = null;
  21376. this.cacheKey = '';
  21377. if ( parentContext === null ) {
  21378. this.intersectionPlanes = [];
  21379. this.unionPlanes = [];
  21380. this.viewNormalMatrix = new Matrix3();
  21381. this.clippingGroupContexts = new WeakMap();
  21382. this.shadowPass = false;
  21383. } else {
  21384. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  21385. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  21386. this.shadowPass = parentContext.shadowPass;
  21387. this.viewMatrix = parentContext.viewMatrix;
  21388. }
  21389. this.parentVersion = null;
  21390. }
  21391. projectPlanes( source, destination, offset ) {
  21392. const l = source.length;
  21393. for ( let i = 0; i < l; i ++ ) {
  21394. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  21395. const v = destination[ offset + i ];
  21396. const normal = _plane.normal;
  21397. v.x = - normal.x;
  21398. v.y = - normal.y;
  21399. v.z = - normal.z;
  21400. v.w = _plane.constant;
  21401. }
  21402. }
  21403. updateGlobal( scene, camera ) {
  21404. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowNodeMaterial );
  21405. this.viewMatrix = camera.matrixWorldInverse;
  21406. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  21407. }
  21408. update( parentContext, clippingGroup ) {
  21409. let update = false;
  21410. if ( parentContext.version !== this.parentVersion ) {
  21411. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  21412. this.unionPlanes = Array.from( parentContext.unionPlanes );
  21413. this.parentVersion = parentContext.version;
  21414. }
  21415. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  21416. this.clipIntersection = clippingGroup.clipIntersection;
  21417. if ( this.clipIntersection ) {
  21418. this.unionPlanes.length = parentContext.unionPlanes.length;
  21419. } else {
  21420. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  21421. }
  21422. }
  21423. const srcClippingPlanes = clippingGroup.clippingPlanes;
  21424. const l = srcClippingPlanes.length;
  21425. let dstClippingPlanes;
  21426. let offset;
  21427. if ( this.clipIntersection ) {
  21428. dstClippingPlanes = this.intersectionPlanes;
  21429. offset = parentContext.intersectionPlanes.length;
  21430. } else {
  21431. dstClippingPlanes = this.unionPlanes;
  21432. offset = parentContext.unionPlanes.length;
  21433. }
  21434. if ( dstClippingPlanes.length !== offset + l ) {
  21435. dstClippingPlanes.length = offset + l;
  21436. for ( let i = 0; i < l; i ++ ) {
  21437. dstClippingPlanes[ offset + i ] = new Vector4();
  21438. }
  21439. update = true;
  21440. }
  21441. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  21442. if ( update ) {
  21443. this.version ++;
  21444. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  21445. }
  21446. }
  21447. getGroupContext( clippingGroup ) {
  21448. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  21449. let context = this.clippingGroupContexts.get( clippingGroup );
  21450. if ( context === undefined ) {
  21451. context = new ClippingContext( this );
  21452. this.clippingGroupContexts.set( clippingGroup, context );
  21453. }
  21454. context.update( this, clippingGroup );
  21455. return context;
  21456. }
  21457. get unionClippingCount() {
  21458. return this.unionPlanes.length;
  21459. }
  21460. }
  21461. class RenderBundle {
  21462. constructor( scene, camera ) {
  21463. this.scene = scene;
  21464. this.camera = camera;
  21465. }
  21466. clone() {
  21467. return Object.assign( new this.constructor(), this );
  21468. }
  21469. }
  21470. class RenderBundles {
  21471. constructor() {
  21472. this.lists = new ChainMap();
  21473. }
  21474. get( scene, camera ) {
  21475. const lists = this.lists;
  21476. const keys = [ scene, camera ];
  21477. let list = lists.get( keys );
  21478. if ( list === undefined ) {
  21479. list = new RenderBundle( scene, camera );
  21480. lists.set( keys, list );
  21481. }
  21482. return list;
  21483. }
  21484. dispose() {
  21485. this.lists = new ChainMap();
  21486. }
  21487. }
  21488. class NodeLibrary {
  21489. constructor() {
  21490. this.lightNodes = new WeakMap();
  21491. this.materialNodes = new Map();
  21492. this.toneMappingNodes = new Map();
  21493. }
  21494. fromMaterial( material ) {
  21495. if ( material.isNodeMaterial ) return material;
  21496. let nodeMaterial = null;
  21497. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  21498. if ( nodeMaterialClass !== null ) {
  21499. nodeMaterial = new nodeMaterialClass();
  21500. for ( const key in material ) {
  21501. nodeMaterial[ key ] = material[ key ];
  21502. }
  21503. }
  21504. return nodeMaterial;
  21505. }
  21506. addToneMapping( toneMappingNode, toneMapping ) {
  21507. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  21508. }
  21509. getToneMappingFunction( toneMapping ) {
  21510. return this.toneMappingNodes.get( toneMapping ) || null;
  21511. }
  21512. getMaterialNodeClass( materialType ) {
  21513. return this.materialNodes.get( materialType ) || null;
  21514. }
  21515. addMaterial( materialNodeClass, materialClassType ) {
  21516. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  21517. }
  21518. getLightNodeClass( light ) {
  21519. return this.lightNodes.get( light ) || null;
  21520. }
  21521. addLight( lightNodeClass, lightClass ) {
  21522. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  21523. }
  21524. addType( nodeClass, type, library ) {
  21525. if ( library.has( type ) ) {
  21526. console.warn( `Redefinition of node ${ type }` );
  21527. return;
  21528. }
  21529. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  21530. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  21531. library.set( type, nodeClass );
  21532. }
  21533. addClass( nodeClass, baseClass, library ) {
  21534. if ( library.has( baseClass ) ) {
  21535. console.warn( `Redefinition of node ${ baseClass.name }` );
  21536. return;
  21537. }
  21538. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  21539. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  21540. library.set( baseClass, nodeClass );
  21541. }
  21542. }
  21543. const _defaultLights = /*@__PURE__*/ new LightsNode();
  21544. class Lighting extends ChainMap {
  21545. constructor() {
  21546. super();
  21547. }
  21548. createNode( lights = [] ) {
  21549. return new LightsNode().setLights( lights );
  21550. }
  21551. getNode( scene, camera ) {
  21552. // ignore post-processing
  21553. if ( scene.isQuadMesh ) return _defaultLights;
  21554. // tiled lighting
  21555. const keys = [ scene, camera ];
  21556. let node = this.get( keys );
  21557. if ( node === undefined ) {
  21558. node = this.createNode();
  21559. this.set( keys, node );
  21560. }
  21561. return node;
  21562. }
  21563. }
  21564. const _scene = /*@__PURE__*/ new Scene();
  21565. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  21566. const _screen = /*@__PURE__*/ new Vector4();
  21567. const _frustum = /*@__PURE__*/ new Frustum();
  21568. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  21569. const _vector4 = /*@__PURE__*/ new Vector4();
  21570. class Renderer {
  21571. constructor( backend, parameters = {} ) {
  21572. this.isRenderer = true;
  21573. //
  21574. const {
  21575. logarithmicDepthBuffer = false,
  21576. alpha = true,
  21577. depth = true,
  21578. stencil = false,
  21579. antialias = false,
  21580. samples = 0,
  21581. getFallback = null
  21582. } = parameters;
  21583. // public
  21584. this.domElement = backend.getDomElement();
  21585. this.backend = backend;
  21586. this.samples = samples || ( antialias === true ) ? 4 : 0;
  21587. this.autoClear = true;
  21588. this.autoClearColor = true;
  21589. this.autoClearDepth = true;
  21590. this.autoClearStencil = true;
  21591. this.alpha = alpha;
  21592. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  21593. this.outputColorSpace = SRGBColorSpace;
  21594. this.toneMapping = NoToneMapping;
  21595. this.toneMappingExposure = 1.0;
  21596. this.sortObjects = true;
  21597. this.depth = depth;
  21598. this.stencil = stencil;
  21599. this.info = new Info();
  21600. this.nodes = {
  21601. modelViewMatrix: null,
  21602. modelNormalViewMatrix: null
  21603. };
  21604. this.library = new NodeLibrary();
  21605. this.lighting = new Lighting();
  21606. // internals
  21607. this._getFallback = getFallback;
  21608. this._pixelRatio = 1;
  21609. this._width = this.domElement.width;
  21610. this._height = this.domElement.height;
  21611. this._viewport = new Vector4( 0, 0, this._width, this._height );
  21612. this._scissor = new Vector4( 0, 0, this._width, this._height );
  21613. this._scissorTest = false;
  21614. this._attributes = null;
  21615. this._geometries = null;
  21616. this._nodes = null;
  21617. this._animation = null;
  21618. this._bindings = null;
  21619. this._objects = null;
  21620. this._pipelines = null;
  21621. this._bundles = null;
  21622. this._renderLists = null;
  21623. this._renderContexts = null;
  21624. this._textures = null;
  21625. this._background = null;
  21626. this._quad = new QuadMesh( new NodeMaterial() );
  21627. this._quad.material.type = 'Renderer_output';
  21628. this._currentRenderContext = null;
  21629. this._opaqueSort = null;
  21630. this._transparentSort = null;
  21631. this._frameBufferTarget = null;
  21632. const alphaClear = this.alpha === true ? 0 : 1;
  21633. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  21634. this._clearDepth = 1;
  21635. this._clearStencil = 0;
  21636. this._renderTarget = null;
  21637. this._activeCubeFace = 0;
  21638. this._activeMipmapLevel = 0;
  21639. this._mrt = null;
  21640. this._renderObjectFunction = null;
  21641. this._currentRenderObjectFunction = null;
  21642. this._currentRenderBundle = null;
  21643. this._handleObjectFunction = this._renderObjectDirect;
  21644. this._isDeviceLost = false;
  21645. this.onDeviceLost = this._onDeviceLost;
  21646. this._initialized = false;
  21647. this._initPromise = null;
  21648. this._compilationPromises = null;
  21649. this.transparent = true;
  21650. this.opaque = true;
  21651. this.shadowMap = {
  21652. enabled: false,
  21653. type: PCFShadowMap
  21654. };
  21655. this.xr = {
  21656. enabled: false
  21657. };
  21658. this.debug = {
  21659. checkShaderErrors: true,
  21660. onShaderError: null,
  21661. getShaderAsync: async ( scene, camera, object ) => {
  21662. await this.compileAsync( scene, camera );
  21663. const renderList = this._renderLists.get( scene, camera );
  21664. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  21665. const material = scene.overrideMaterial || object.material;
  21666. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  21667. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  21668. return { fragmentShader, vertexShader };
  21669. }
  21670. };
  21671. }
  21672. async init() {
  21673. if ( this._initialized ) {
  21674. throw new Error( 'Renderer: Backend has already been initialized.' );
  21675. }
  21676. if ( this._initPromise !== null ) {
  21677. return this._initPromise;
  21678. }
  21679. this._initPromise = new Promise( async ( resolve, reject ) => {
  21680. let backend = this.backend;
  21681. try {
  21682. await backend.init( this );
  21683. } catch ( error ) {
  21684. if ( this._getFallback !== null ) {
  21685. // try the fallback
  21686. try {
  21687. this.backend = backend = this._getFallback( error );
  21688. await backend.init( this );
  21689. } catch ( error ) {
  21690. reject( error );
  21691. return;
  21692. }
  21693. } else {
  21694. reject( error );
  21695. return;
  21696. }
  21697. }
  21698. this._nodes = new Nodes( this, backend );
  21699. this._animation = new Animation( this._nodes, this.info );
  21700. this._attributes = new Attributes( backend );
  21701. this._background = new Background( this, this._nodes );
  21702. this._geometries = new Geometries( this._attributes, this.info );
  21703. this._textures = new Textures( this, backend, this.info );
  21704. this._pipelines = new Pipelines( backend, this._nodes );
  21705. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  21706. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  21707. this._renderLists = new RenderLists( this.lighting );
  21708. this._bundles = new RenderBundles();
  21709. this._renderContexts = new RenderContexts();
  21710. //
  21711. this._animation.start();
  21712. this._initialized = true;
  21713. resolve();
  21714. } );
  21715. return this._initPromise;
  21716. }
  21717. get coordinateSystem() {
  21718. return this.backend.coordinateSystem;
  21719. }
  21720. async compileAsync( scene, camera, targetScene = null ) {
  21721. if ( this._isDeviceLost === true ) return;
  21722. if ( this._initialized === false ) await this.init();
  21723. // preserve render tree
  21724. const nodeFrame = this._nodes.nodeFrame;
  21725. const previousRenderId = nodeFrame.renderId;
  21726. const previousRenderContext = this._currentRenderContext;
  21727. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  21728. const previousCompilationPromises = this._compilationPromises;
  21729. //
  21730. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  21731. if ( targetScene === null ) targetScene = scene;
  21732. const renderTarget = this._renderTarget;
  21733. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  21734. const activeMipmapLevel = this._activeMipmapLevel;
  21735. const compilationPromises = [];
  21736. this._currentRenderContext = renderContext;
  21737. this._currentRenderObjectFunction = this.renderObject;
  21738. this._handleObjectFunction = this._createObjectPipeline;
  21739. this._compilationPromises = compilationPromises;
  21740. nodeFrame.renderId ++;
  21741. //
  21742. nodeFrame.update();
  21743. //
  21744. renderContext.depth = this.depth;
  21745. renderContext.stencil = this.stencil;
  21746. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  21747. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  21748. //
  21749. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  21750. //
  21751. const renderList = this._renderLists.get( scene, camera );
  21752. renderList.begin();
  21753. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  21754. // include lights from target scene
  21755. if ( targetScene !== scene ) {
  21756. targetScene.traverseVisible( function ( object ) {
  21757. if ( object.isLight && object.layers.test( camera.layers ) ) {
  21758. renderList.pushLight( object );
  21759. }
  21760. } );
  21761. }
  21762. renderList.finish();
  21763. //
  21764. if ( renderTarget !== null ) {
  21765. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  21766. const renderTargetData = this._textures.get( renderTarget );
  21767. renderContext.textures = renderTargetData.textures;
  21768. renderContext.depthTexture = renderTargetData.depthTexture;
  21769. } else {
  21770. renderContext.textures = null;
  21771. renderContext.depthTexture = null;
  21772. }
  21773. //
  21774. this._nodes.updateScene( sceneRef );
  21775. //
  21776. this._background.update( sceneRef, renderList, renderContext );
  21777. // process render lists
  21778. const opaqueObjects = renderList.opaque;
  21779. const transparentObjects = renderList.transparent;
  21780. const transparentDoublePassObjects = renderList.transparentDoublePass;
  21781. const lightsNode = renderList.lightsNode;
  21782. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  21783. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  21784. // restore render tree
  21785. nodeFrame.renderId = previousRenderId;
  21786. this._currentRenderContext = previousRenderContext;
  21787. this._currentRenderObjectFunction = previousRenderObjectFunction;
  21788. this._compilationPromises = previousCompilationPromises;
  21789. this._handleObjectFunction = this._renderObjectDirect;
  21790. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  21791. await Promise.all( compilationPromises );
  21792. }
  21793. async renderAsync( scene, camera ) {
  21794. if ( this._initialized === false ) await this.init();
  21795. const renderContext = this._renderScene( scene, camera );
  21796. await this.backend.resolveTimestampAsync( renderContext, 'render' );
  21797. }
  21798. async waitForGPU() {
  21799. await this.backend.waitForGPU();
  21800. }
  21801. setMRT( mrt ) {
  21802. this._mrt = mrt;
  21803. return this;
  21804. }
  21805. getMRT() {
  21806. return this._mrt;
  21807. }
  21808. _onDeviceLost( info ) {
  21809. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  21810. if ( info.reason ) {
  21811. errorMessage += `\nReason: ${info.reason}`;
  21812. }
  21813. console.error( errorMessage );
  21814. this._isDeviceLost = true;
  21815. }
  21816. _renderBundle( bundle, sceneRef, lightsNode ) {
  21817. const { bundleGroup, camera, renderList } = bundle;
  21818. const renderContext = this._currentRenderContext;
  21819. //
  21820. const renderBundle = this._bundles.get( bundleGroup, camera );
  21821. const renderBundleData = this.backend.get( renderBundle );
  21822. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  21823. //
  21824. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  21825. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  21826. renderBundleData.renderContexts.add( renderContext );
  21827. if ( renderBundleNeedsUpdate ) {
  21828. this.backend.beginBundle( renderContext );
  21829. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  21830. renderBundleData.renderObjects = [];
  21831. }
  21832. this._currentRenderBundle = renderBundle;
  21833. const opaqueObjects = renderList.opaque;
  21834. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  21835. this._currentRenderBundle = null;
  21836. //
  21837. this.backend.finishBundle( renderContext, renderBundle );
  21838. renderBundleData.version = bundleGroup.version;
  21839. } else {
  21840. const { renderObjects } = renderBundleData;
  21841. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  21842. const renderObject = renderObjects[ i ];
  21843. if ( this._nodes.needsRefresh( renderObject ) ) {
  21844. this._nodes.updateBefore( renderObject );
  21845. this._nodes.updateForRender( renderObject );
  21846. this._bindings.updateForRender( renderObject );
  21847. this._nodes.updateAfter( renderObject );
  21848. }
  21849. }
  21850. }
  21851. this.backend.addBundle( renderContext, renderBundle );
  21852. }
  21853. render( scene, camera ) {
  21854. if ( this._initialized === false ) {
  21855. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  21856. return this.renderAsync( scene, camera );
  21857. }
  21858. this._renderScene( scene, camera );
  21859. }
  21860. _getFrameBufferTarget() {
  21861. const { currentToneMapping, currentColorSpace } = this;
  21862. const useToneMapping = currentToneMapping !== NoToneMapping;
  21863. const useColorSpace = currentColorSpace !== LinearSRGBColorSpace;
  21864. if ( useToneMapping === false && useColorSpace === false ) return null;
  21865. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  21866. const { depth, stencil } = this;
  21867. let frameBufferTarget = this._frameBufferTarget;
  21868. if ( frameBufferTarget === null ) {
  21869. frameBufferTarget = new RenderTarget( width, height, {
  21870. depthBuffer: depth,
  21871. stencilBuffer: stencil,
  21872. type: HalfFloatType, // FloatType
  21873. format: RGBAFormat,
  21874. colorSpace: LinearSRGBColorSpace,
  21875. generateMipmaps: false,
  21876. minFilter: LinearFilter,
  21877. magFilter: LinearFilter,
  21878. samples: this.samples
  21879. } );
  21880. frameBufferTarget.isPostProcessingRenderTarget = true;
  21881. this._frameBufferTarget = frameBufferTarget;
  21882. }
  21883. frameBufferTarget.depthBuffer = depth;
  21884. frameBufferTarget.stencilBuffer = stencil;
  21885. frameBufferTarget.setSize( width, height );
  21886. frameBufferTarget.viewport.copy( this._viewport );
  21887. frameBufferTarget.scissor.copy( this._scissor );
  21888. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  21889. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  21890. frameBufferTarget.scissorTest = this._scissorTest;
  21891. return frameBufferTarget;
  21892. }
  21893. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  21894. if ( this._isDeviceLost === true ) return;
  21895. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  21896. // preserve render tree
  21897. const nodeFrame = this._nodes.nodeFrame;
  21898. const previousRenderId = nodeFrame.renderId;
  21899. const previousRenderContext = this._currentRenderContext;
  21900. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  21901. //
  21902. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  21903. const outputRenderTarget = this._renderTarget;
  21904. const activeCubeFace = this._activeCubeFace;
  21905. const activeMipmapLevel = this._activeMipmapLevel;
  21906. //
  21907. let renderTarget;
  21908. if ( frameBufferTarget !== null ) {
  21909. renderTarget = frameBufferTarget;
  21910. this.setRenderTarget( renderTarget );
  21911. } else {
  21912. renderTarget = outputRenderTarget;
  21913. }
  21914. //
  21915. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  21916. this._currentRenderContext = renderContext;
  21917. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  21918. //
  21919. this.info.calls ++;
  21920. this.info.render.calls ++;
  21921. this.info.render.frameCalls ++;
  21922. nodeFrame.renderId = this.info.calls;
  21923. //
  21924. const coordinateSystem = this.coordinateSystem;
  21925. if ( camera.coordinateSystem !== coordinateSystem ) {
  21926. camera.coordinateSystem = coordinateSystem;
  21927. camera.updateProjectionMatrix();
  21928. }
  21929. //
  21930. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  21931. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  21932. //
  21933. let viewport = this._viewport;
  21934. let scissor = this._scissor;
  21935. let pixelRatio = this._pixelRatio;
  21936. if ( renderTarget !== null ) {
  21937. viewport = renderTarget.viewport;
  21938. scissor = renderTarget.scissor;
  21939. pixelRatio = 1;
  21940. }
  21941. this.getDrawingBufferSize( _drawingBufferSize );
  21942. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  21943. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  21944. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  21945. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  21946. renderContext.viewportValue.width >>= activeMipmapLevel;
  21947. renderContext.viewportValue.height >>= activeMipmapLevel;
  21948. renderContext.viewportValue.minDepth = minDepth;
  21949. renderContext.viewportValue.maxDepth = maxDepth;
  21950. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  21951. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  21952. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  21953. renderContext.scissorValue.width >>= activeMipmapLevel;
  21954. renderContext.scissorValue.height >>= activeMipmapLevel;
  21955. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  21956. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  21957. //
  21958. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  21959. //
  21960. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  21961. _frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  21962. const renderList = this._renderLists.get( scene, camera );
  21963. renderList.begin();
  21964. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  21965. renderList.finish();
  21966. if ( this.sortObjects === true ) {
  21967. renderList.sort( this._opaqueSort, this._transparentSort );
  21968. }
  21969. //
  21970. if ( renderTarget !== null ) {
  21971. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  21972. const renderTargetData = this._textures.get( renderTarget );
  21973. renderContext.textures = renderTargetData.textures;
  21974. renderContext.depthTexture = renderTargetData.depthTexture;
  21975. renderContext.width = renderTargetData.width;
  21976. renderContext.height = renderTargetData.height;
  21977. renderContext.renderTarget = renderTarget;
  21978. renderContext.depth = renderTarget.depthBuffer;
  21979. renderContext.stencil = renderTarget.stencilBuffer;
  21980. } else {
  21981. renderContext.textures = null;
  21982. renderContext.depthTexture = null;
  21983. renderContext.width = this.domElement.width;
  21984. renderContext.height = this.domElement.height;
  21985. renderContext.depth = this.depth;
  21986. renderContext.stencil = this.stencil;
  21987. }
  21988. renderContext.width >>= activeMipmapLevel;
  21989. renderContext.height >>= activeMipmapLevel;
  21990. renderContext.activeCubeFace = activeCubeFace;
  21991. renderContext.activeMipmapLevel = activeMipmapLevel;
  21992. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  21993. //
  21994. this._nodes.updateScene( sceneRef );
  21995. //
  21996. this._background.update( sceneRef, renderList, renderContext );
  21997. //
  21998. this.backend.beginRender( renderContext );
  21999. // process render lists
  22000. const {
  22001. bundles,
  22002. lightsNode,
  22003. transparentDoublePass: transparentDoublePassObjects,
  22004. transparent: transparentObjects,
  22005. opaque: opaqueObjects
  22006. } = renderList;
  22007. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  22008. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  22009. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  22010. // finish render pass
  22011. this.backend.finishRender( renderContext );
  22012. // restore render tree
  22013. nodeFrame.renderId = previousRenderId;
  22014. this._currentRenderContext = previousRenderContext;
  22015. this._currentRenderObjectFunction = previousRenderObjectFunction;
  22016. //
  22017. if ( frameBufferTarget !== null ) {
  22018. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  22019. const quad = this._quad;
  22020. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  22021. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  22022. quad.material.needsUpdate = true;
  22023. }
  22024. this._renderScene( quad, quad.camera, false );
  22025. }
  22026. //
  22027. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  22028. //
  22029. return renderContext;
  22030. }
  22031. getMaxAnisotropy() {
  22032. return this.backend.getMaxAnisotropy();
  22033. }
  22034. getActiveCubeFace() {
  22035. return this._activeCubeFace;
  22036. }
  22037. getActiveMipmapLevel() {
  22038. return this._activeMipmapLevel;
  22039. }
  22040. async setAnimationLoop( callback ) {
  22041. if ( this._initialized === false ) await this.init();
  22042. this._animation.setAnimationLoop( callback );
  22043. }
  22044. async getArrayBufferAsync( attribute ) {
  22045. return await this.backend.getArrayBufferAsync( attribute );
  22046. }
  22047. getContext() {
  22048. return this.backend.getContext();
  22049. }
  22050. getPixelRatio() {
  22051. return this._pixelRatio;
  22052. }
  22053. getDrawingBufferSize( target ) {
  22054. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  22055. }
  22056. getSize( target ) {
  22057. return target.set( this._width, this._height );
  22058. }
  22059. setPixelRatio( value = 1 ) {
  22060. if ( this._pixelRatio === value ) return;
  22061. this._pixelRatio = value;
  22062. this.setSize( this._width, this._height, false );
  22063. }
  22064. setDrawingBufferSize( width, height, pixelRatio ) {
  22065. this._width = width;
  22066. this._height = height;
  22067. this._pixelRatio = pixelRatio;
  22068. this.domElement.width = Math.floor( width * pixelRatio );
  22069. this.domElement.height = Math.floor( height * pixelRatio );
  22070. this.setViewport( 0, 0, width, height );
  22071. if ( this._initialized ) this.backend.updateSize();
  22072. }
  22073. setSize( width, height, updateStyle = true ) {
  22074. this._width = width;
  22075. this._height = height;
  22076. this.domElement.width = Math.floor( width * this._pixelRatio );
  22077. this.domElement.height = Math.floor( height * this._pixelRatio );
  22078. if ( updateStyle === true ) {
  22079. this.domElement.style.width = width + 'px';
  22080. this.domElement.style.height = height + 'px';
  22081. }
  22082. this.setViewport( 0, 0, width, height );
  22083. if ( this._initialized ) this.backend.updateSize();
  22084. }
  22085. setOpaqueSort( method ) {
  22086. this._opaqueSort = method;
  22087. }
  22088. setTransparentSort( method ) {
  22089. this._transparentSort = method;
  22090. }
  22091. getScissor( target ) {
  22092. const scissor = this._scissor;
  22093. target.x = scissor.x;
  22094. target.y = scissor.y;
  22095. target.width = scissor.width;
  22096. target.height = scissor.height;
  22097. return target;
  22098. }
  22099. setScissor( x, y, width, height ) {
  22100. const scissor = this._scissor;
  22101. if ( x.isVector4 ) {
  22102. scissor.copy( x );
  22103. } else {
  22104. scissor.set( x, y, width, height );
  22105. }
  22106. }
  22107. getScissorTest() {
  22108. return this._scissorTest;
  22109. }
  22110. setScissorTest( boolean ) {
  22111. this._scissorTest = boolean;
  22112. this.backend.setScissorTest( boolean );
  22113. }
  22114. getViewport( target ) {
  22115. return target.copy( this._viewport );
  22116. }
  22117. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  22118. const viewport = this._viewport;
  22119. if ( x.isVector4 ) {
  22120. viewport.copy( x );
  22121. } else {
  22122. viewport.set( x, y, width, height );
  22123. }
  22124. viewport.minDepth = minDepth;
  22125. viewport.maxDepth = maxDepth;
  22126. }
  22127. getClearColor( target ) {
  22128. return target.copy( this._clearColor );
  22129. }
  22130. setClearColor( color, alpha = 1 ) {
  22131. this._clearColor.set( color );
  22132. this._clearColor.a = alpha;
  22133. }
  22134. getClearAlpha() {
  22135. return this._clearColor.a;
  22136. }
  22137. setClearAlpha( alpha ) {
  22138. this._clearColor.a = alpha;
  22139. }
  22140. getClearDepth() {
  22141. return this._clearDepth;
  22142. }
  22143. setClearDepth( depth ) {
  22144. this._clearDepth = depth;
  22145. }
  22146. getClearStencil() {
  22147. return this._clearStencil;
  22148. }
  22149. setClearStencil( stencil ) {
  22150. this._clearStencil = stencil;
  22151. }
  22152. isOccluded( object ) {
  22153. const renderContext = this._currentRenderContext;
  22154. return renderContext && this.backend.isOccluded( renderContext, object );
  22155. }
  22156. clear( color = true, depth = true, stencil = true ) {
  22157. if ( this._initialized === false ) {
  22158. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  22159. return this.clearAsync( color, depth, stencil );
  22160. }
  22161. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  22162. let renderTargetData = null;
  22163. if ( renderTarget !== null ) {
  22164. this._textures.updateRenderTarget( renderTarget );
  22165. renderTargetData = this._textures.get( renderTarget );
  22166. }
  22167. this.backend.clear( color, depth, stencil, renderTargetData );
  22168. if ( renderTarget !== null && this._renderTarget === null ) {
  22169. // If a color space transform or tone mapping is required,
  22170. // the clear operation clears the intermediate renderTarget texture, but does not update the screen canvas.
  22171. const quad = this._quad;
  22172. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  22173. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  22174. quad.material.needsUpdate = true;
  22175. }
  22176. this._renderScene( quad, quad.camera, false );
  22177. }
  22178. }
  22179. clearColor() {
  22180. return this.clear( true, false, false );
  22181. }
  22182. clearDepth() {
  22183. return this.clear( false, true, false );
  22184. }
  22185. clearStencil() {
  22186. return this.clear( false, false, true );
  22187. }
  22188. async clearAsync( color = true, depth = true, stencil = true ) {
  22189. if ( this._initialized === false ) await this.init();
  22190. this.clear( color, depth, stencil );
  22191. }
  22192. clearColorAsync() {
  22193. return this.clearAsync( true, false, false );
  22194. }
  22195. clearDepthAsync() {
  22196. return this.clearAsync( false, true, false );
  22197. }
  22198. clearStencilAsync() {
  22199. return this.clearAsync( false, false, true );
  22200. }
  22201. get currentToneMapping() {
  22202. return this._renderTarget !== null ? NoToneMapping : this.toneMapping;
  22203. }
  22204. get currentColorSpace() {
  22205. return this._renderTarget !== null ? LinearSRGBColorSpace : this.outputColorSpace;
  22206. }
  22207. dispose() {
  22208. this.info.dispose();
  22209. this.backend.dispose();
  22210. this._animation.dispose();
  22211. this._objects.dispose();
  22212. this._pipelines.dispose();
  22213. this._nodes.dispose();
  22214. this._bindings.dispose();
  22215. this._renderLists.dispose();
  22216. this._renderContexts.dispose();
  22217. this._textures.dispose();
  22218. this.setRenderTarget( null );
  22219. this.setAnimationLoop( null );
  22220. }
  22221. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  22222. this._renderTarget = renderTarget;
  22223. this._activeCubeFace = activeCubeFace;
  22224. this._activeMipmapLevel = activeMipmapLevel;
  22225. }
  22226. getRenderTarget() {
  22227. return this._renderTarget;
  22228. }
  22229. setRenderObjectFunction( renderObjectFunction ) {
  22230. this._renderObjectFunction = renderObjectFunction;
  22231. }
  22232. getRenderObjectFunction() {
  22233. return this._renderObjectFunction;
  22234. }
  22235. compute( computeNodes ) {
  22236. if ( this.isDeviceLost === true ) return;
  22237. if ( this._initialized === false ) {
  22238. console.warn( 'THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  22239. return this.computeAsync( computeNodes );
  22240. }
  22241. //
  22242. const nodeFrame = this._nodes.nodeFrame;
  22243. const previousRenderId = nodeFrame.renderId;
  22244. //
  22245. this.info.calls ++;
  22246. this.info.compute.calls ++;
  22247. this.info.compute.frameCalls ++;
  22248. nodeFrame.renderId = this.info.calls;
  22249. //
  22250. const backend = this.backend;
  22251. const pipelines = this._pipelines;
  22252. const bindings = this._bindings;
  22253. const nodes = this._nodes;
  22254. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  22255. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  22256. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  22257. }
  22258. backend.beginCompute( computeNodes );
  22259. for ( const computeNode of computeList ) {
  22260. // onInit
  22261. if ( pipelines.has( computeNode ) === false ) {
  22262. const dispose = () => {
  22263. computeNode.removeEventListener( 'dispose', dispose );
  22264. pipelines.delete( computeNode );
  22265. bindings.delete( computeNode );
  22266. nodes.delete( computeNode );
  22267. };
  22268. computeNode.addEventListener( 'dispose', dispose );
  22269. //
  22270. const onInitFn = computeNode.onInitFunction;
  22271. if ( onInitFn !== null ) {
  22272. onInitFn.call( computeNode, { renderer: this } );
  22273. }
  22274. }
  22275. nodes.updateForCompute( computeNode );
  22276. bindings.updateForCompute( computeNode );
  22277. const computeBindings = bindings.getForCompute( computeNode );
  22278. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  22279. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  22280. }
  22281. backend.finishCompute( computeNodes );
  22282. //
  22283. nodeFrame.renderId = previousRenderId;
  22284. }
  22285. async computeAsync( computeNodes ) {
  22286. if ( this._initialized === false ) await this.init();
  22287. this.compute( computeNodes );
  22288. await this.backend.resolveTimestampAsync( computeNodes, 'compute' );
  22289. }
  22290. async hasFeatureAsync( name ) {
  22291. if ( this._initialized === false ) await this.init();
  22292. return this.backend.hasFeature( name );
  22293. }
  22294. hasFeature( name ) {
  22295. if ( this._initialized === false ) {
  22296. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  22297. return false;
  22298. }
  22299. return this.backend.hasFeature( name );
  22300. }
  22301. hasInitialized() {
  22302. return this._initialized;
  22303. }
  22304. async initTextureAsync( texture ) {
  22305. if ( this._initialized === false ) await this.init();
  22306. this._textures.updateTexture( texture );
  22307. }
  22308. initTexture( texture ) {
  22309. if ( this._initialized === false ) {
  22310. console.warn( 'THREE.Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead.' );
  22311. return false;
  22312. }
  22313. this._textures.updateTexture( texture );
  22314. }
  22315. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  22316. if ( rectangle !== null ) {
  22317. if ( rectangle.isVector2 ) {
  22318. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  22319. } else if ( rectangle.isVector4 ) {
  22320. rectangle = _vector4.copy( rectangle ).floor();
  22321. } else {
  22322. console.error( 'THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  22323. return;
  22324. }
  22325. } else {
  22326. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  22327. }
  22328. //
  22329. let renderContext = this._currentRenderContext;
  22330. let renderTarget;
  22331. if ( renderContext !== null ) {
  22332. renderTarget = renderContext.renderTarget;
  22333. } else {
  22334. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  22335. if ( renderTarget !== null ) {
  22336. this._textures.updateRenderTarget( renderTarget );
  22337. renderContext = this._textures.get( renderTarget );
  22338. }
  22339. }
  22340. //
  22341. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  22342. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  22343. }
  22344. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  22345. this._textures.updateTexture( srcTexture );
  22346. this._textures.updateTexture( dstTexture );
  22347. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  22348. }
  22349. readRenderTargetPixelsAsync( renderTarget, x, y, width, height, index = 0, faceIndex = 0 ) {
  22350. return this.backend.copyTextureToBuffer( renderTarget.textures[ index ], x, y, width, height, faceIndex );
  22351. }
  22352. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  22353. if ( object.visible === false ) return;
  22354. const visible = object.layers.test( camera.layers );
  22355. if ( visible ) {
  22356. if ( object.isGroup ) {
  22357. groupOrder = object.renderOrder;
  22358. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  22359. } else if ( object.isLOD ) {
  22360. if ( object.autoUpdate === true ) object.update( camera );
  22361. } else if ( object.isLight ) {
  22362. renderList.pushLight( object );
  22363. } else if ( object.isSprite ) {
  22364. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  22365. if ( this.sortObjects === true ) {
  22366. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  22367. }
  22368. const { geometry, material } = object;
  22369. if ( material.visible ) {
  22370. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  22371. }
  22372. }
  22373. } else if ( object.isLineLoop ) {
  22374. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  22375. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  22376. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  22377. const { geometry, material } = object;
  22378. if ( this.sortObjects === true ) {
  22379. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  22380. _vector4
  22381. .copy( geometry.boundingSphere.center )
  22382. .applyMatrix4( object.matrixWorld )
  22383. .applyMatrix4( _projScreenMatrix );
  22384. }
  22385. if ( Array.isArray( material ) ) {
  22386. const groups = geometry.groups;
  22387. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  22388. const group = groups[ i ];
  22389. const groupMaterial = material[ group.materialIndex ];
  22390. if ( groupMaterial && groupMaterial.visible ) {
  22391. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  22392. }
  22393. }
  22394. } else if ( material.visible ) {
  22395. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  22396. }
  22397. }
  22398. }
  22399. }
  22400. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  22401. const baseRenderList = renderList;
  22402. // replace render list
  22403. renderList = this._renderLists.get( object, camera );
  22404. renderList.begin();
  22405. baseRenderList.pushBundle( {
  22406. bundleGroup: object,
  22407. camera,
  22408. renderList,
  22409. } );
  22410. renderList.finish();
  22411. }
  22412. const children = object.children;
  22413. for ( let i = 0, l = children.length; i < l; i ++ ) {
  22414. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  22415. }
  22416. }
  22417. _renderBundles( bundles, sceneRef, lightsNode ) {
  22418. for ( const bundle of bundles ) {
  22419. this._renderBundle( bundle, sceneRef, lightsNode );
  22420. }
  22421. }
  22422. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  22423. if ( doublePassList.length > 0 ) {
  22424. // render back side
  22425. for ( const { material } of doublePassList ) {
  22426. material.side = BackSide;
  22427. }
  22428. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  22429. // render front side
  22430. for ( const { material } of doublePassList ) {
  22431. material.side = FrontSide;
  22432. }
  22433. this._renderObjects( renderList, camera, scene, lightsNode );
  22434. // restore
  22435. for ( const { material } of doublePassList ) {
  22436. material.side = DoubleSide;
  22437. }
  22438. } else {
  22439. this._renderObjects( renderList, camera, scene, lightsNode );
  22440. }
  22441. }
  22442. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  22443. // process renderable objects
  22444. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  22445. const renderItem = renderList[ i ];
  22446. // @TODO: Add support for multiple materials per object. This will require to extract
  22447. // the material from the renderItem object and pass it with its group data to renderObject().
  22448. const { object, geometry, material, group, clippingContext } = renderItem;
  22449. if ( camera.isArrayCamera ) {
  22450. const cameras = camera.cameras;
  22451. for ( let j = 0, jl = cameras.length; j < jl; j ++ ) {
  22452. const camera2 = cameras[ j ];
  22453. if ( object.layers.test( camera2.layers ) ) {
  22454. const vp = camera2.viewport;
  22455. const minDepth = ( vp.minDepth === undefined ) ? 0 : vp.minDepth;
  22456. const maxDepth = ( vp.maxDepth === undefined ) ? 1 : vp.maxDepth;
  22457. const viewportValue = this._currentRenderContext.viewportValue;
  22458. viewportValue.copy( vp ).multiplyScalar( this._pixelRatio ).floor();
  22459. viewportValue.minDepth = minDepth;
  22460. viewportValue.maxDepth = maxDepth;
  22461. this.backend.updateViewport( this._currentRenderContext );
  22462. this._currentRenderObjectFunction( object, scene, camera2, geometry, material, group, lightsNode, clippingContext, passId );
  22463. }
  22464. }
  22465. } else {
  22466. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  22467. }
  22468. }
  22469. }
  22470. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  22471. let overridePositionNode;
  22472. let overrideColorNode;
  22473. let overrideDepthNode;
  22474. //
  22475. object.onBeforeRender( this, scene, camera, geometry, material, group );
  22476. //
  22477. if ( scene.overrideMaterial !== null ) {
  22478. const overrideMaterial = scene.overrideMaterial;
  22479. if ( material.positionNode && material.positionNode.isNode ) {
  22480. overridePositionNode = overrideMaterial.positionNode;
  22481. overrideMaterial.positionNode = material.positionNode;
  22482. }
  22483. overrideMaterial.alphaTest = material.alphaTest;
  22484. overrideMaterial.alphaMap = material.alphaMap;
  22485. if ( overrideMaterial.isShadowNodeMaterial ) {
  22486. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  22487. if ( material.depthNode && material.depthNode.isNode ) {
  22488. overrideDepthNode = overrideMaterial.depthNode;
  22489. overrideMaterial.depthNode = material.depthNode;
  22490. }
  22491. if ( material.castShadowNode && material.castShadowNode.isNode ) {
  22492. overrideColorNode = overrideMaterial.colorNode;
  22493. overrideMaterial.colorNode = material.castShadowNode;
  22494. }
  22495. }
  22496. material = overrideMaterial;
  22497. }
  22498. //
  22499. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  22500. material.side = BackSide;
  22501. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  22502. material.side = FrontSide;
  22503. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  22504. material.side = DoubleSide;
  22505. } else {
  22506. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  22507. }
  22508. //
  22509. if ( overridePositionNode !== undefined ) {
  22510. scene.overrideMaterial.positionNode = overridePositionNode;
  22511. }
  22512. if ( overrideDepthNode !== undefined ) {
  22513. scene.overrideMaterial.depthNode = overrideDepthNode;
  22514. }
  22515. if ( overrideColorNode !== undefined ) {
  22516. scene.overrideMaterial.colorNode = overrideColorNode;
  22517. }
  22518. //
  22519. object.onAfterRender( this, scene, camera, geometry, material, group );
  22520. }
  22521. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  22522. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  22523. renderObject.drawRange = object.geometry.drawRange;
  22524. renderObject.group = group;
  22525. //
  22526. const needsRefresh = this._nodes.needsRefresh( renderObject );
  22527. if ( needsRefresh ) {
  22528. this._nodes.updateBefore( renderObject );
  22529. this._geometries.updateForRender( renderObject );
  22530. this._nodes.updateForRender( renderObject );
  22531. this._bindings.updateForRender( renderObject );
  22532. }
  22533. this._pipelines.updateForRender( renderObject );
  22534. //
  22535. if ( this._currentRenderBundle !== null ) {
  22536. const renderBundleData = this.backend.get( this._currentRenderBundle );
  22537. renderBundleData.renderObjects.push( renderObject );
  22538. renderObject.bundle = this._currentRenderBundle.scene;
  22539. }
  22540. this.backend.draw( renderObject, this.info );
  22541. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  22542. }
  22543. _createObjectPipeline( object, material, scene, camera, lightsNode, clippingContext, passId ) {
  22544. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  22545. //
  22546. this._nodes.updateBefore( renderObject );
  22547. this._geometries.updateForRender( renderObject );
  22548. this._nodes.updateForRender( renderObject );
  22549. this._bindings.updateForRender( renderObject );
  22550. this._pipelines.getForRender( renderObject, this._compilationPromises );
  22551. this._nodes.updateAfter( renderObject );
  22552. }
  22553. get compile() {
  22554. return this.compileAsync;
  22555. }
  22556. }
  22557. class Binding {
  22558. constructor( name = '' ) {
  22559. this.name = name;
  22560. this.visibility = 0;
  22561. }
  22562. setVisibility( visibility ) {
  22563. this.visibility |= visibility;
  22564. }
  22565. clone() {
  22566. return Object.assign( new this.constructor(), this );
  22567. }
  22568. }
  22569. function getFloatLength( floatLength ) {
  22570. // ensure chunk size alignment (STD140 layout)
  22571. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  22572. }
  22573. class Buffer extends Binding {
  22574. constructor( name, buffer = null ) {
  22575. super( name );
  22576. this.isBuffer = true;
  22577. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  22578. this._buffer = buffer;
  22579. }
  22580. get byteLength() {
  22581. return getFloatLength( this._buffer.byteLength );
  22582. }
  22583. get buffer() {
  22584. return this._buffer;
  22585. }
  22586. update() {
  22587. return true;
  22588. }
  22589. }
  22590. class UniformBuffer extends Buffer {
  22591. constructor( name, buffer = null ) {
  22592. super( name, buffer );
  22593. this.isUniformBuffer = true;
  22594. }
  22595. }
  22596. let _id$4 = 0;
  22597. class NodeUniformBuffer extends UniformBuffer {
  22598. constructor( nodeUniform, groupNode ) {
  22599. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  22600. this.nodeUniform = nodeUniform;
  22601. this.groupNode = groupNode;
  22602. }
  22603. get buffer() {
  22604. return this.nodeUniform.value;
  22605. }
  22606. }
  22607. class UniformsGroup extends UniformBuffer {
  22608. constructor( name ) {
  22609. super( name );
  22610. this.isUniformsGroup = true;
  22611. this._values = null;
  22612. // the order of uniforms in this array must match the order of uniforms in the shader
  22613. this.uniforms = [];
  22614. }
  22615. addUniform( uniform ) {
  22616. this.uniforms.push( uniform );
  22617. return this;
  22618. }
  22619. removeUniform( uniform ) {
  22620. const index = this.uniforms.indexOf( uniform );
  22621. if ( index !== - 1 ) {
  22622. this.uniforms.splice( index, 1 );
  22623. }
  22624. return this;
  22625. }
  22626. get values() {
  22627. if ( this._values === null ) {
  22628. this._values = Array.from( this.buffer );
  22629. }
  22630. return this._values;
  22631. }
  22632. get buffer() {
  22633. let buffer = this._buffer;
  22634. if ( buffer === null ) {
  22635. const byteLength = this.byteLength;
  22636. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  22637. this._buffer = buffer;
  22638. }
  22639. return buffer;
  22640. }
  22641. get byteLength() {
  22642. let offset = 0; // global buffer offset in bytes
  22643. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  22644. const uniform = this.uniforms[ i ];
  22645. const { boundary, itemSize } = uniform;
  22646. // offset within a single chunk in bytes
  22647. const chunkOffset = offset % GPU_CHUNK_BYTES;
  22648. const remainingSizeInChunk = GPU_CHUNK_BYTES - chunkOffset;
  22649. // conformance tests
  22650. if ( chunkOffset !== 0 && ( remainingSizeInChunk - boundary ) < 0 ) {
  22651. // check for chunk overflow
  22652. offset += ( GPU_CHUNK_BYTES - chunkOffset );
  22653. } else if ( chunkOffset % boundary !== 0 ) {
  22654. // check for correct alignment
  22655. offset += ( chunkOffset % boundary );
  22656. }
  22657. uniform.offset = ( offset / this.bytesPerElement );
  22658. offset += ( itemSize * this.bytesPerElement );
  22659. }
  22660. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  22661. }
  22662. update() {
  22663. let updated = false;
  22664. for ( const uniform of this.uniforms ) {
  22665. if ( this.updateByType( uniform ) === true ) {
  22666. updated = true;
  22667. }
  22668. }
  22669. return updated;
  22670. }
  22671. updateByType( uniform ) {
  22672. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  22673. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  22674. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  22675. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  22676. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  22677. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  22678. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  22679. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  22680. }
  22681. updateNumber( uniform ) {
  22682. let updated = false;
  22683. const a = this.values;
  22684. const v = uniform.getValue();
  22685. const offset = uniform.offset;
  22686. const type = uniform.getType();
  22687. if ( a[ offset ] !== v ) {
  22688. const b = this._getBufferForType( type );
  22689. b[ offset ] = a[ offset ] = v;
  22690. updated = true;
  22691. }
  22692. return updated;
  22693. }
  22694. updateVector2( uniform ) {
  22695. let updated = false;
  22696. const a = this.values;
  22697. const v = uniform.getValue();
  22698. const offset = uniform.offset;
  22699. const type = uniform.getType();
  22700. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  22701. const b = this._getBufferForType( type );
  22702. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  22703. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  22704. updated = true;
  22705. }
  22706. return updated;
  22707. }
  22708. updateVector3( uniform ) {
  22709. let updated = false;
  22710. const a = this.values;
  22711. const v = uniform.getValue();
  22712. const offset = uniform.offset;
  22713. const type = uniform.getType();
  22714. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  22715. const b = this._getBufferForType( type );
  22716. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  22717. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  22718. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  22719. updated = true;
  22720. }
  22721. return updated;
  22722. }
  22723. updateVector4( uniform ) {
  22724. let updated = false;
  22725. const a = this.values;
  22726. const v = uniform.getValue();
  22727. const offset = uniform.offset;
  22728. const type = uniform.getType();
  22729. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  22730. const b = this._getBufferForType( type );
  22731. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  22732. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  22733. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  22734. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  22735. updated = true;
  22736. }
  22737. return updated;
  22738. }
  22739. updateColor( uniform ) {
  22740. let updated = false;
  22741. const a = this.values;
  22742. const c = uniform.getValue();
  22743. const offset = uniform.offset;
  22744. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  22745. const b = this.buffer;
  22746. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  22747. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  22748. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  22749. updated = true;
  22750. }
  22751. return updated;
  22752. }
  22753. updateMatrix3( uniform ) {
  22754. let updated = false;
  22755. const a = this.values;
  22756. const e = uniform.getValue().elements;
  22757. const offset = uniform.offset;
  22758. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  22759. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  22760. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  22761. const b = this.buffer;
  22762. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  22763. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  22764. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  22765. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  22766. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  22767. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  22768. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  22769. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  22770. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  22771. updated = true;
  22772. }
  22773. return updated;
  22774. }
  22775. updateMatrix4( uniform ) {
  22776. let updated = false;
  22777. const a = this.values;
  22778. const e = uniform.getValue().elements;
  22779. const offset = uniform.offset;
  22780. if ( arraysEqual( a, e, offset ) === false ) {
  22781. const b = this.buffer;
  22782. b.set( e, offset );
  22783. setArray( a, e, offset );
  22784. updated = true;
  22785. }
  22786. return updated;
  22787. }
  22788. _getBufferForType( type ) {
  22789. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  22790. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  22791. return this.buffer;
  22792. }
  22793. }
  22794. function setArray( a, b, offset ) {
  22795. for ( let i = 0, l = b.length; i < l; i ++ ) {
  22796. a[ offset + i ] = b[ i ];
  22797. }
  22798. }
  22799. function arraysEqual( a, b, offset ) {
  22800. for ( let i = 0, l = b.length; i < l; i ++ ) {
  22801. if ( a[ offset + i ] !== b[ i ] ) return false;
  22802. }
  22803. return true;
  22804. }
  22805. let _id$3 = 0;
  22806. class NodeUniformsGroup extends UniformsGroup {
  22807. constructor( name, groupNode ) {
  22808. super( name );
  22809. this.id = _id$3 ++;
  22810. this.groupNode = groupNode;
  22811. this.isNodeUniformsGroup = true;
  22812. }
  22813. getNodes() {
  22814. const nodes = [];
  22815. for ( const uniform of this.uniforms ) {
  22816. const node = uniform.nodeUniform.node;
  22817. if ( ! node ) throw new Error( 'NodeUniformsGroup: Uniform has no node.' );
  22818. nodes.push( node );
  22819. }
  22820. return nodes;
  22821. }
  22822. }
  22823. let _id$2 = 0;
  22824. class SampledTexture extends Binding {
  22825. constructor( name, texture ) {
  22826. super( name );
  22827. this.id = _id$2 ++;
  22828. this.texture = texture;
  22829. this.version = texture ? texture.version : 0;
  22830. this.store = false;
  22831. this.generation = null;
  22832. this.isSampledTexture = true;
  22833. }
  22834. needsBindingsUpdate( generation ) {
  22835. const { texture } = this;
  22836. if ( generation !== this.generation ) {
  22837. this.generation = generation;
  22838. return true;
  22839. }
  22840. return texture.isVideoTexture;
  22841. }
  22842. update() {
  22843. const { texture, version } = this;
  22844. if ( version !== texture.version ) {
  22845. this.version = texture.version;
  22846. return true;
  22847. }
  22848. return false;
  22849. }
  22850. }
  22851. class NodeSampledTexture extends SampledTexture {
  22852. constructor( name, textureNode, groupNode, access = null ) {
  22853. super( name, textureNode ? textureNode.value : null );
  22854. this.textureNode = textureNode;
  22855. this.groupNode = groupNode;
  22856. this.access = access;
  22857. }
  22858. needsBindingsUpdate( generation ) {
  22859. return this.textureNode.value !== this.texture || super.needsBindingsUpdate( generation );
  22860. }
  22861. update() {
  22862. const { textureNode } = this;
  22863. if ( this.texture !== textureNode.value ) {
  22864. this.texture = textureNode.value;
  22865. return true;
  22866. }
  22867. return super.update();
  22868. }
  22869. }
  22870. class NodeSampledCubeTexture extends NodeSampledTexture {
  22871. constructor( name, textureNode, groupNode, access ) {
  22872. super( name, textureNode, groupNode, access );
  22873. this.isSampledCubeTexture = true;
  22874. }
  22875. }
  22876. class NodeSampledTexture3D extends NodeSampledTexture {
  22877. constructor( name, textureNode, groupNode, access ) {
  22878. super( name, textureNode, groupNode, access );
  22879. this.isSampledTexture3D = true;
  22880. }
  22881. }
  22882. const glslMethods = {
  22883. atan2: 'atan',
  22884. textureDimensions: 'textureSize',
  22885. equals: 'equal'
  22886. };
  22887. const precisionLib = {
  22888. low: 'lowp',
  22889. medium: 'mediump',
  22890. high: 'highp'
  22891. };
  22892. const supports$1 = {
  22893. swizzleAssign: true,
  22894. storageBuffer: false
  22895. };
  22896. const defaultPrecisions = `
  22897. precision highp float;
  22898. precision highp int;
  22899. precision highp sampler2D;
  22900. precision highp sampler3D;
  22901. precision highp samplerCube;
  22902. precision highp sampler2DArray;
  22903. precision highp usampler2D;
  22904. precision highp usampler3D;
  22905. precision highp usamplerCube;
  22906. precision highp usampler2DArray;
  22907. precision highp isampler2D;
  22908. precision highp isampler3D;
  22909. precision highp isamplerCube;
  22910. precision highp isampler2DArray;
  22911. precision lowp sampler2DShadow;
  22912. `;
  22913. class GLSLNodeBuilder extends NodeBuilder {
  22914. constructor( object, renderer ) {
  22915. super( object, renderer, new GLSLNodeParser() );
  22916. this.uniformGroups = {};
  22917. this.transforms = [];
  22918. this.extensions = {};
  22919. this.builtins = { vertex: [], fragment: [], compute: [] };
  22920. this.useComparisonMethod = true;
  22921. }
  22922. needsToWorkingColorSpace( texture ) {
  22923. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  22924. }
  22925. getMethod( method ) {
  22926. return glslMethods[ method ] || method;
  22927. }
  22928. getOutputStructName() {
  22929. return '';
  22930. }
  22931. buildFunctionCode( shaderNode ) {
  22932. const layout = shaderNode.layout;
  22933. const flowData = this.flowShaderNode( shaderNode );
  22934. const parameters = [];
  22935. for ( const input of layout.inputs ) {
  22936. parameters.push( this.getType( input.type ) + ' ' + input.name );
  22937. }
  22938. //
  22939. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  22940. ${ flowData.vars }
  22941. ${ flowData.code }
  22942. return ${ flowData.result };
  22943. }`;
  22944. //
  22945. return code;
  22946. }
  22947. setupPBO( storageBufferNode ) {
  22948. const attribute = storageBufferNode.value;
  22949. if ( attribute.pbo === undefined ) {
  22950. const originalArray = attribute.array;
  22951. const numElements = attribute.count * attribute.itemSize;
  22952. const { itemSize } = attribute;
  22953. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  22954. let format = isInteger ? RedIntegerFormat : RedFormat;
  22955. if ( itemSize === 2 ) {
  22956. format = isInteger ? RGIntegerFormat : RGFormat;
  22957. } else if ( itemSize === 3 ) {
  22958. format = isInteger ? RGBIntegerFormat : RGBFormat;
  22959. } else if ( itemSize === 4 ) {
  22960. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  22961. }
  22962. const typeMap = {
  22963. Float32Array: FloatType,
  22964. Uint8Array: UnsignedByteType,
  22965. Uint16Array: UnsignedShortType,
  22966. Uint32Array: UnsignedIntType,
  22967. Int8Array: ByteType,
  22968. Int16Array: ShortType,
  22969. Int32Array: IntType,
  22970. Uint8ClampedArray: UnsignedByteType,
  22971. };
  22972. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  22973. let height = Math.ceil( ( numElements / itemSize ) / width );
  22974. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  22975. const newSize = width * height * itemSize;
  22976. const newArray = new originalArray.constructor( newSize );
  22977. newArray.set( originalArray, 0 );
  22978. attribute.array = newArray;
  22979. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  22980. pboTexture.needsUpdate = true;
  22981. pboTexture.isPBOTexture = true;
  22982. const pbo = new TextureNode( pboTexture, null, null );
  22983. pbo.setPrecision( 'high' );
  22984. attribute.pboNode = pbo;
  22985. attribute.pbo = pbo.value;
  22986. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  22987. }
  22988. }
  22989. getPropertyName( node, shaderStage = this.shaderStage ) {
  22990. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  22991. return shaderStage.charAt( 0 ) + '_' + node.name;
  22992. }
  22993. return super.getPropertyName( node, shaderStage );
  22994. }
  22995. generatePBO( storageArrayElementNode ) {
  22996. const { node, indexNode } = storageArrayElementNode;
  22997. const attribute = node.value;
  22998. if ( this.renderer.backend.has( attribute ) ) {
  22999. const attributeData = this.renderer.backend.get( attribute );
  23000. attributeData.pbo = attribute.pbo;
  23001. }
  23002. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  23003. const textureName = this.getPropertyName( nodeUniform );
  23004. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  23005. const indexSnippet = indexNode.build( this, 'uint' );
  23006. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  23007. let propertyName = elementNodeData.propertyName;
  23008. if ( propertyName === undefined ) {
  23009. // property element
  23010. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  23011. propertyName = this.getPropertyName( nodeVar );
  23012. // property size
  23013. const bufferNodeData = this.getDataFromNode( node );
  23014. let propertySizeName = bufferNodeData.propertySizeName;
  23015. if ( propertySizeName === undefined ) {
  23016. propertySizeName = propertyName + 'Size';
  23017. this.getVarFromNode( node, propertySizeName, 'uint' );
  23018. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  23019. bufferNodeData.propertySizeName = propertySizeName;
  23020. }
  23021. //
  23022. const { itemSize } = attribute;
  23023. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  23024. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  23025. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  23026. //
  23027. let prefix = 'vec4';
  23028. if ( attribute.pbo.type === UnsignedIntType ) {
  23029. prefix = 'uvec4';
  23030. } else if ( attribute.pbo.type === IntType ) {
  23031. prefix = 'ivec4';
  23032. }
  23033. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  23034. elementNodeData.propertyName = propertyName;
  23035. }
  23036. return propertyName;
  23037. }
  23038. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  23039. if ( depthSnippet ) {
  23040. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  23041. } else {
  23042. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  23043. }
  23044. }
  23045. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  23046. if ( texture.isDepthTexture ) {
  23047. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  23048. } else {
  23049. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  23050. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  23051. }
  23052. }
  23053. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  23054. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  23055. }
  23056. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
  23057. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  23058. }
  23059. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  23060. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  23061. }
  23062. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  23063. if ( shaderStage === 'fragment' ) {
  23064. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  23065. } else {
  23066. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  23067. }
  23068. }
  23069. getVars( shaderStage ) {
  23070. const snippets = [];
  23071. const vars = this.vars[ shaderStage ];
  23072. if ( vars !== undefined ) {
  23073. for ( const variable of vars ) {
  23074. snippets.push( `${ this.getVar( variable.type, variable.name ) };` );
  23075. }
  23076. }
  23077. return snippets.join( '\n\t' );
  23078. }
  23079. getUniforms( shaderStage ) {
  23080. const uniforms = this.uniforms[ shaderStage ];
  23081. const bindingSnippets = [];
  23082. const uniformGroups = {};
  23083. for ( const uniform of uniforms ) {
  23084. let snippet = null;
  23085. let group = false;
  23086. if ( uniform.type === 'texture' ) {
  23087. const texture = uniform.node.value;
  23088. let typePrefix = '';
  23089. if ( texture.isDataTexture === true ) {
  23090. if ( texture.type === UnsignedIntType ) {
  23091. typePrefix = 'u';
  23092. } else if ( texture.type === IntType ) {
  23093. typePrefix = 'i';
  23094. }
  23095. }
  23096. if ( texture.compareFunction ) {
  23097. snippet = `sampler2DShadow ${ uniform.name };`;
  23098. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  23099. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  23100. } else {
  23101. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  23102. }
  23103. } else if ( uniform.type === 'cubeTexture' ) {
  23104. snippet = `samplerCube ${ uniform.name };`;
  23105. } else if ( uniform.type === 'texture3D' ) {
  23106. snippet = `sampler3D ${ uniform.name };`;
  23107. } else if ( uniform.type === 'buffer' ) {
  23108. const bufferNode = uniform.node;
  23109. const bufferType = this.getType( bufferNode.bufferType );
  23110. const bufferCount = bufferNode.bufferCount;
  23111. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  23112. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  23113. } else {
  23114. const vectorType = this.getVectorType( uniform.type );
  23115. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  23116. group = true;
  23117. }
  23118. const precision = uniform.node.precision;
  23119. if ( precision !== null ) {
  23120. snippet = precisionLib[ precision ] + ' ' + snippet;
  23121. }
  23122. if ( group ) {
  23123. snippet = '\t' + snippet;
  23124. const groupName = uniform.groupNode.name;
  23125. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  23126. groupSnippets.push( snippet );
  23127. } else {
  23128. snippet = 'uniform ' + snippet;
  23129. bindingSnippets.push( snippet );
  23130. }
  23131. }
  23132. let output = '';
  23133. for ( const name in uniformGroups ) {
  23134. const groupSnippets = uniformGroups[ name ];
  23135. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  23136. }
  23137. output += bindingSnippets.join( '\n' );
  23138. return output;
  23139. }
  23140. getTypeFromAttribute( attribute ) {
  23141. let nodeType = super.getTypeFromAttribute( attribute );
  23142. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  23143. let dataAttribute = attribute;
  23144. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  23145. const array = dataAttribute.array;
  23146. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  23147. nodeType = nodeType.slice( 1 );
  23148. }
  23149. }
  23150. return nodeType;
  23151. }
  23152. getAttributes( shaderStage ) {
  23153. let snippet = '';
  23154. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  23155. const attributes = this.getAttributesArray();
  23156. let location = 0;
  23157. for ( const attribute of attributes ) {
  23158. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  23159. }
  23160. }
  23161. return snippet;
  23162. }
  23163. getStructMembers( struct ) {
  23164. const snippets = [];
  23165. const members = struct.getMemberTypes();
  23166. for ( let i = 0; i < members.length; i ++ ) {
  23167. const member = members[ i ];
  23168. snippets.push( `layout( location = ${i} ) out ${ member} m${i};` );
  23169. }
  23170. return snippets.join( '\n' );
  23171. }
  23172. getStructs( shaderStage ) {
  23173. const snippets = [];
  23174. const structs = this.structs[ shaderStage ];
  23175. if ( structs.length === 0 ) {
  23176. return 'layout( location = 0 ) out vec4 fragColor;\n';
  23177. }
  23178. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  23179. const struct = structs[ index ];
  23180. let snippet = '\n';
  23181. snippet += this.getStructMembers( struct );
  23182. snippet += '\n';
  23183. snippets.push( snippet );
  23184. }
  23185. return snippets.join( '\n\n' );
  23186. }
  23187. getVaryings( shaderStage ) {
  23188. let snippet = '';
  23189. const varyings = this.varyings;
  23190. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  23191. for ( const varying of varyings ) {
  23192. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  23193. const type = this.getType( varying.type );
  23194. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  23195. snippet += `${flat}${varying.needsInterpolation ? 'out' : '/*out*/'} ${type} ${varying.name};\n`;
  23196. }
  23197. } else if ( shaderStage === 'fragment' ) {
  23198. for ( const varying of varyings ) {
  23199. if ( varying.needsInterpolation ) {
  23200. const type = this.getType( varying.type );
  23201. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  23202. snippet += `${flat}in ${type} ${varying.name};\n`;
  23203. }
  23204. }
  23205. }
  23206. for ( const builtin of this.builtins[ shaderStage ] ) {
  23207. snippet += `${builtin};\n`;
  23208. }
  23209. return snippet;
  23210. }
  23211. getVertexIndex() {
  23212. return 'uint( gl_VertexID )';
  23213. }
  23214. getInstanceIndex() {
  23215. return 'uint( gl_InstanceID )';
  23216. }
  23217. getInvocationLocalIndex() {
  23218. const workgroupSize = this.object.workgroupSize;
  23219. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  23220. return `uint( gl_InstanceID ) % ${size}u`;
  23221. }
  23222. getDrawIndex() {
  23223. const extensions = this.renderer.backend.extensions;
  23224. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  23225. return 'uint( gl_DrawID )';
  23226. }
  23227. return null;
  23228. }
  23229. getFrontFacing() {
  23230. return 'gl_FrontFacing';
  23231. }
  23232. getFragCoord() {
  23233. return 'gl_FragCoord.xy';
  23234. }
  23235. getFragDepth() {
  23236. return 'gl_FragDepth';
  23237. }
  23238. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  23239. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  23240. if ( map.has( name ) === false ) {
  23241. map.set( name, {
  23242. name,
  23243. behavior
  23244. } );
  23245. }
  23246. }
  23247. getExtensions( shaderStage ) {
  23248. const snippets = [];
  23249. if ( shaderStage === 'vertex' ) {
  23250. const ext = this.renderer.backend.extensions;
  23251. const isBatchedMesh = this.object.isBatchedMesh;
  23252. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  23253. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  23254. }
  23255. }
  23256. const extensions = this.extensions[ shaderStage ];
  23257. if ( extensions !== undefined ) {
  23258. for ( const { name, behavior } of extensions.values() ) {
  23259. snippets.push( `#extension ${name} : ${behavior}` );
  23260. }
  23261. }
  23262. return snippets.join( '\n' );
  23263. }
  23264. getClipDistance() {
  23265. return 'gl_ClipDistance';
  23266. }
  23267. isAvailable( name ) {
  23268. let result = supports$1[ name ];
  23269. if ( result === undefined ) {
  23270. let extensionName;
  23271. result = false;
  23272. switch ( name ) {
  23273. case 'float32Filterable':
  23274. extensionName = 'OES_texture_float_linear';
  23275. break;
  23276. case 'clipDistance':
  23277. extensionName = 'WEBGL_clip_cull_distance';
  23278. break;
  23279. }
  23280. if ( extensionName !== undefined ) {
  23281. const extensions = this.renderer.backend.extensions;
  23282. if ( extensions.has( extensionName ) ) {
  23283. extensions.get( extensionName );
  23284. result = true;
  23285. }
  23286. }
  23287. supports$1[ name ] = result;
  23288. }
  23289. return result;
  23290. }
  23291. isFlipY() {
  23292. return true;
  23293. }
  23294. enableHardwareClipping( planeCount ) {
  23295. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  23296. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  23297. }
  23298. registerTransform( varyingName, attributeNode ) {
  23299. this.transforms.push( { varyingName, attributeNode } );
  23300. }
  23301. getTransforms( /* shaderStage */ ) {
  23302. const transforms = this.transforms;
  23303. let snippet = '';
  23304. for ( let i = 0; i < transforms.length; i ++ ) {
  23305. const transform = transforms[ i ];
  23306. const attributeName = this.getPropertyName( transform.attributeNode );
  23307. snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  23308. }
  23309. return snippet;
  23310. }
  23311. _getGLSLUniformStruct( name, vars ) {
  23312. return `
  23313. layout( std140 ) uniform ${name} {
  23314. ${vars}
  23315. };`;
  23316. }
  23317. _getGLSLVertexCode( shaderData ) {
  23318. return `#version 300 es
  23319. ${ this.getSignature() }
  23320. // extensions
  23321. ${shaderData.extensions}
  23322. // precision
  23323. ${ defaultPrecisions }
  23324. // uniforms
  23325. ${shaderData.uniforms}
  23326. // varyings
  23327. ${shaderData.varyings}
  23328. // attributes
  23329. ${shaderData.attributes}
  23330. // codes
  23331. ${shaderData.codes}
  23332. void main() {
  23333. // vars
  23334. ${shaderData.vars}
  23335. // transforms
  23336. ${shaderData.transforms}
  23337. // flow
  23338. ${shaderData.flow}
  23339. gl_PointSize = 1.0;
  23340. }
  23341. `;
  23342. }
  23343. _getGLSLFragmentCode( shaderData ) {
  23344. return `#version 300 es
  23345. ${ this.getSignature() }
  23346. // precision
  23347. ${ defaultPrecisions }
  23348. // uniforms
  23349. ${shaderData.uniforms}
  23350. // varyings
  23351. ${shaderData.varyings}
  23352. // codes
  23353. ${shaderData.codes}
  23354. ${shaderData.structs}
  23355. void main() {
  23356. // vars
  23357. ${shaderData.vars}
  23358. // flow
  23359. ${shaderData.flow}
  23360. }
  23361. `;
  23362. }
  23363. buildCode() {
  23364. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  23365. this.sortBindingGroups();
  23366. for ( const shaderStage in shadersData ) {
  23367. let flow = '// code\n\n';
  23368. flow += this.flowCode[ shaderStage ];
  23369. const flowNodes = this.flowNodes[ shaderStage ];
  23370. const mainNode = flowNodes[ flowNodes.length - 1 ];
  23371. for ( const node of flowNodes ) {
  23372. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  23373. const slotName = node.name;
  23374. if ( slotName ) {
  23375. if ( flow.length > 0 ) flow += '\n';
  23376. flow += `\t// flow -> ${ slotName }\n\t`;
  23377. }
  23378. flow += `${ flowSlotData.code }\n\t`;
  23379. if ( node === mainNode && shaderStage !== 'compute' ) {
  23380. flow += '// result\n\t';
  23381. if ( shaderStage === 'vertex' ) {
  23382. flow += 'gl_Position = ';
  23383. flow += `${ flowSlotData.result };`;
  23384. } else if ( shaderStage === 'fragment' ) {
  23385. if ( ! node.outputNode.isOutputStructNode ) {
  23386. flow += 'fragColor = ';
  23387. flow += `${ flowSlotData.result };`;
  23388. }
  23389. }
  23390. }
  23391. }
  23392. const stageData = shadersData[ shaderStage ];
  23393. stageData.extensions = this.getExtensions( shaderStage );
  23394. stageData.uniforms = this.getUniforms( shaderStage );
  23395. stageData.attributes = this.getAttributes( shaderStage );
  23396. stageData.varyings = this.getVaryings( shaderStage );
  23397. stageData.vars = this.getVars( shaderStage );
  23398. stageData.structs = this.getStructs( shaderStage );
  23399. stageData.codes = this.getCodes( shaderStage );
  23400. stageData.transforms = this.getTransforms( shaderStage );
  23401. stageData.flow = flow;
  23402. }
  23403. if ( this.material !== null ) {
  23404. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  23405. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  23406. } else {
  23407. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  23408. }
  23409. }
  23410. getUniformFromNode( node, type, shaderStage, name = null ) {
  23411. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  23412. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  23413. let uniformGPU = nodeData.uniformGPU;
  23414. if ( uniformGPU === undefined ) {
  23415. const group = node.groupNode;
  23416. const groupName = group.name;
  23417. const bindings = this.getBindGroupArray( groupName, shaderStage );
  23418. if ( type === 'texture' ) {
  23419. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  23420. bindings.push( uniformGPU );
  23421. } else if ( type === 'cubeTexture' ) {
  23422. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  23423. bindings.push( uniformGPU );
  23424. } else if ( type === 'texture3D' ) {
  23425. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  23426. bindings.push( uniformGPU );
  23427. } else if ( type === 'buffer' ) {
  23428. node.name = `NodeBuffer_${ node.id }`;
  23429. uniformNode.name = `buffer${ node.id }`;
  23430. const buffer = new NodeUniformBuffer( node, group );
  23431. buffer.name = node.name;
  23432. bindings.push( buffer );
  23433. uniformGPU = buffer;
  23434. } else {
  23435. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  23436. let uniformsGroup = uniformsStage[ groupName ];
  23437. if ( uniformsGroup === undefined ) {
  23438. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  23439. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  23440. uniformsStage[ groupName ] = uniformsGroup;
  23441. bindings.push( uniformsGroup );
  23442. }
  23443. uniformGPU = this.getNodeUniform( uniformNode, type );
  23444. uniformsGroup.addUniform( uniformGPU );
  23445. }
  23446. nodeData.uniformGPU = uniformGPU;
  23447. }
  23448. return uniformNode;
  23449. }
  23450. }
  23451. let vector2 = null;
  23452. let vector4 = null;
  23453. let color4 = null;
  23454. class Backend {
  23455. constructor( parameters = {} ) {
  23456. this.parameters = Object.assign( {}, parameters );
  23457. this.data = new WeakMap();
  23458. this.renderer = null;
  23459. this.domElement = null;
  23460. }
  23461. async init( renderer ) {
  23462. this.renderer = renderer;
  23463. }
  23464. // render context
  23465. begin( /*renderContext*/ ) { }
  23466. finish( /*renderContext*/ ) { }
  23467. // render object
  23468. draw( /*renderObject, info*/ ) { }
  23469. // program
  23470. createProgram( /*program*/ ) { }
  23471. destroyProgram( /*program*/ ) { }
  23472. // bindings
  23473. createBindings( /*bingGroup, bindings*/ ) { }
  23474. updateBindings( /*bingGroup, bindings*/ ) { }
  23475. // pipeline
  23476. createRenderPipeline( /*renderObject*/ ) { }
  23477. createComputePipeline( /*computeNode, pipeline*/ ) { }
  23478. destroyPipeline( /*pipeline*/ ) { }
  23479. // cache key
  23480. needsRenderUpdate( /*renderObject*/ ) { } // return Boolean ( fast test )
  23481. getRenderCacheKey( /*renderObject*/ ) { } // return String
  23482. // node builder
  23483. createNodeBuilder( /*renderObject*/ ) { } // return NodeBuilder (ADD IT)
  23484. // textures
  23485. createSampler( /*texture*/ ) { }
  23486. createDefaultTexture( /*texture*/ ) { }
  23487. createTexture( /*texture*/ ) { }
  23488. copyTextureToBuffer( /*texture, x, y, width, height*/ ) {}
  23489. // attributes
  23490. createAttribute( /*attribute*/ ) { }
  23491. createIndexAttribute( /*attribute*/ ) { }
  23492. updateAttribute( /*attribute*/ ) { }
  23493. destroyAttribute( /*attribute*/ ) { }
  23494. // canvas
  23495. getContext() { }
  23496. updateSize() { }
  23497. // utils
  23498. resolveTimestampAsync( /*renderContext, type*/ ) { }
  23499. hasFeatureAsync( /*name*/ ) { } // return Boolean
  23500. hasFeature( /*name*/ ) { } // return Boolean
  23501. getInstanceCount( renderObject ) {
  23502. const { object, geometry } = renderObject;
  23503. return geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  23504. }
  23505. getDrawingBufferSize() {
  23506. vector2 = vector2 || new Vector2();
  23507. return this.renderer.getDrawingBufferSize( vector2 );
  23508. }
  23509. getScissor() {
  23510. vector4 = vector4 || new Vector4();
  23511. return this.renderer.getScissor( vector4 );
  23512. }
  23513. setScissorTest( /*boolean*/ ) { }
  23514. getClearColor() {
  23515. const renderer = this.renderer;
  23516. color4 = color4 || new Color4();
  23517. renderer.getClearColor( color4 );
  23518. color4.getRGB( color4, this.renderer.currentColorSpace );
  23519. return color4;
  23520. }
  23521. getDomElement() {
  23522. let domElement = this.domElement;
  23523. if ( domElement === null ) {
  23524. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  23525. // OffscreenCanvas does not have setAttribute, see #22811
  23526. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  23527. this.domElement = domElement;
  23528. }
  23529. return domElement;
  23530. }
  23531. // resource properties
  23532. set( object, value ) {
  23533. this.data.set( object, value );
  23534. }
  23535. get( object ) {
  23536. let map = this.data.get( object );
  23537. if ( map === undefined ) {
  23538. map = {};
  23539. this.data.set( object, map );
  23540. }
  23541. return map;
  23542. }
  23543. has( object ) {
  23544. return this.data.has( object );
  23545. }
  23546. delete( object ) {
  23547. this.data.delete( object );
  23548. }
  23549. dispose() { }
  23550. }
  23551. let _id$1 = 0;
  23552. class DualAttributeData {
  23553. constructor( attributeData, dualBuffer ) {
  23554. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  23555. this.type = attributeData.type;
  23556. this.bufferType = attributeData.bufferType;
  23557. this.pbo = attributeData.pbo;
  23558. this.byteLength = attributeData.byteLength;
  23559. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  23560. this.version = attributeData.version;
  23561. this.isInteger = attributeData.isInteger;
  23562. this.activeBufferIndex = 0;
  23563. this.baseId = attributeData.id;
  23564. }
  23565. get id() {
  23566. return `${ this.baseId }|${ this.activeBufferIndex }`;
  23567. }
  23568. get bufferGPU() {
  23569. return this.buffers[ this.activeBufferIndex ];
  23570. }
  23571. get transformBuffer() {
  23572. return this.buffers[ this.activeBufferIndex ^ 1 ];
  23573. }
  23574. switchBuffers() {
  23575. this.activeBufferIndex ^= 1;
  23576. }
  23577. }
  23578. class WebGLAttributeUtils {
  23579. constructor( backend ) {
  23580. this.backend = backend;
  23581. }
  23582. createAttribute( attribute, bufferType ) {
  23583. const backend = this.backend;
  23584. const { gl } = backend;
  23585. const array = attribute.array;
  23586. const usage = attribute.usage || gl.STATIC_DRAW;
  23587. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  23588. const bufferData = backend.get( bufferAttribute );
  23589. let bufferGPU = bufferData.bufferGPU;
  23590. if ( bufferGPU === undefined ) {
  23591. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  23592. bufferData.bufferGPU = bufferGPU;
  23593. bufferData.bufferType = bufferType;
  23594. bufferData.version = bufferAttribute.version;
  23595. }
  23596. //attribute.onUploadCallback();
  23597. let type;
  23598. if ( array instanceof Float32Array ) {
  23599. type = gl.FLOAT;
  23600. } else if ( array instanceof Uint16Array ) {
  23601. if ( attribute.isFloat16BufferAttribute ) {
  23602. type = gl.HALF_FLOAT;
  23603. } else {
  23604. type = gl.UNSIGNED_SHORT;
  23605. }
  23606. } else if ( array instanceof Int16Array ) {
  23607. type = gl.SHORT;
  23608. } else if ( array instanceof Uint32Array ) {
  23609. type = gl.UNSIGNED_INT;
  23610. } else if ( array instanceof Int32Array ) {
  23611. type = gl.INT;
  23612. } else if ( array instanceof Int8Array ) {
  23613. type = gl.BYTE;
  23614. } else if ( array instanceof Uint8Array ) {
  23615. type = gl.UNSIGNED_BYTE;
  23616. } else if ( array instanceof Uint8ClampedArray ) {
  23617. type = gl.UNSIGNED_BYTE;
  23618. } else {
  23619. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  23620. }
  23621. let attributeData = {
  23622. bufferGPU,
  23623. bufferType,
  23624. type,
  23625. byteLength: array.byteLength,
  23626. bytesPerElement: array.BYTES_PER_ELEMENT,
  23627. version: attribute.version,
  23628. pbo: attribute.pbo,
  23629. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  23630. id: _id$1 ++
  23631. };
  23632. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  23633. // create buffer for tranform feedback use
  23634. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  23635. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  23636. }
  23637. backend.set( attribute, attributeData );
  23638. }
  23639. updateAttribute( attribute ) {
  23640. const backend = this.backend;
  23641. const { gl } = backend;
  23642. const array = attribute.array;
  23643. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  23644. const bufferData = backend.get( bufferAttribute );
  23645. const bufferType = bufferData.bufferType;
  23646. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  23647. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  23648. if ( updateRanges.length === 0 ) {
  23649. // Not using update ranges
  23650. gl.bufferSubData( bufferType, 0, array );
  23651. } else {
  23652. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  23653. const range = updateRanges[ i ];
  23654. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  23655. array, range.start, range.count );
  23656. }
  23657. bufferAttribute.clearUpdateRanges();
  23658. }
  23659. gl.bindBuffer( bufferType, null );
  23660. bufferData.version = bufferAttribute.version;
  23661. }
  23662. destroyAttribute( attribute ) {
  23663. const backend = this.backend;
  23664. const { gl } = backend;
  23665. if ( attribute.isInterleavedBufferAttribute ) {
  23666. backend.delete( attribute.data );
  23667. }
  23668. const attributeData = backend.get( attribute );
  23669. gl.deleteBuffer( attributeData.bufferGPU );
  23670. backend.delete( attribute );
  23671. }
  23672. async getArrayBufferAsync( attribute ) {
  23673. const backend = this.backend;
  23674. const { gl } = backend;
  23675. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  23676. const { bufferGPU } = backend.get( bufferAttribute );
  23677. const array = attribute.array;
  23678. const byteLength = array.byteLength;
  23679. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  23680. const writeBuffer = gl.createBuffer();
  23681. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  23682. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  23683. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  23684. await backend.utils._clientWaitAsync();
  23685. const dstBuffer = new attribute.array.constructor( array.length );
  23686. // Ensure the buffer is bound before reading
  23687. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  23688. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  23689. gl.deleteBuffer( writeBuffer );
  23690. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  23691. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  23692. return dstBuffer.buffer;
  23693. }
  23694. _createBuffer( gl, bufferType, array, usage ) {
  23695. const bufferGPU = gl.createBuffer();
  23696. gl.bindBuffer( bufferType, bufferGPU );
  23697. gl.bufferData( bufferType, array, usage );
  23698. gl.bindBuffer( bufferType, null );
  23699. return bufferGPU;
  23700. }
  23701. }
  23702. let initialized$1 = false, equationToGL, factorToGL;
  23703. class WebGLState {
  23704. constructor( backend ) {
  23705. this.backend = backend;
  23706. this.gl = this.backend.gl;
  23707. this.enabled = {};
  23708. this.currentFlipSided = null;
  23709. this.currentCullFace = null;
  23710. this.currentProgram = null;
  23711. this.currentBlendingEnabled = false;
  23712. this.currentBlending = null;
  23713. this.currentBlendSrc = null;
  23714. this.currentBlendDst = null;
  23715. this.currentBlendSrcAlpha = null;
  23716. this.currentBlendDstAlpha = null;
  23717. this.currentPremultipledAlpha = null;
  23718. this.currentPolygonOffsetFactor = null;
  23719. this.currentPolygonOffsetUnits = null;
  23720. this.currentColorMask = null;
  23721. this.currentDepthFunc = null;
  23722. this.currentDepthMask = null;
  23723. this.currentStencilFunc = null;
  23724. this.currentStencilRef = null;
  23725. this.currentStencilFuncMask = null;
  23726. this.currentStencilFail = null;
  23727. this.currentStencilZFail = null;
  23728. this.currentStencilZPass = null;
  23729. this.currentStencilMask = null;
  23730. this.currentLineWidth = null;
  23731. this.currentClippingPlanes = 0;
  23732. this.currentBoundFramebuffers = {};
  23733. this.currentDrawbuffers = new WeakMap();
  23734. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  23735. this.currentTextureSlot = null;
  23736. this.currentBoundTextures = {};
  23737. this.currentBoundBufferBases = {};
  23738. if ( initialized$1 === false ) {
  23739. this._init( this.gl );
  23740. initialized$1 = true;
  23741. }
  23742. }
  23743. _init( gl ) {
  23744. // Store only WebGL constants here.
  23745. equationToGL = {
  23746. [ AddEquation ]: gl.FUNC_ADD,
  23747. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  23748. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  23749. };
  23750. factorToGL = {
  23751. [ ZeroFactor ]: gl.ZERO,
  23752. [ OneFactor ]: gl.ONE,
  23753. [ SrcColorFactor ]: gl.SRC_COLOR,
  23754. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  23755. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  23756. [ DstColorFactor ]: gl.DST_COLOR,
  23757. [ DstAlphaFactor ]: gl.DST_ALPHA,
  23758. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  23759. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  23760. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  23761. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  23762. };
  23763. }
  23764. enable( id ) {
  23765. const { enabled } = this;
  23766. if ( enabled[ id ] !== true ) {
  23767. this.gl.enable( id );
  23768. enabled[ id ] = true;
  23769. }
  23770. }
  23771. disable( id ) {
  23772. const { enabled } = this;
  23773. if ( enabled[ id ] !== false ) {
  23774. this.gl.disable( id );
  23775. enabled[ id ] = false;
  23776. }
  23777. }
  23778. setFlipSided( flipSided ) {
  23779. if ( this.currentFlipSided !== flipSided ) {
  23780. const { gl } = this;
  23781. if ( flipSided ) {
  23782. gl.frontFace( gl.CW );
  23783. } else {
  23784. gl.frontFace( gl.CCW );
  23785. }
  23786. this.currentFlipSided = flipSided;
  23787. }
  23788. }
  23789. setCullFace( cullFace ) {
  23790. const { gl } = this;
  23791. if ( cullFace !== CullFaceNone ) {
  23792. this.enable( gl.CULL_FACE );
  23793. if ( cullFace !== this.currentCullFace ) {
  23794. if ( cullFace === CullFaceBack ) {
  23795. gl.cullFace( gl.BACK );
  23796. } else if ( cullFace === CullFaceFront ) {
  23797. gl.cullFace( gl.FRONT );
  23798. } else {
  23799. gl.cullFace( gl.FRONT_AND_BACK );
  23800. }
  23801. }
  23802. } else {
  23803. this.disable( gl.CULL_FACE );
  23804. }
  23805. this.currentCullFace = cullFace;
  23806. }
  23807. setLineWidth( width ) {
  23808. const { currentLineWidth, gl } = this;
  23809. if ( width !== currentLineWidth ) {
  23810. gl.lineWidth( width );
  23811. this.currentLineWidth = width;
  23812. }
  23813. }
  23814. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  23815. const { gl } = this;
  23816. if ( blending === NoBlending ) {
  23817. if ( this.currentBlendingEnabled === true ) {
  23818. this.disable( gl.BLEND );
  23819. this.currentBlendingEnabled = false;
  23820. }
  23821. return;
  23822. }
  23823. if ( this.currentBlendingEnabled === false ) {
  23824. this.enable( gl.BLEND );
  23825. this.currentBlendingEnabled = true;
  23826. }
  23827. if ( blending !== CustomBlending ) {
  23828. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  23829. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  23830. gl.blendEquation( gl.FUNC_ADD );
  23831. this.currentBlendEquation = AddEquation;
  23832. this.currentBlendEquationAlpha = AddEquation;
  23833. }
  23834. if ( premultipliedAlpha ) {
  23835. switch ( blending ) {
  23836. case NormalBlending:
  23837. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  23838. break;
  23839. case AdditiveBlending:
  23840. gl.blendFunc( gl.ONE, gl.ONE );
  23841. break;
  23842. case SubtractiveBlending:
  23843. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  23844. break;
  23845. case MultiplyBlending:
  23846. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  23847. break;
  23848. default:
  23849. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  23850. break;
  23851. }
  23852. } else {
  23853. switch ( blending ) {
  23854. case NormalBlending:
  23855. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  23856. break;
  23857. case AdditiveBlending:
  23858. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  23859. break;
  23860. case SubtractiveBlending:
  23861. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  23862. break;
  23863. case MultiplyBlending:
  23864. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  23865. break;
  23866. default:
  23867. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  23868. break;
  23869. }
  23870. }
  23871. this.currentBlendSrc = null;
  23872. this.currentBlendDst = null;
  23873. this.currentBlendSrcAlpha = null;
  23874. this.currentBlendDstAlpha = null;
  23875. this.currentBlending = blending;
  23876. this.currentPremultipledAlpha = premultipliedAlpha;
  23877. }
  23878. return;
  23879. }
  23880. // custom blending
  23881. blendEquationAlpha = blendEquationAlpha || blendEquation;
  23882. blendSrcAlpha = blendSrcAlpha || blendSrc;
  23883. blendDstAlpha = blendDstAlpha || blendDst;
  23884. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  23885. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  23886. this.currentBlendEquation = blendEquation;
  23887. this.currentBlendEquationAlpha = blendEquationAlpha;
  23888. }
  23889. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  23890. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  23891. this.currentBlendSrc = blendSrc;
  23892. this.currentBlendDst = blendDst;
  23893. this.currentBlendSrcAlpha = blendSrcAlpha;
  23894. this.currentBlendDstAlpha = blendDstAlpha;
  23895. }
  23896. this.currentBlending = blending;
  23897. this.currentPremultipledAlpha = false;
  23898. }
  23899. setColorMask( colorMask ) {
  23900. if ( this.currentColorMask !== colorMask ) {
  23901. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  23902. this.currentColorMask = colorMask;
  23903. }
  23904. }
  23905. setDepthTest( depthTest ) {
  23906. const { gl } = this;
  23907. if ( depthTest ) {
  23908. this.enable( gl.DEPTH_TEST );
  23909. } else {
  23910. this.disable( gl.DEPTH_TEST );
  23911. }
  23912. }
  23913. setDepthMask( depthMask ) {
  23914. if ( this.currentDepthMask !== depthMask ) {
  23915. this.gl.depthMask( depthMask );
  23916. this.currentDepthMask = depthMask;
  23917. }
  23918. }
  23919. setDepthFunc( depthFunc ) {
  23920. if ( this.currentDepthFunc !== depthFunc ) {
  23921. const { gl } = this;
  23922. switch ( depthFunc ) {
  23923. case NeverDepth:
  23924. gl.depthFunc( gl.NEVER );
  23925. break;
  23926. case AlwaysDepth:
  23927. gl.depthFunc( gl.ALWAYS );
  23928. break;
  23929. case LessDepth:
  23930. gl.depthFunc( gl.LESS );
  23931. break;
  23932. case LessEqualDepth:
  23933. gl.depthFunc( gl.LEQUAL );
  23934. break;
  23935. case EqualDepth:
  23936. gl.depthFunc( gl.EQUAL );
  23937. break;
  23938. case GreaterEqualDepth:
  23939. gl.depthFunc( gl.GEQUAL );
  23940. break;
  23941. case GreaterDepth:
  23942. gl.depthFunc( gl.GREATER );
  23943. break;
  23944. case NotEqualDepth:
  23945. gl.depthFunc( gl.NOTEQUAL );
  23946. break;
  23947. default:
  23948. gl.depthFunc( gl.LEQUAL );
  23949. }
  23950. this.currentDepthFunc = depthFunc;
  23951. }
  23952. }
  23953. setStencilTest( stencilTest ) {
  23954. const { gl } = this;
  23955. if ( stencilTest ) {
  23956. this.enable( gl.STENCIL_TEST );
  23957. } else {
  23958. this.disable( gl.STENCIL_TEST );
  23959. }
  23960. }
  23961. setStencilMask( stencilMask ) {
  23962. if ( this.currentStencilMask !== stencilMask ) {
  23963. this.gl.stencilMask( stencilMask );
  23964. this.currentStencilMask = stencilMask;
  23965. }
  23966. }
  23967. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  23968. if ( this.currentStencilFunc !== stencilFunc ||
  23969. this.currentStencilRef !== stencilRef ||
  23970. this.currentStencilFuncMask !== stencilMask ) {
  23971. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  23972. this.currentStencilFunc = stencilFunc;
  23973. this.currentStencilRef = stencilRef;
  23974. this.currentStencilFuncMask = stencilMask;
  23975. }
  23976. }
  23977. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  23978. if ( this.currentStencilFail !== stencilFail ||
  23979. this.currentStencilZFail !== stencilZFail ||
  23980. this.currentStencilZPass !== stencilZPass ) {
  23981. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  23982. this.currentStencilFail = stencilFail;
  23983. this.currentStencilZFail = stencilZFail;
  23984. this.currentStencilZPass = stencilZPass;
  23985. }
  23986. }
  23987. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  23988. const { gl } = this;
  23989. material.side === DoubleSide
  23990. ? this.disable( gl.CULL_FACE )
  23991. : this.enable( gl.CULL_FACE );
  23992. let flipSided = ( material.side === BackSide );
  23993. if ( frontFaceCW ) flipSided = ! flipSided;
  23994. this.setFlipSided( flipSided );
  23995. ( material.blending === NormalBlending && material.transparent === false )
  23996. ? this.setBlending( NoBlending )
  23997. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  23998. this.setDepthFunc( material.depthFunc );
  23999. this.setDepthTest( material.depthTest );
  24000. this.setDepthMask( material.depthWrite );
  24001. this.setColorMask( material.colorWrite );
  24002. const stencilWrite = material.stencilWrite;
  24003. this.setStencilTest( stencilWrite );
  24004. if ( stencilWrite ) {
  24005. this.setStencilMask( material.stencilWriteMask );
  24006. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  24007. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  24008. }
  24009. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  24010. material.alphaToCoverage === true && this.backend.renderer.samples > 1
  24011. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  24012. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  24013. if ( hardwareClippingPlanes > 0 ) {
  24014. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  24015. const CLIP_DISTANCE0_WEBGL = 0x3000;
  24016. for ( let i = 0; i < 8; i ++ ) {
  24017. if ( i < hardwareClippingPlanes ) {
  24018. this.enable( CLIP_DISTANCE0_WEBGL + i );
  24019. } else {
  24020. this.disable( CLIP_DISTANCE0_WEBGL + i );
  24021. }
  24022. }
  24023. }
  24024. }
  24025. }
  24026. setPolygonOffset( polygonOffset, factor, units ) {
  24027. const { gl } = this;
  24028. if ( polygonOffset ) {
  24029. this.enable( gl.POLYGON_OFFSET_FILL );
  24030. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  24031. gl.polygonOffset( factor, units );
  24032. this.currentPolygonOffsetFactor = factor;
  24033. this.currentPolygonOffsetUnits = units;
  24034. }
  24035. } else {
  24036. this.disable( gl.POLYGON_OFFSET_FILL );
  24037. }
  24038. }
  24039. useProgram( program ) {
  24040. if ( this.currentProgram !== program ) {
  24041. this.gl.useProgram( program );
  24042. this.currentProgram = program;
  24043. return true;
  24044. }
  24045. return false;
  24046. }
  24047. // framebuffer
  24048. bindFramebuffer( target, framebuffer ) {
  24049. const { gl, currentBoundFramebuffers } = this;
  24050. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  24051. gl.bindFramebuffer( target, framebuffer );
  24052. currentBoundFramebuffers[ target ] = framebuffer;
  24053. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  24054. if ( target === gl.DRAW_FRAMEBUFFER ) {
  24055. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  24056. }
  24057. if ( target === gl.FRAMEBUFFER ) {
  24058. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  24059. }
  24060. return true;
  24061. }
  24062. return false;
  24063. }
  24064. drawBuffers( renderContext, framebuffer ) {
  24065. const { gl } = this;
  24066. let drawBuffers = [];
  24067. let needsUpdate = false;
  24068. if ( renderContext.textures !== null ) {
  24069. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  24070. if ( drawBuffers === undefined ) {
  24071. drawBuffers = [];
  24072. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  24073. }
  24074. const textures = renderContext.textures;
  24075. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  24076. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  24077. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  24078. }
  24079. drawBuffers.length = textures.length;
  24080. needsUpdate = true;
  24081. }
  24082. } else {
  24083. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  24084. drawBuffers[ 0 ] = gl.BACK;
  24085. needsUpdate = true;
  24086. }
  24087. }
  24088. if ( needsUpdate ) {
  24089. gl.drawBuffers( drawBuffers );
  24090. }
  24091. }
  24092. // texture
  24093. activeTexture( webglSlot ) {
  24094. const { gl, currentTextureSlot, maxTextures } = this;
  24095. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  24096. if ( currentTextureSlot !== webglSlot ) {
  24097. gl.activeTexture( webglSlot );
  24098. this.currentTextureSlot = webglSlot;
  24099. }
  24100. }
  24101. bindTexture( webglType, webglTexture, webglSlot ) {
  24102. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  24103. if ( webglSlot === undefined ) {
  24104. if ( currentTextureSlot === null ) {
  24105. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  24106. } else {
  24107. webglSlot = currentTextureSlot;
  24108. }
  24109. }
  24110. let boundTexture = currentBoundTextures[ webglSlot ];
  24111. if ( boundTexture === undefined ) {
  24112. boundTexture = { type: undefined, texture: undefined };
  24113. currentBoundTextures[ webglSlot ] = boundTexture;
  24114. }
  24115. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  24116. if ( currentTextureSlot !== webglSlot ) {
  24117. gl.activeTexture( webglSlot );
  24118. this.currentTextureSlot = webglSlot;
  24119. }
  24120. gl.bindTexture( webglType, webglTexture );
  24121. boundTexture.type = webglType;
  24122. boundTexture.texture = webglTexture;
  24123. }
  24124. }
  24125. bindBufferBase( target, index, buffer ) {
  24126. const { gl } = this;
  24127. const key = `${target}-${index}`;
  24128. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  24129. gl.bindBufferBase( target, index, buffer );
  24130. this.currentBoundBufferBases[ key ] = buffer;
  24131. return true;
  24132. }
  24133. return false;
  24134. }
  24135. unbindTexture() {
  24136. const { gl, currentTextureSlot, currentBoundTextures } = this;
  24137. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  24138. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  24139. gl.bindTexture( boundTexture.type, null );
  24140. boundTexture.type = undefined;
  24141. boundTexture.texture = undefined;
  24142. }
  24143. }
  24144. }
  24145. class WebGLUtils {
  24146. constructor( backend ) {
  24147. this.backend = backend;
  24148. this.gl = this.backend.gl;
  24149. this.extensions = backend.extensions;
  24150. }
  24151. convert( p, colorSpace = NoColorSpace ) {
  24152. const { gl, extensions } = this;
  24153. let extension;
  24154. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  24155. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  24156. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  24157. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  24158. if ( p === ByteType ) return gl.BYTE;
  24159. if ( p === ShortType ) return gl.SHORT;
  24160. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  24161. if ( p === IntType ) return gl.INT;
  24162. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  24163. if ( p === FloatType ) return gl.FLOAT;
  24164. if ( p === HalfFloatType ) {
  24165. return gl.HALF_FLOAT;
  24166. }
  24167. if ( p === AlphaFormat ) return gl.ALPHA;
  24168. if ( p === RGBFormat ) return gl.RGB;
  24169. if ( p === RGBAFormat ) return gl.RGBA;
  24170. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  24171. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  24172. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  24173. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  24174. // WebGL2 formats.
  24175. if ( p === RedFormat ) return gl.RED;
  24176. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  24177. if ( p === RGFormat ) return gl.RG;
  24178. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  24179. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  24180. // S3TC
  24181. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  24182. if ( colorSpace === SRGBColorSpace ) {
  24183. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  24184. if ( extension !== null ) {
  24185. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  24186. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  24187. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  24188. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  24189. } else {
  24190. return null;
  24191. }
  24192. } else {
  24193. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  24194. if ( extension !== null ) {
  24195. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  24196. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  24197. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  24198. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  24199. } else {
  24200. return null;
  24201. }
  24202. }
  24203. }
  24204. // PVRTC
  24205. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  24206. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  24207. if ( extension !== null ) {
  24208. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  24209. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  24210. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  24211. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  24212. } else {
  24213. return null;
  24214. }
  24215. }
  24216. // ETC
  24217. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  24218. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  24219. if ( extension !== null ) {
  24220. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  24221. if ( p === RGBA_ETC2_EAC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  24222. } else {
  24223. return null;
  24224. }
  24225. }
  24226. // ASTC
  24227. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  24228. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  24229. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  24230. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  24231. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  24232. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  24233. if ( extension !== null ) {
  24234. if ( p === RGBA_ASTC_4x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  24235. if ( p === RGBA_ASTC_5x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  24236. if ( p === RGBA_ASTC_5x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  24237. if ( p === RGBA_ASTC_6x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  24238. if ( p === RGBA_ASTC_6x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  24239. if ( p === RGBA_ASTC_8x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  24240. if ( p === RGBA_ASTC_8x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  24241. if ( p === RGBA_ASTC_8x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  24242. if ( p === RGBA_ASTC_10x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  24243. if ( p === RGBA_ASTC_10x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  24244. if ( p === RGBA_ASTC_10x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  24245. if ( p === RGBA_ASTC_10x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  24246. if ( p === RGBA_ASTC_12x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  24247. if ( p === RGBA_ASTC_12x12_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  24248. } else {
  24249. return null;
  24250. }
  24251. }
  24252. // BPTC
  24253. if ( p === RGBA_BPTC_Format ) {
  24254. extension = extensions.get( 'EXT_texture_compression_bptc' );
  24255. if ( extension !== null ) {
  24256. if ( p === RGBA_BPTC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  24257. } else {
  24258. return null;
  24259. }
  24260. }
  24261. // RGTC
  24262. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  24263. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  24264. if ( extension !== null ) {
  24265. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  24266. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  24267. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  24268. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  24269. } else {
  24270. return null;
  24271. }
  24272. }
  24273. //
  24274. if ( p === UnsignedInt248Type ) {
  24275. return gl.UNSIGNED_INT_24_8;
  24276. }
  24277. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  24278. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  24279. }
  24280. _clientWaitAsync() {
  24281. const { gl } = this;
  24282. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  24283. gl.flush();
  24284. return new Promise( ( resolve, reject ) => {
  24285. function test() {
  24286. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  24287. if ( res === gl.WAIT_FAILED ) {
  24288. gl.deleteSync( sync );
  24289. reject();
  24290. return;
  24291. }
  24292. if ( res === gl.TIMEOUT_EXPIRED ) {
  24293. requestAnimationFrame( test );
  24294. return;
  24295. }
  24296. gl.deleteSync( sync );
  24297. resolve();
  24298. }
  24299. test();
  24300. } );
  24301. }
  24302. }
  24303. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  24304. class WebGLTextureUtils {
  24305. constructor( backend ) {
  24306. this.backend = backend;
  24307. this.gl = backend.gl;
  24308. this.extensions = backend.extensions;
  24309. this.defaultTextures = {};
  24310. if ( initialized === false ) {
  24311. this._init( this.gl );
  24312. initialized = true;
  24313. }
  24314. }
  24315. _init( gl ) {
  24316. // Store only WebGL constants here.
  24317. wrappingToGL = {
  24318. [ RepeatWrapping ]: gl.REPEAT,
  24319. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  24320. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  24321. };
  24322. filterToGL = {
  24323. [ NearestFilter ]: gl.NEAREST,
  24324. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  24325. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  24326. [ LinearFilter ]: gl.LINEAR,
  24327. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  24328. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  24329. };
  24330. compareToGL = {
  24331. [ NeverCompare ]: gl.NEVER,
  24332. [ AlwaysCompare ]: gl.ALWAYS,
  24333. [ LessCompare ]: gl.LESS,
  24334. [ LessEqualCompare ]: gl.LEQUAL,
  24335. [ EqualCompare ]: gl.EQUAL,
  24336. [ GreaterEqualCompare ]: gl.GEQUAL,
  24337. [ GreaterCompare ]: gl.GREATER,
  24338. [ NotEqualCompare ]: gl.NOTEQUAL
  24339. };
  24340. }
  24341. filterFallback( f ) {
  24342. const { gl } = this;
  24343. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  24344. return gl.NEAREST;
  24345. }
  24346. return gl.LINEAR;
  24347. }
  24348. getGLTextureType( texture ) {
  24349. const { gl } = this;
  24350. let glTextureType;
  24351. if ( texture.isCubeTexture === true ) {
  24352. glTextureType = gl.TEXTURE_CUBE_MAP;
  24353. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  24354. glTextureType = gl.TEXTURE_2D_ARRAY;
  24355. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  24356. glTextureType = gl.TEXTURE_3D;
  24357. } else {
  24358. glTextureType = gl.TEXTURE_2D;
  24359. }
  24360. return glTextureType;
  24361. }
  24362. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  24363. const { gl, extensions } = this;
  24364. if ( internalFormatName !== null ) {
  24365. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  24366. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  24367. }
  24368. let internalFormat = glFormat;
  24369. if ( glFormat === gl.RED ) {
  24370. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  24371. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  24372. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  24373. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  24374. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  24375. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  24376. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  24377. if ( glType === gl.INT ) internalFormat = gl.R32I;
  24378. }
  24379. if ( glFormat === gl.RED_INTEGER ) {
  24380. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  24381. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  24382. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  24383. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  24384. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  24385. if ( glType === gl.INT ) internalFormat = gl.R32I;
  24386. }
  24387. if ( glFormat === gl.RG ) {
  24388. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  24389. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  24390. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  24391. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  24392. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  24393. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  24394. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  24395. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  24396. }
  24397. if ( glFormat === gl.RG_INTEGER ) {
  24398. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  24399. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  24400. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  24401. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  24402. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  24403. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  24404. }
  24405. if ( glFormat === gl.RGB ) {
  24406. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  24407. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  24408. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  24409. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  24410. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  24411. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  24412. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  24413. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  24414. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8 : gl.RGB8;
  24415. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  24416. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  24417. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  24418. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  24419. }
  24420. if ( glFormat === gl.RGB_INTEGER ) {
  24421. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  24422. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  24423. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  24424. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  24425. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  24426. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  24427. }
  24428. if ( glFormat === gl.RGBA ) {
  24429. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  24430. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  24431. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  24432. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  24433. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  24434. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  24435. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  24436. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  24437. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  24438. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  24439. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  24440. }
  24441. if ( glFormat === gl.RGBA_INTEGER ) {
  24442. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  24443. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  24444. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  24445. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  24446. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  24447. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  24448. }
  24449. if ( glFormat === gl.DEPTH_COMPONENT ) {
  24450. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH24_STENCIL8;
  24451. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  24452. }
  24453. if ( glFormat === gl.DEPTH_STENCIL ) {
  24454. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  24455. }
  24456. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  24457. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  24458. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  24459. extensions.get( 'EXT_color_buffer_float' );
  24460. }
  24461. return internalFormat;
  24462. }
  24463. setTextureParameters( textureType, texture ) {
  24464. const { gl, extensions, backend } = this;
  24465. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  24466. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  24467. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  24468. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE );
  24469. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  24470. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  24471. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  24472. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  24473. }
  24474. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  24475. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  24476. // follow WebGPU backend mapping for texture filtering
  24477. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  24478. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  24479. if ( texture.compareFunction ) {
  24480. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  24481. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  24482. }
  24483. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  24484. if ( texture.magFilter === NearestFilter ) return;
  24485. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  24486. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  24487. if ( texture.anisotropy > 1 ) {
  24488. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  24489. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  24490. }
  24491. }
  24492. }
  24493. createDefaultTexture( texture ) {
  24494. const { gl, backend, defaultTextures } = this;
  24495. const glTextureType = this.getGLTextureType( texture );
  24496. let textureGPU = defaultTextures[ glTextureType ];
  24497. if ( textureGPU === undefined ) {
  24498. textureGPU = gl.createTexture();
  24499. backend.state.bindTexture( glTextureType, textureGPU );
  24500. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  24501. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  24502. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  24503. defaultTextures[ glTextureType ] = textureGPU;
  24504. }
  24505. backend.set( texture, {
  24506. textureGPU,
  24507. glTextureType,
  24508. isDefault: true
  24509. } );
  24510. }
  24511. createTexture( texture, options ) {
  24512. const { gl, backend } = this;
  24513. const { levels, width, height, depth } = options;
  24514. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  24515. const glType = backend.utils.convert( texture.type );
  24516. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  24517. const textureGPU = gl.createTexture();
  24518. const glTextureType = this.getGLTextureType( texture );
  24519. backend.state.bindTexture( glTextureType, textureGPU );
  24520. this.setTextureParameters( glTextureType, texture );
  24521. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  24522. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  24523. } else if ( texture.isData3DTexture ) {
  24524. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  24525. } else if ( ! texture.isVideoTexture ) {
  24526. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  24527. }
  24528. backend.set( texture, {
  24529. textureGPU,
  24530. glTextureType,
  24531. glFormat,
  24532. glType,
  24533. glInternalFormat
  24534. } );
  24535. }
  24536. copyBufferToTexture( buffer, texture ) {
  24537. const { gl, backend } = this;
  24538. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  24539. const { width, height } = texture.source.data;
  24540. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  24541. backend.state.bindTexture( glTextureType, textureGPU );
  24542. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  24543. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  24544. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  24545. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  24546. backend.state.unbindTexture();
  24547. // debug
  24548. // const framebuffer = gl.createFramebuffer();
  24549. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  24550. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  24551. // const readout = new Float32Array( width * height * 4 );
  24552. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  24553. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  24554. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  24555. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  24556. // console.log( readout );
  24557. }
  24558. updateTexture( texture, options ) {
  24559. const { gl } = this;
  24560. const { width, height } = options;
  24561. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  24562. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  24563. return;
  24564. const getImage = ( source ) => {
  24565. if ( source.isDataTexture ) {
  24566. return source.image.data;
  24567. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  24568. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  24569. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  24570. source instanceof OffscreenCanvas ) {
  24571. return source;
  24572. }
  24573. return source.data;
  24574. };
  24575. this.backend.state.bindTexture( glTextureType, textureGPU );
  24576. this.setTextureParameters( glTextureType, texture );
  24577. if ( texture.isCompressedTexture ) {
  24578. const mipmaps = texture.mipmaps;
  24579. const image = options.image;
  24580. for ( let i = 0; i < mipmaps.length; i ++ ) {
  24581. const mipmap = mipmaps[ i ];
  24582. if ( texture.isCompressedArrayTexture ) {
  24583. if ( texture.format !== gl.RGBA ) {
  24584. if ( glFormat !== null ) {
  24585. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  24586. } else {
  24587. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  24588. }
  24589. } else {
  24590. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  24591. }
  24592. } else {
  24593. if ( glFormat !== null ) {
  24594. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  24595. } else {
  24596. console.warn( 'Unsupported compressed texture format' );
  24597. }
  24598. }
  24599. }
  24600. } else if ( texture.isCubeTexture ) {
  24601. const images = options.images;
  24602. for ( let i = 0; i < 6; i ++ ) {
  24603. const image = getImage( images[ i ] );
  24604. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  24605. }
  24606. } else if ( texture.isDataArrayTexture ) {
  24607. const image = options.image;
  24608. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  24609. } else if ( texture.isData3DTexture ) {
  24610. const image = options.image;
  24611. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  24612. } else if ( texture.isVideoTexture ) {
  24613. texture.update();
  24614. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  24615. } else {
  24616. const image = getImage( options.image );
  24617. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  24618. }
  24619. }
  24620. generateMipmaps( texture ) {
  24621. const { gl, backend } = this;
  24622. const { textureGPU, glTextureType } = backend.get( texture );
  24623. backend.state.bindTexture( glTextureType, textureGPU );
  24624. gl.generateMipmap( glTextureType );
  24625. }
  24626. deallocateRenderBuffers( renderTarget ) {
  24627. const { gl, backend } = this;
  24628. // remove framebuffer reference
  24629. if ( renderTarget ) {
  24630. const renderContextData = backend.get( renderTarget );
  24631. renderContextData.renderBufferStorageSetup = undefined;
  24632. if ( renderContextData.framebuffers ) {
  24633. for ( const cacheKey in renderContextData.framebuffers ) {
  24634. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  24635. }
  24636. delete renderContextData.framebuffers;
  24637. }
  24638. if ( renderContextData.depthRenderbuffer ) {
  24639. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  24640. delete renderContextData.depthRenderbuffer;
  24641. }
  24642. if ( renderContextData.stencilRenderbuffer ) {
  24643. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  24644. delete renderContextData.stencilRenderbuffer;
  24645. }
  24646. if ( renderContextData.msaaFrameBuffer ) {
  24647. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  24648. delete renderContextData.msaaFrameBuffer;
  24649. }
  24650. if ( renderContextData.msaaRenderbuffers ) {
  24651. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  24652. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  24653. }
  24654. delete renderContextData.msaaRenderbuffers;
  24655. }
  24656. }
  24657. }
  24658. destroyTexture( texture ) {
  24659. const { gl, backend } = this;
  24660. const { textureGPU, renderTarget } = backend.get( texture );
  24661. this.deallocateRenderBuffers( renderTarget );
  24662. gl.deleteTexture( textureGPU );
  24663. backend.delete( texture );
  24664. }
  24665. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  24666. const { gl, backend } = this;
  24667. const { state } = this.backend;
  24668. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  24669. let width, height, minX, minY;
  24670. let dstX, dstY;
  24671. if ( srcRegion !== null ) {
  24672. width = srcRegion.max.x - srcRegion.min.x;
  24673. height = srcRegion.max.y - srcRegion.min.y;
  24674. minX = srcRegion.min.x;
  24675. minY = srcRegion.min.y;
  24676. } else {
  24677. width = srcTexture.image.width;
  24678. height = srcTexture.image.height;
  24679. minX = 0;
  24680. minY = 0;
  24681. }
  24682. if ( dstPosition !== null ) {
  24683. dstX = dstPosition.x;
  24684. dstY = dstPosition.y;
  24685. } else {
  24686. dstX = 0;
  24687. dstY = 0;
  24688. }
  24689. state.bindTexture( glTextureType, dstTextureGPU );
  24690. // As another texture upload may have changed pixelStorei
  24691. // parameters, make sure they are correct for the dstTexture
  24692. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  24693. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  24694. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  24695. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  24696. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  24697. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  24698. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  24699. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  24700. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  24701. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  24702. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  24703. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  24704. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  24705. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  24706. if ( srcTexture.isRenderTargetTexture || srcTexture.isDepthTexture ) {
  24707. const srcTextureData = backend.get( srcTexture );
  24708. const dstTextureData = backend.get( dstTexture );
  24709. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  24710. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  24711. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  24712. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  24713. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  24714. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  24715. let mask = gl.COLOR_BUFFER_BIT;
  24716. if ( srcTexture.isDepthTexture ) mask = gl.DEPTH_BUFFER_BIT;
  24717. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, mask, gl.NEAREST );
  24718. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  24719. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  24720. } else {
  24721. if ( srcTexture.isDataTexture ) {
  24722. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image.data );
  24723. } else {
  24724. if ( srcTexture.isCompressedTexture ) {
  24725. gl.compressedTexSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, image.width, image.height, glFormat, image.data );
  24726. } else {
  24727. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image );
  24728. }
  24729. }
  24730. }
  24731. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  24732. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  24733. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  24734. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  24735. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  24736. // Generate mipmaps only when copying level 0
  24737. if ( level === 0 && dstTexture.generateMipmaps ) gl.generateMipmap( gl.TEXTURE_2D );
  24738. state.unbindTexture();
  24739. }
  24740. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  24741. const { gl } = this;
  24742. const { state } = this.backend;
  24743. const { textureGPU } = this.backend.get( texture );
  24744. const { x, y, z: width, w: height } = rectangle;
  24745. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  24746. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.gerDrawingBufferSize().y;
  24747. if ( requireDrawFrameBuffer ) {
  24748. const partial = ( x !== 0 || y !== 0 );
  24749. let mask;
  24750. let attachment;
  24751. if ( texture.isDepthTexture === true ) {
  24752. mask = gl.DEPTH_BUFFER_BIT;
  24753. attachment = gl.DEPTH_ATTACHMENT;
  24754. if ( renderContext.stencil ) {
  24755. mask |= gl.STENCIL_BUFFER_BIT;
  24756. }
  24757. } else {
  24758. mask = gl.COLOR_BUFFER_BIT;
  24759. attachment = gl.COLOR_ATTACHMENT0;
  24760. }
  24761. if ( partial ) {
  24762. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  24763. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  24764. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  24765. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  24766. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  24767. const flippedY = srcHeight - y - height;
  24768. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  24769. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  24770. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  24771. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  24772. state.unbindTexture();
  24773. } else {
  24774. const fb = gl.createFramebuffer();
  24775. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  24776. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  24777. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  24778. gl.deleteFramebuffer( fb );
  24779. }
  24780. } else {
  24781. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  24782. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  24783. state.unbindTexture();
  24784. }
  24785. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  24786. this.backend._setFramebuffer( renderContext );
  24787. }
  24788. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  24789. setupRenderBufferStorage( renderbuffer, renderContext ) {
  24790. const { gl } = this;
  24791. const renderTarget = renderContext.renderTarget;
  24792. const { samples, depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  24793. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  24794. if ( depthBuffer && ! stencilBuffer ) {
  24795. let glInternalFormat = gl.DEPTH_COMPONENT24;
  24796. if ( samples > 0 ) {
  24797. if ( depthTexture && depthTexture.isDepthTexture ) {
  24798. if ( depthTexture.type === gl.FLOAT ) {
  24799. glInternalFormat = gl.DEPTH_COMPONENT32F;
  24800. }
  24801. }
  24802. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  24803. } else {
  24804. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  24805. }
  24806. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  24807. } else if ( depthBuffer && stencilBuffer ) {
  24808. if ( samples > 0 ) {
  24809. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  24810. } else {
  24811. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  24812. }
  24813. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  24814. }
  24815. }
  24816. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  24817. const { backend, gl } = this;
  24818. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  24819. const fb = gl.createFramebuffer();
  24820. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  24821. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  24822. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  24823. const typedArrayType = this._getTypedArrayType( glType );
  24824. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  24825. const elementCount = width * height;
  24826. const byteLength = elementCount * bytesPerTexel;
  24827. const buffer = gl.createBuffer();
  24828. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  24829. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  24830. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  24831. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  24832. await backend.utils._clientWaitAsync();
  24833. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  24834. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  24835. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  24836. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  24837. gl.deleteFramebuffer( fb );
  24838. return dstBuffer;
  24839. }
  24840. _getTypedArrayType( glType ) {
  24841. const { gl } = this;
  24842. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  24843. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  24844. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  24845. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  24846. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  24847. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  24848. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  24849. if ( glType === gl.FLOAT ) return Float32Array;
  24850. throw new Error( `Unsupported WebGL type: ${glType}` );
  24851. }
  24852. _getBytesPerTexel( glType, glFormat ) {
  24853. const { gl } = this;
  24854. let bytesPerComponent = 0;
  24855. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  24856. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  24857. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  24858. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  24859. glType === gl.UNSIGNED_SHORT ||
  24860. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  24861. if ( glType === gl.UNSIGNED_INT ||
  24862. glType === gl.FLOAT ) bytesPerComponent = 4;
  24863. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  24864. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  24865. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  24866. }
  24867. }
  24868. class WebGLExtensions {
  24869. constructor( backend ) {
  24870. this.backend = backend;
  24871. this.gl = this.backend.gl;
  24872. this.availableExtensions = this.gl.getSupportedExtensions();
  24873. this.extensions = {};
  24874. }
  24875. get( name ) {
  24876. let extension = this.extensions[ name ];
  24877. if ( extension === undefined ) {
  24878. extension = this.gl.getExtension( name );
  24879. this.extensions[ name ] = extension;
  24880. }
  24881. return extension;
  24882. }
  24883. has( name ) {
  24884. return this.availableExtensions.includes( name );
  24885. }
  24886. }
  24887. class WebGLCapabilities {
  24888. constructor( backend ) {
  24889. this.backend = backend;
  24890. this.maxAnisotropy = null;
  24891. }
  24892. getMaxAnisotropy() {
  24893. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  24894. const gl = this.backend.gl;
  24895. const extensions = this.backend.extensions;
  24896. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  24897. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  24898. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  24899. } else {
  24900. this.maxAnisotropy = 0;
  24901. }
  24902. return this.maxAnisotropy;
  24903. }
  24904. }
  24905. const GLFeatureName = {
  24906. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  24907. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  24908. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  24909. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  24910. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  24911. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  24912. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  24913. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  24914. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  24915. };
  24916. class WebGLBufferRenderer {
  24917. constructor( backend ) {
  24918. this.gl = backend.gl;
  24919. this.extensions = backend.extensions;
  24920. this.info = backend.renderer.info;
  24921. this.mode = null;
  24922. this.index = 0;
  24923. this.type = null;
  24924. this.object = null;
  24925. }
  24926. render( start, count ) {
  24927. const { gl, mode, object, type, info, index } = this;
  24928. if ( index !== 0 ) {
  24929. gl.drawElements( mode, count, type, start );
  24930. } else {
  24931. gl.drawArrays( mode, start, count );
  24932. }
  24933. info.update( object, count, mode, 1 );
  24934. }
  24935. renderInstances( start, count, primcount ) {
  24936. const { gl, mode, type, index, object, info } = this;
  24937. if ( primcount === 0 ) return;
  24938. if ( index !== 0 ) {
  24939. gl.drawElementsInstanced( mode, count, type, start, primcount );
  24940. } else {
  24941. gl.drawArraysInstanced( mode, start, count, primcount );
  24942. }
  24943. info.update( object, count, mode, primcount );
  24944. }
  24945. renderMultiDraw( starts, counts, drawCount ) {
  24946. const { extensions, mode, object, info } = this;
  24947. if ( drawCount === 0 ) return;
  24948. const extension = extensions.get( 'WEBGL_multi_draw' );
  24949. if ( extension === null ) {
  24950. for ( let i = 0; i < drawCount; i ++ ) {
  24951. this.render( starts[ i ], counts[ i ] );
  24952. }
  24953. } else {
  24954. if ( this.index !== 0 ) {
  24955. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  24956. } else {
  24957. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  24958. }
  24959. let elementCount = 0;
  24960. for ( let i = 0; i < drawCount; i ++ ) {
  24961. elementCount += counts[ i ];
  24962. }
  24963. info.update( object, elementCount, mode, 1 );
  24964. }
  24965. }
  24966. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  24967. const { extensions, mode, object, info } = this;
  24968. if ( drawCount === 0 ) return;
  24969. const extension = extensions.get( 'WEBGL_multi_draw' );
  24970. if ( extension === null ) {
  24971. for ( let i = 0; i < drawCount; i ++ ) {
  24972. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  24973. }
  24974. } else {
  24975. if ( this.index !== 0 ) {
  24976. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  24977. } else {
  24978. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  24979. }
  24980. let elementCount = 0;
  24981. for ( let i = 0; i < drawCount; i ++ ) {
  24982. elementCount += counts[ i ] * primcount[ i ];
  24983. }
  24984. info.update( object, elementCount, mode, 1 );
  24985. }
  24986. }
  24987. //
  24988. }
  24989. //
  24990. class WebGLBackend extends Backend {
  24991. constructor( parameters = {} ) {
  24992. super( parameters );
  24993. this.isWebGLBackend = true;
  24994. }
  24995. init( renderer ) {
  24996. super.init( renderer );
  24997. //
  24998. const parameters = this.parameters;
  24999. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2' );
  25000. function onContextLost( event ) {
  25001. event.preventDefault();
  25002. const contextLossInfo = {
  25003. api: 'WebGL',
  25004. message: event.statusMessage || 'Unknown reason',
  25005. reason: null,
  25006. originalEvent: event
  25007. };
  25008. renderer.onDeviceLost( contextLossInfo );
  25009. }
  25010. this._onContextLost = onContextLost;
  25011. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  25012. this.gl = glContext;
  25013. this.extensions = new WebGLExtensions( this );
  25014. this.capabilities = new WebGLCapabilities( this );
  25015. this.attributeUtils = new WebGLAttributeUtils( this );
  25016. this.textureUtils = new WebGLTextureUtils( this );
  25017. this.bufferRenderer = new WebGLBufferRenderer( this );
  25018. this.state = new WebGLState( this );
  25019. this.utils = new WebGLUtils( this );
  25020. this.vaoCache = {};
  25021. this.transformFeedbackCache = {};
  25022. this.discard = false;
  25023. this.trackTimestamp = ( parameters.trackTimestamp === true );
  25024. this.extensions.get( 'EXT_color_buffer_float' );
  25025. this.extensions.get( 'WEBGL_clip_cull_distance' );
  25026. this.extensions.get( 'OES_texture_float_linear' );
  25027. this.extensions.get( 'EXT_color_buffer_half_float' );
  25028. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  25029. this.extensions.get( 'WEBGL_render_shared_exponent' );
  25030. this.extensions.get( 'WEBGL_multi_draw' );
  25031. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  25032. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  25033. this._knownBindings = new WeakSet();
  25034. this._currentContext = null;
  25035. }
  25036. get coordinateSystem() {
  25037. return WebGLCoordinateSystem;
  25038. }
  25039. async getArrayBufferAsync( attribute ) {
  25040. return await this.attributeUtils.getArrayBufferAsync( attribute );
  25041. }
  25042. async waitForGPU() {
  25043. await this.utils._clientWaitAsync();
  25044. }
  25045. initTimestampQuery( renderContext ) {
  25046. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  25047. const renderContextData = this.get( renderContext );
  25048. if ( this.queryRunning ) {
  25049. if ( ! renderContextData.queryQueue ) renderContextData.queryQueue = [];
  25050. renderContextData.queryQueue.push( renderContext );
  25051. return;
  25052. }
  25053. if ( renderContextData.activeQuery ) {
  25054. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  25055. renderContextData.activeQuery = null;
  25056. }
  25057. renderContextData.activeQuery = this.gl.createQuery();
  25058. if ( renderContextData.activeQuery !== null ) {
  25059. this.gl.beginQuery( this.disjoint.TIME_ELAPSED_EXT, renderContextData.activeQuery );
  25060. this.queryRunning = true;
  25061. }
  25062. }
  25063. // timestamp utils
  25064. prepareTimestampBuffer( renderContext ) {
  25065. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  25066. const renderContextData = this.get( renderContext );
  25067. if ( renderContextData.activeQuery ) {
  25068. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  25069. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  25070. renderContextData.gpuQueries.push( { query: renderContextData.activeQuery } );
  25071. renderContextData.activeQuery = null;
  25072. this.queryRunning = false;
  25073. if ( renderContextData.queryQueue && renderContextData.queryQueue.length > 0 ) {
  25074. const nextRenderContext = renderContextData.queryQueue.shift();
  25075. this.initTimestampQuery( nextRenderContext );
  25076. }
  25077. }
  25078. }
  25079. async resolveTimestampAsync( renderContext, type = 'render' ) {
  25080. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  25081. const renderContextData = this.get( renderContext );
  25082. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  25083. for ( let i = 0; i < renderContextData.gpuQueries.length; i ++ ) {
  25084. const queryInfo = renderContextData.gpuQueries[ i ];
  25085. const available = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT_AVAILABLE );
  25086. const disjoint = this.gl.getParameter( this.disjoint.GPU_DISJOINT_EXT );
  25087. if ( available && ! disjoint ) {
  25088. const elapsed = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT );
  25089. const duration = Number( elapsed ) / 1000000; // Convert nanoseconds to milliseconds
  25090. this.gl.deleteQuery( queryInfo.query );
  25091. renderContextData.gpuQueries.splice( i, 1 ); // Remove the processed query
  25092. i --;
  25093. this.renderer.info.updateTimestamp( type, duration );
  25094. }
  25095. }
  25096. }
  25097. getContext() {
  25098. return this.gl;
  25099. }
  25100. beginRender( renderContext ) {
  25101. const { gl } = this;
  25102. const renderContextData = this.get( renderContext );
  25103. //
  25104. //
  25105. this.initTimestampQuery( renderContext );
  25106. renderContextData.previousContext = this._currentContext;
  25107. this._currentContext = renderContext;
  25108. this._setFramebuffer( renderContext );
  25109. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  25110. //
  25111. if ( renderContext.viewport ) {
  25112. this.updateViewport( renderContext );
  25113. } else {
  25114. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  25115. }
  25116. if ( renderContext.scissor ) {
  25117. const { x, y, width, height } = renderContext.scissorValue;
  25118. gl.scissor( x, renderContext.height - height - y, width, height );
  25119. }
  25120. const occlusionQueryCount = renderContext.occlusionQueryCount;
  25121. if ( occlusionQueryCount > 0 ) {
  25122. // Get a reference to the array of objects with queries. The renderContextData property
  25123. // can be changed by another render pass before the async reading of all previous queries complete
  25124. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  25125. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  25126. renderContextData.lastOcclusionObject = null;
  25127. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  25128. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  25129. renderContextData.occlusionQueryIndex = 0;
  25130. }
  25131. }
  25132. finishRender( renderContext ) {
  25133. const { gl, state } = this;
  25134. const renderContextData = this.get( renderContext );
  25135. const previousContext = renderContextData.previousContext;
  25136. const occlusionQueryCount = renderContext.occlusionQueryCount;
  25137. if ( occlusionQueryCount > 0 ) {
  25138. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  25139. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  25140. }
  25141. this.resolveOccludedAsync( renderContext );
  25142. }
  25143. const textures = renderContext.textures;
  25144. if ( textures !== null ) {
  25145. for ( let i = 0; i < textures.length; i ++ ) {
  25146. const texture = textures[ i ];
  25147. if ( texture.generateMipmaps ) {
  25148. this.generateMipmaps( texture );
  25149. }
  25150. }
  25151. }
  25152. this._currentContext = previousContext;
  25153. if ( renderContext.textures !== null && renderContext.renderTarget ) {
  25154. const renderTargetContextData = this.get( renderContext.renderTarget );
  25155. const { samples } = renderContext.renderTarget;
  25156. if ( samples > 0 ) {
  25157. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  25158. const mask = gl.COLOR_BUFFER_BIT;
  25159. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  25160. const textures = renderContext.textures;
  25161. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  25162. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  25163. for ( let i = 0; i < textures.length; i ++ ) {
  25164. // TODO Add support for MRT
  25165. if ( renderContext.scissor ) {
  25166. const { x, y, width, height } = renderContext.scissorValue;
  25167. const viewY = renderContext.height - height - y;
  25168. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  25169. gl.invalidateSubFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray, x, viewY, width, height );
  25170. } else {
  25171. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  25172. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  25173. }
  25174. }
  25175. }
  25176. }
  25177. if ( previousContext !== null ) {
  25178. this._setFramebuffer( previousContext );
  25179. if ( previousContext.viewport ) {
  25180. this.updateViewport( previousContext );
  25181. } else {
  25182. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  25183. }
  25184. }
  25185. this.prepareTimestampBuffer( renderContext );
  25186. }
  25187. resolveOccludedAsync( renderContext ) {
  25188. const renderContextData = this.get( renderContext );
  25189. // handle occlusion query results
  25190. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  25191. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  25192. const occluded = new WeakSet();
  25193. const { gl } = this;
  25194. renderContextData.currentOcclusionQueryObjects = null;
  25195. renderContextData.currentOcclusionQueries = null;
  25196. const check = () => {
  25197. let completed = 0;
  25198. // check all queries and requeue as appropriate
  25199. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  25200. const query = currentOcclusionQueries[ i ];
  25201. if ( query === null ) continue;
  25202. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  25203. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) > 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  25204. currentOcclusionQueries[ i ] = null;
  25205. gl.deleteQuery( query );
  25206. completed ++;
  25207. }
  25208. }
  25209. if ( completed < currentOcclusionQueries.length ) {
  25210. requestAnimationFrame( check );
  25211. } else {
  25212. renderContextData.occluded = occluded;
  25213. }
  25214. };
  25215. check();
  25216. }
  25217. }
  25218. isOccluded( renderContext, object ) {
  25219. const renderContextData = this.get( renderContext );
  25220. return renderContextData.occluded && renderContextData.occluded.has( object );
  25221. }
  25222. updateViewport( renderContext ) {
  25223. const gl = this.gl;
  25224. const { x, y, width, height } = renderContext.viewportValue;
  25225. gl.viewport( x, renderContext.height - height - y, width, height );
  25226. }
  25227. setScissorTest( boolean ) {
  25228. const gl = this.gl;
  25229. if ( boolean ) {
  25230. gl.enable( gl.SCISSOR_TEST );
  25231. } else {
  25232. gl.disable( gl.SCISSOR_TEST );
  25233. }
  25234. }
  25235. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  25236. const { gl } = this;
  25237. if ( descriptor === null ) {
  25238. const clearColor = this.getClearColor();
  25239. // premultiply alpha
  25240. clearColor.r *= clearColor.a;
  25241. clearColor.g *= clearColor.a;
  25242. clearColor.b *= clearColor.a;
  25243. descriptor = {
  25244. textures: null,
  25245. clearColorValue: clearColor
  25246. };
  25247. }
  25248. //
  25249. let clear = 0;
  25250. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  25251. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  25252. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  25253. if ( clear !== 0 ) {
  25254. let clearColor;
  25255. if ( descriptor.clearColorValue ) {
  25256. clearColor = descriptor.clearColorValue;
  25257. } else {
  25258. clearColor = this.getClearColor();
  25259. // premultiply alpha
  25260. clearColor.r *= clearColor.a;
  25261. clearColor.g *= clearColor.a;
  25262. clearColor.b *= clearColor.a;
  25263. }
  25264. if ( depth ) this.state.setDepthMask( true );
  25265. if ( descriptor.textures === null ) {
  25266. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  25267. gl.clear( clear );
  25268. } else {
  25269. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  25270. if ( color ) {
  25271. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  25272. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  25273. }
  25274. }
  25275. if ( depth && stencil ) {
  25276. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, 1, 0 );
  25277. } else if ( depth ) {
  25278. gl.clearBufferfv( gl.DEPTH, 0, [ 1.0 ] );
  25279. } else if ( stencil ) {
  25280. gl.clearBufferiv( gl.STENCIL, 0, [ 0 ] );
  25281. }
  25282. }
  25283. }
  25284. }
  25285. beginCompute( computeGroup ) {
  25286. const { state, gl } = this;
  25287. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  25288. this.initTimestampQuery( computeGroup );
  25289. }
  25290. compute( computeGroup, computeNode, bindings, pipeline ) {
  25291. const { state, gl } = this;
  25292. if ( ! this.discard ) {
  25293. // required here to handle async behaviour of render.compute()
  25294. gl.enable( gl.RASTERIZER_DISCARD );
  25295. this.discard = true;
  25296. }
  25297. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  25298. const vaoKey = this._getVaoKey( null, attributes );
  25299. const vaoGPU = this.vaoCache[ vaoKey ];
  25300. if ( vaoGPU === undefined ) {
  25301. this._createVao( null, attributes );
  25302. } else {
  25303. gl.bindVertexArray( vaoGPU );
  25304. }
  25305. state.useProgram( programGPU );
  25306. this._bindUniforms( bindings );
  25307. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  25308. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  25309. gl.beginTransformFeedback( gl.POINTS );
  25310. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  25311. gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count );
  25312. } else {
  25313. gl.drawArrays( gl.POINTS, 0, computeNode.count );
  25314. }
  25315. gl.endTransformFeedback();
  25316. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  25317. // switch active buffers
  25318. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  25319. const dualAttributeData = transformBuffers[ i ];
  25320. if ( dualAttributeData.pbo ) {
  25321. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  25322. }
  25323. dualAttributeData.switchBuffers();
  25324. }
  25325. }
  25326. finishCompute( computeGroup ) {
  25327. const gl = this.gl;
  25328. this.discard = false;
  25329. gl.disable( gl.RASTERIZER_DISCARD );
  25330. this.prepareTimestampBuffer( computeGroup );
  25331. if ( this._currentContext ) {
  25332. this._setFramebuffer( this._currentContext );
  25333. }
  25334. }
  25335. draw( renderObject/*, info*/ ) {
  25336. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  25337. const { programGPU } = this.get( pipeline );
  25338. const { gl, state } = this;
  25339. const contextData = this.get( context );
  25340. const drawParams = renderObject.getDrawParameters();
  25341. if ( drawParams === null ) return;
  25342. //
  25343. this._bindUniforms( renderObject.getBindings() );
  25344. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  25345. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  25346. state.useProgram( programGPU );
  25347. //
  25348. const renderObjectData = this.get( renderObject );
  25349. let vaoGPU = renderObjectData.staticVao;
  25350. if ( vaoGPU === undefined || renderObjectData.geometryId !== renderObject.geometry.id ) {
  25351. const vaoKey = this._getVaoKey( renderObject.getIndex(), renderObject.getAttributes() );
  25352. vaoGPU = this.vaoCache[ vaoKey ];
  25353. if ( vaoGPU === undefined ) {
  25354. let staticVao;
  25355. ( { vaoGPU, staticVao } = this._createVao( renderObject.getIndex(), renderObject.getAttributes() ) );
  25356. if ( staticVao ) {
  25357. renderObjectData.staticVao = vaoGPU;
  25358. renderObjectData.geometryId = renderObject.geometry.id;
  25359. }
  25360. }
  25361. }
  25362. gl.bindVertexArray( vaoGPU );
  25363. //
  25364. const index = renderObject.getIndex();
  25365. //
  25366. const lastObject = contextData.lastOcclusionObject;
  25367. if ( lastObject !== object && lastObject !== undefined ) {
  25368. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  25369. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  25370. contextData.occlusionQueryIndex ++;
  25371. }
  25372. if ( object.occlusionTest === true ) {
  25373. const query = gl.createQuery();
  25374. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  25375. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  25376. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  25377. }
  25378. contextData.lastOcclusionObject = object;
  25379. }
  25380. //
  25381. const renderer = this.bufferRenderer;
  25382. if ( object.isPoints ) renderer.mode = gl.POINTS;
  25383. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  25384. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  25385. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  25386. else {
  25387. if ( material.wireframe === true ) {
  25388. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  25389. renderer.mode = gl.LINES;
  25390. } else {
  25391. renderer.mode = gl.TRIANGLES;
  25392. }
  25393. }
  25394. //
  25395. const { vertexCount, instanceCount } = drawParams;
  25396. let { firstVertex } = drawParams;
  25397. renderer.object = object;
  25398. if ( index !== null ) {
  25399. firstVertex *= index.array.BYTES_PER_ELEMENT;
  25400. const indexData = this.get( index );
  25401. renderer.index = index.count;
  25402. renderer.type = indexData.type;
  25403. } else {
  25404. renderer.index = 0;
  25405. }
  25406. if ( object.isBatchedMesh ) {
  25407. if ( object._multiDrawInstances !== null ) {
  25408. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  25409. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  25410. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  25411. } else {
  25412. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  25413. }
  25414. } else if ( instanceCount > 1 ) {
  25415. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  25416. } else {
  25417. renderer.render( firstVertex, vertexCount );
  25418. }
  25419. //
  25420. gl.bindVertexArray( null );
  25421. }
  25422. needsRenderUpdate( /*renderObject*/ ) {
  25423. return false;
  25424. }
  25425. getRenderCacheKey( /*renderObject*/ ) {
  25426. return '';
  25427. }
  25428. // textures
  25429. createDefaultTexture( texture ) {
  25430. this.textureUtils.createDefaultTexture( texture );
  25431. }
  25432. createTexture( texture, options ) {
  25433. this.textureUtils.createTexture( texture, options );
  25434. }
  25435. updateTexture( texture, options ) {
  25436. this.textureUtils.updateTexture( texture, options );
  25437. }
  25438. generateMipmaps( texture ) {
  25439. this.textureUtils.generateMipmaps( texture );
  25440. }
  25441. destroyTexture( texture ) {
  25442. this.textureUtils.destroyTexture( texture );
  25443. }
  25444. copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  25445. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  25446. }
  25447. createSampler( /*texture*/ ) {
  25448. //console.warn( 'Abstract class.' );
  25449. }
  25450. destroySampler() {}
  25451. // node builder
  25452. createNodeBuilder( object, renderer ) {
  25453. return new GLSLNodeBuilder( object, renderer );
  25454. }
  25455. // program
  25456. createProgram( program ) {
  25457. const gl = this.gl;
  25458. const { stage, code } = program;
  25459. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  25460. gl.shaderSource( shader, code );
  25461. gl.compileShader( shader );
  25462. this.set( program, {
  25463. shaderGPU: shader
  25464. } );
  25465. }
  25466. destroyProgram( /*program*/ ) {
  25467. console.warn( 'Abstract class.' );
  25468. }
  25469. createRenderPipeline( renderObject, promises ) {
  25470. const gl = this.gl;
  25471. const pipeline = renderObject.pipeline;
  25472. // Program
  25473. const { fragmentProgram, vertexProgram } = pipeline;
  25474. const programGPU = gl.createProgram();
  25475. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  25476. const vertexShader = this.get( vertexProgram ).shaderGPU;
  25477. gl.attachShader( programGPU, fragmentShader );
  25478. gl.attachShader( programGPU, vertexShader );
  25479. gl.linkProgram( programGPU );
  25480. this.set( pipeline, {
  25481. programGPU,
  25482. fragmentShader,
  25483. vertexShader
  25484. } );
  25485. if ( promises !== null && this.parallel ) {
  25486. const p = new Promise( ( resolve /*, reject*/ ) => {
  25487. const parallel = this.parallel;
  25488. const checkStatus = () => {
  25489. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  25490. this._completeCompile( renderObject, pipeline );
  25491. resolve();
  25492. } else {
  25493. requestAnimationFrame( checkStatus );
  25494. }
  25495. };
  25496. checkStatus();
  25497. } );
  25498. promises.push( p );
  25499. return;
  25500. }
  25501. this._completeCompile( renderObject, pipeline );
  25502. }
  25503. _handleSource( string, errorLine ) {
  25504. const lines = string.split( '\n' );
  25505. const lines2 = [];
  25506. const from = Math.max( errorLine - 6, 0 );
  25507. const to = Math.min( errorLine + 6, lines.length );
  25508. for ( let i = from; i < to; i ++ ) {
  25509. const line = i + 1;
  25510. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  25511. }
  25512. return lines2.join( '\n' );
  25513. }
  25514. _getShaderErrors( gl, shader, type ) {
  25515. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  25516. const errors = gl.getShaderInfoLog( shader ).trim();
  25517. if ( status && errors === '' ) return '';
  25518. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  25519. if ( errorMatches ) {
  25520. const errorLine = parseInt( errorMatches[ 1 ] );
  25521. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  25522. } else {
  25523. return errors;
  25524. }
  25525. }
  25526. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  25527. if ( this.renderer.debug.checkShaderErrors ) {
  25528. const gl = this.gl;
  25529. const programLog = gl.getProgramInfoLog( programGPU ).trim();
  25530. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  25531. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  25532. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  25533. } else {
  25534. // default error reporting
  25535. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  25536. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  25537. console.error(
  25538. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  25539. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  25540. 'Program Info Log: ' + programLog + '\n' +
  25541. vertexErrors + '\n' +
  25542. fragmentErrors
  25543. );
  25544. }
  25545. } else if ( programLog !== '' ) {
  25546. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  25547. }
  25548. }
  25549. }
  25550. _completeCompile( renderObject, pipeline ) {
  25551. const { state, gl } = this;
  25552. const pipelineData = this.get( pipeline );
  25553. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  25554. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  25555. this._logProgramError( programGPU, fragmentShader, vertexShader );
  25556. }
  25557. state.useProgram( programGPU );
  25558. // Bindings
  25559. const bindings = renderObject.getBindings();
  25560. this._setupBindings( bindings, programGPU );
  25561. //
  25562. this.set( pipeline, {
  25563. programGPU
  25564. } );
  25565. }
  25566. createComputePipeline( computePipeline, bindings ) {
  25567. const { state, gl } = this;
  25568. // Program
  25569. const fragmentProgram = {
  25570. stage: 'fragment',
  25571. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  25572. };
  25573. this.createProgram( fragmentProgram );
  25574. const { computeProgram } = computePipeline;
  25575. const programGPU = gl.createProgram();
  25576. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  25577. const vertexShader = this.get( computeProgram ).shaderGPU;
  25578. const transforms = computeProgram.transforms;
  25579. const transformVaryingNames = [];
  25580. const transformAttributeNodes = [];
  25581. for ( let i = 0; i < transforms.length; i ++ ) {
  25582. const transform = transforms[ i ];
  25583. transformVaryingNames.push( transform.varyingName );
  25584. transformAttributeNodes.push( transform.attributeNode );
  25585. }
  25586. gl.attachShader( programGPU, fragmentShader );
  25587. gl.attachShader( programGPU, vertexShader );
  25588. gl.transformFeedbackVaryings(
  25589. programGPU,
  25590. transformVaryingNames,
  25591. gl.SEPARATE_ATTRIBS
  25592. );
  25593. gl.linkProgram( programGPU );
  25594. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  25595. this._logProgramError( programGPU, fragmentShader, vertexShader );
  25596. }
  25597. state.useProgram( programGPU );
  25598. // Bindings
  25599. this._setupBindings( bindings, programGPU );
  25600. const attributeNodes = computeProgram.attributes;
  25601. const attributes = [];
  25602. const transformBuffers = [];
  25603. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  25604. const attribute = attributeNodes[ i ].node.attribute;
  25605. attributes.push( attribute );
  25606. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  25607. }
  25608. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  25609. const attribute = transformAttributeNodes[ i ].attribute;
  25610. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  25611. const attributeData = this.get( attribute );
  25612. transformBuffers.push( attributeData );
  25613. }
  25614. //
  25615. this.set( computePipeline, {
  25616. programGPU,
  25617. transformBuffers,
  25618. attributes
  25619. } );
  25620. }
  25621. createBindings( bindGroup, bindings ) {
  25622. if ( this._knownBindings.has( bindings ) === false ) {
  25623. this._knownBindings.add( bindings );
  25624. let uniformBuffers = 0;
  25625. let textures = 0;
  25626. for ( const bindGroup of bindings ) {
  25627. this.set( bindGroup, {
  25628. textures: textures,
  25629. uniformBuffers: uniformBuffers
  25630. } );
  25631. for ( const binding of bindGroup.bindings ) {
  25632. if ( binding.isUniformBuffer ) uniformBuffers ++;
  25633. if ( binding.isSampledTexture ) textures ++;
  25634. }
  25635. }
  25636. }
  25637. this.updateBindings( bindGroup, bindings );
  25638. }
  25639. updateBindings( bindGroup /*, bindings*/ ) {
  25640. const { gl } = this;
  25641. const bindGroupData = this.get( bindGroup );
  25642. let i = bindGroupData.uniformBuffers;
  25643. let t = bindGroupData.textures;
  25644. for ( const binding of bindGroup.bindings ) {
  25645. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  25646. const data = binding.buffer;
  25647. const bufferGPU = gl.createBuffer();
  25648. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  25649. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  25650. this.set( binding, {
  25651. index: i ++,
  25652. bufferGPU
  25653. } );
  25654. } else if ( binding.isSampledTexture ) {
  25655. const { textureGPU, glTextureType } = this.get( binding.texture );
  25656. this.set( binding, {
  25657. index: t ++,
  25658. textureGPU,
  25659. glTextureType
  25660. } );
  25661. }
  25662. }
  25663. }
  25664. updateBinding( binding ) {
  25665. const gl = this.gl;
  25666. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  25667. const bindingData = this.get( binding );
  25668. const bufferGPU = bindingData.bufferGPU;
  25669. const data = binding.buffer;
  25670. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  25671. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  25672. }
  25673. }
  25674. // attributes
  25675. createIndexAttribute( attribute ) {
  25676. const gl = this.gl;
  25677. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  25678. }
  25679. createAttribute( attribute ) {
  25680. if ( this.has( attribute ) ) return;
  25681. const gl = this.gl;
  25682. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  25683. }
  25684. createStorageAttribute( attribute ) {
  25685. if ( this.has( attribute ) ) return;
  25686. const gl = this.gl;
  25687. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  25688. }
  25689. updateAttribute( attribute ) {
  25690. this.attributeUtils.updateAttribute( attribute );
  25691. }
  25692. destroyAttribute( attribute ) {
  25693. this.attributeUtils.destroyAttribute( attribute );
  25694. }
  25695. updateSize() {
  25696. //console.warn( 'Abstract class.' );
  25697. }
  25698. hasFeature( name ) {
  25699. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  25700. const extensions = this.extensions;
  25701. for ( let i = 0; i < keysMatching.length; i ++ ) {
  25702. if ( extensions.has( keysMatching[ i ] ) ) return true;
  25703. }
  25704. return false;
  25705. }
  25706. getMaxAnisotropy() {
  25707. return this.capabilities.getMaxAnisotropy();
  25708. }
  25709. copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level ) {
  25710. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  25711. }
  25712. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  25713. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  25714. }
  25715. _setFramebuffer( descriptor ) {
  25716. const { gl, state } = this;
  25717. let currentFrameBuffer = null;
  25718. if ( descriptor.textures !== null ) {
  25719. const renderTarget = descriptor.renderTarget;
  25720. const renderTargetContextData = this.get( renderTarget );
  25721. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  25722. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  25723. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  25724. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  25725. const cacheKey = getCacheKey( descriptor );
  25726. let fb;
  25727. if ( isCube ) {
  25728. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  25729. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  25730. } else {
  25731. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  25732. fb = renderTargetContextData.framebuffers[ cacheKey ];
  25733. }
  25734. if ( fb === undefined ) {
  25735. fb = gl.createFramebuffer();
  25736. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  25737. const textures = descriptor.textures;
  25738. if ( isCube ) {
  25739. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  25740. const { textureGPU } = this.get( textures[ 0 ] );
  25741. const cubeFace = this.renderer._activeCubeFace;
  25742. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  25743. } else {
  25744. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  25745. for ( let i = 0; i < textures.length; i ++ ) {
  25746. const texture = textures[ i ];
  25747. const textureData = this.get( texture );
  25748. textureData.renderTarget = descriptor.renderTarget;
  25749. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  25750. const attachment = gl.COLOR_ATTACHMENT0 + i;
  25751. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  25752. }
  25753. state.drawBuffers( descriptor, fb );
  25754. }
  25755. if ( descriptor.depthTexture !== null ) {
  25756. const textureData = this.get( descriptor.depthTexture );
  25757. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  25758. textureData.renderTarget = descriptor.renderTarget;
  25759. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  25760. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  25761. }
  25762. }
  25763. if ( samples > 0 ) {
  25764. if ( msaaFb === undefined ) {
  25765. const invalidationArray = [];
  25766. msaaFb = gl.createFramebuffer();
  25767. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  25768. const msaaRenderbuffers = [];
  25769. const textures = descriptor.textures;
  25770. for ( let i = 0; i < textures.length; i ++ ) {
  25771. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  25772. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  25773. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  25774. if ( depthBuffer ) {
  25775. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  25776. invalidationArray.push( depthStyle );
  25777. }
  25778. const texture = descriptor.textures[ i ];
  25779. const textureData = this.get( texture );
  25780. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  25781. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  25782. }
  25783. renderTargetContextData.msaaFrameBuffer = msaaFb;
  25784. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  25785. if ( depthRenderbuffer === undefined ) {
  25786. depthRenderbuffer = gl.createRenderbuffer();
  25787. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor );
  25788. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  25789. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  25790. invalidationArray.push( depthStyle );
  25791. }
  25792. renderTargetContextData.invalidationArray = invalidationArray;
  25793. }
  25794. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  25795. } else {
  25796. currentFrameBuffer = fb;
  25797. }
  25798. }
  25799. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  25800. }
  25801. _getVaoKey( index, attributes ) {
  25802. let key = [];
  25803. if ( index !== null ) {
  25804. const indexData = this.get( index );
  25805. key += ':' + indexData.id;
  25806. }
  25807. for ( let i = 0; i < attributes.length; i ++ ) {
  25808. const attributeData = this.get( attributes[ i ] );
  25809. key += ':' + attributeData.id;
  25810. }
  25811. return key;
  25812. }
  25813. _createVao( index, attributes ) {
  25814. const { gl } = this;
  25815. const vaoGPU = gl.createVertexArray();
  25816. let key = '';
  25817. let staticVao = true;
  25818. gl.bindVertexArray( vaoGPU );
  25819. if ( index !== null ) {
  25820. const indexData = this.get( index );
  25821. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexData.bufferGPU );
  25822. key += ':' + indexData.id;
  25823. }
  25824. for ( let i = 0; i < attributes.length; i ++ ) {
  25825. const attribute = attributes[ i ];
  25826. const attributeData = this.get( attribute );
  25827. key += ':' + attributeData.id;
  25828. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  25829. gl.enableVertexAttribArray( i );
  25830. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false;
  25831. let stride, offset;
  25832. if ( attribute.isInterleavedBufferAttribute === true ) {
  25833. stride = attribute.data.stride * attributeData.bytesPerElement;
  25834. offset = attribute.offset * attributeData.bytesPerElement;
  25835. } else {
  25836. stride = 0;
  25837. offset = 0;
  25838. }
  25839. if ( attributeData.isInteger ) {
  25840. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  25841. } else {
  25842. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  25843. }
  25844. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  25845. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  25846. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  25847. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  25848. }
  25849. }
  25850. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  25851. this.vaoCache[ key ] = vaoGPU;
  25852. return { vaoGPU, staticVao };
  25853. }
  25854. _getTransformFeedback( transformBuffers ) {
  25855. let key = '';
  25856. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  25857. key += ':' + transformBuffers[ i ].id;
  25858. }
  25859. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  25860. if ( transformFeedbackGPU !== undefined ) {
  25861. return transformFeedbackGPU;
  25862. }
  25863. const { gl } = this;
  25864. transformFeedbackGPU = gl.createTransformFeedback();
  25865. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  25866. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  25867. const attributeData = transformBuffers[ i ];
  25868. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  25869. }
  25870. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  25871. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  25872. return transformFeedbackGPU;
  25873. }
  25874. _setupBindings( bindings, programGPU ) {
  25875. const gl = this.gl;
  25876. for ( const bindGroup of bindings ) {
  25877. for ( const binding of bindGroup.bindings ) {
  25878. const bindingData = this.get( binding );
  25879. const index = bindingData.index;
  25880. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  25881. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  25882. gl.uniformBlockBinding( programGPU, location, index );
  25883. } else if ( binding.isSampledTexture ) {
  25884. const location = gl.getUniformLocation( programGPU, binding.name );
  25885. gl.uniform1i( location, index );
  25886. }
  25887. }
  25888. }
  25889. }
  25890. _bindUniforms( bindings ) {
  25891. const { gl, state } = this;
  25892. for ( const bindGroup of bindings ) {
  25893. for ( const binding of bindGroup.bindings ) {
  25894. const bindingData = this.get( binding );
  25895. const index = bindingData.index;
  25896. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  25897. // TODO USE bindBufferRange to group multiple uniform buffers
  25898. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  25899. } else if ( binding.isSampledTexture ) {
  25900. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  25901. }
  25902. }
  25903. }
  25904. }
  25905. dispose() {
  25906. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  25907. }
  25908. }
  25909. const GPUPrimitiveTopology = {
  25910. PointList: 'point-list',
  25911. LineList: 'line-list',
  25912. LineStrip: 'line-strip',
  25913. TriangleList: 'triangle-list',
  25914. TriangleStrip: 'triangle-strip',
  25915. };
  25916. const GPUCompareFunction = {
  25917. Never: 'never',
  25918. Less: 'less',
  25919. Equal: 'equal',
  25920. LessEqual: 'less-equal',
  25921. Greater: 'greater',
  25922. NotEqual: 'not-equal',
  25923. GreaterEqual: 'greater-equal',
  25924. Always: 'always'
  25925. };
  25926. const GPUStoreOp = {
  25927. Store: 'store',
  25928. Discard: 'discard'
  25929. };
  25930. const GPULoadOp = {
  25931. Load: 'load',
  25932. Clear: 'clear'
  25933. };
  25934. const GPUFrontFace = {
  25935. CCW: 'ccw',
  25936. CW: 'cw'
  25937. };
  25938. const GPUCullMode = {
  25939. None: 'none',
  25940. Front: 'front',
  25941. Back: 'back'
  25942. };
  25943. const GPUIndexFormat = {
  25944. Uint16: 'uint16',
  25945. Uint32: 'uint32'
  25946. };
  25947. const GPUTextureFormat = {
  25948. // 8-bit formats
  25949. R8Unorm: 'r8unorm',
  25950. R8Snorm: 'r8snorm',
  25951. R8Uint: 'r8uint',
  25952. R8Sint: 'r8sint',
  25953. // 16-bit formats
  25954. R16Uint: 'r16uint',
  25955. R16Sint: 'r16sint',
  25956. R16Float: 'r16float',
  25957. RG8Unorm: 'rg8unorm',
  25958. RG8Snorm: 'rg8snorm',
  25959. RG8Uint: 'rg8uint',
  25960. RG8Sint: 'rg8sint',
  25961. // 32-bit formats
  25962. R32Uint: 'r32uint',
  25963. R32Sint: 'r32sint',
  25964. R32Float: 'r32float',
  25965. RG16Uint: 'rg16uint',
  25966. RG16Sint: 'rg16sint',
  25967. RG16Float: 'rg16float',
  25968. RGBA8Unorm: 'rgba8unorm',
  25969. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  25970. RGBA8Snorm: 'rgba8snorm',
  25971. RGBA8Uint: 'rgba8uint',
  25972. RGBA8Sint: 'rgba8sint',
  25973. BGRA8Unorm: 'bgra8unorm',
  25974. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  25975. // Packed 32-bit formats
  25976. RGB9E5UFloat: 'rgb9e5ufloat',
  25977. RGB10A2Unorm: 'rgb10a2unorm',
  25978. RG11B10uFloat: 'rgb10a2unorm',
  25979. // 64-bit formats
  25980. RG32Uint: 'rg32uint',
  25981. RG32Sint: 'rg32sint',
  25982. RG32Float: 'rg32float',
  25983. RGBA16Uint: 'rgba16uint',
  25984. RGBA16Sint: 'rgba16sint',
  25985. RGBA16Float: 'rgba16float',
  25986. // 128-bit formats
  25987. RGBA32Uint: 'rgba32uint',
  25988. RGBA32Sint: 'rgba32sint',
  25989. RGBA32Float: 'rgba32float',
  25990. // Depth and stencil formats
  25991. Stencil8: 'stencil8',
  25992. Depth16Unorm: 'depth16unorm',
  25993. Depth24Plus: 'depth24plus',
  25994. Depth24PlusStencil8: 'depth24plus-stencil8',
  25995. Depth32Float: 'depth32float',
  25996. // 'depth32float-stencil8' extension
  25997. Depth32FloatStencil8: 'depth32float-stencil8',
  25998. // BC compressed formats usable if 'texture-compression-bc' is both
  25999. // supported by the device/user agent and enabled in requestDevice.
  26000. BC1RGBAUnorm: 'bc1-rgba-unorm',
  26001. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  26002. BC2RGBAUnorm: 'bc2-rgba-unorm',
  26003. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  26004. BC3RGBAUnorm: 'bc3-rgba-unorm',
  26005. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  26006. BC4RUnorm: 'bc4-r-unorm',
  26007. BC4RSnorm: 'bc4-r-snorm',
  26008. BC5RGUnorm: 'bc5-rg-unorm',
  26009. BC5RGSnorm: 'bc5-rg-snorm',
  26010. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  26011. BC6HRGBFloat: 'bc6h-rgb-float',
  26012. BC7RGBAUnorm: 'bc7-rgba-unorm',
  26013. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  26014. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  26015. // supported by the device/user agent and enabled in requestDevice.
  26016. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  26017. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  26018. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  26019. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  26020. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  26021. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  26022. EACR11Unorm: 'eac-r11unorm',
  26023. EACR11Snorm: 'eac-r11snorm',
  26024. EACRG11Unorm: 'eac-rg11unorm',
  26025. EACRG11Snorm: 'eac-rg11snorm',
  26026. // ASTC compressed formats usable if 'texture-compression-astc' is both
  26027. // supported by the device/user agent and enabled in requestDevice.
  26028. ASTC4x4Unorm: 'astc-4x4-unorm',
  26029. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  26030. ASTC5x4Unorm: 'astc-5x4-unorm',
  26031. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  26032. ASTC5x5Unorm: 'astc-5x5-unorm',
  26033. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  26034. ASTC6x5Unorm: 'astc-6x5-unorm',
  26035. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  26036. ASTC6x6Unorm: 'astc-6x6-unorm',
  26037. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  26038. ASTC8x5Unorm: 'astc-8x5-unorm',
  26039. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  26040. ASTC8x6Unorm: 'astc-8x6-unorm',
  26041. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  26042. ASTC8x8Unorm: 'astc-8x8-unorm',
  26043. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  26044. ASTC10x5Unorm: 'astc-10x5-unorm',
  26045. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  26046. ASTC10x6Unorm: 'astc-10x6-unorm',
  26047. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  26048. ASTC10x8Unorm: 'astc-10x8-unorm',
  26049. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  26050. ASTC10x10Unorm: 'astc-10x10-unorm',
  26051. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  26052. ASTC12x10Unorm: 'astc-12x10-unorm',
  26053. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  26054. ASTC12x12Unorm: 'astc-12x12-unorm',
  26055. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  26056. };
  26057. const GPUAddressMode = {
  26058. ClampToEdge: 'clamp-to-edge',
  26059. Repeat: 'repeat',
  26060. MirrorRepeat: 'mirror-repeat'
  26061. };
  26062. const GPUFilterMode = {
  26063. Linear: 'linear',
  26064. Nearest: 'nearest'
  26065. };
  26066. const GPUBlendFactor = {
  26067. Zero: 'zero',
  26068. One: 'one',
  26069. Src: 'src',
  26070. OneMinusSrc: 'one-minus-src',
  26071. SrcAlpha: 'src-alpha',
  26072. OneMinusSrcAlpha: 'one-minus-src-alpha',
  26073. Dst: 'dst',
  26074. OneMinusDstColor: 'one-minus-dst',
  26075. DstAlpha: 'dst-alpha',
  26076. OneMinusDstAlpha: 'one-minus-dst-alpha',
  26077. SrcAlphaSaturated: 'src-alpha-saturated',
  26078. Constant: 'constant',
  26079. OneMinusConstant: 'one-minus-constant'
  26080. };
  26081. const GPUBlendOperation = {
  26082. Add: 'add',
  26083. Subtract: 'subtract',
  26084. ReverseSubtract: 'reverse-subtract',
  26085. Min: 'min',
  26086. Max: 'max'
  26087. };
  26088. const GPUColorWriteFlags = {
  26089. None: 0,
  26090. Red: 0x1,
  26091. Green: 0x2,
  26092. Blue: 0x4,
  26093. Alpha: 0x8,
  26094. All: 0xF
  26095. };
  26096. const GPUStencilOperation = {
  26097. Keep: 'keep',
  26098. Zero: 'zero',
  26099. Replace: 'replace',
  26100. Invert: 'invert',
  26101. IncrementClamp: 'increment-clamp',
  26102. DecrementClamp: 'decrement-clamp',
  26103. IncrementWrap: 'increment-wrap',
  26104. DecrementWrap: 'decrement-wrap'
  26105. };
  26106. const GPUBufferBindingType = {
  26107. Uniform: 'uniform',
  26108. Storage: 'storage',
  26109. ReadOnlyStorage: 'read-only-storage'
  26110. };
  26111. const GPUStorageTextureAccess = {
  26112. WriteOnly: 'write-only',
  26113. ReadOnly: 'read-only',
  26114. ReadWrite: 'read-write',
  26115. };
  26116. const GPUTextureSampleType = {
  26117. Float: 'float',
  26118. UnfilterableFloat: 'unfilterable-float',
  26119. Depth: 'depth',
  26120. SInt: 'sint',
  26121. UInt: 'uint'
  26122. };
  26123. const GPUTextureDimension = {
  26124. OneD: '1d',
  26125. TwoD: '2d',
  26126. ThreeD: '3d'
  26127. };
  26128. const GPUTextureViewDimension = {
  26129. OneD: '1d',
  26130. TwoD: '2d',
  26131. TwoDArray: '2d-array',
  26132. Cube: 'cube',
  26133. CubeArray: 'cube-array',
  26134. ThreeD: '3d'
  26135. };
  26136. const GPUTextureAspect = {
  26137. All: 'all',
  26138. StencilOnly: 'stencil-only',
  26139. DepthOnly: 'depth-only'
  26140. };
  26141. const GPUInputStepMode = {
  26142. Vertex: 'vertex',
  26143. Instance: 'instance'
  26144. };
  26145. const GPUFeatureName = {
  26146. DepthClipControl: 'depth-clip-control',
  26147. Depth32FloatStencil8: 'depth32float-stencil8',
  26148. TextureCompressionBC: 'texture-compression-bc',
  26149. TextureCompressionETC2: 'texture-compression-etc2',
  26150. TextureCompressionASTC: 'texture-compression-astc',
  26151. TimestampQuery: 'timestamp-query',
  26152. IndirectFirstInstance: 'indirect-first-instance',
  26153. ShaderF16: 'shader-f16',
  26154. RG11B10UFloat: 'rg11b10ufloat-renderable',
  26155. BGRA8UNormStorage: 'bgra8unorm-storage',
  26156. Float32Filterable: 'float32-filterable',
  26157. ClipDistances: 'clip-distances',
  26158. DualSourceBlending: 'dual-source-blending',
  26159. Subgroups: 'subgroups'
  26160. };
  26161. class Sampler extends Binding {
  26162. constructor( name, texture ) {
  26163. super( name );
  26164. this.texture = texture;
  26165. this.version = texture ? texture.version : 0;
  26166. this.isSampler = true;
  26167. }
  26168. }
  26169. class NodeSampler extends Sampler {
  26170. constructor( name, textureNode, groupNode ) {
  26171. super( name, textureNode ? textureNode.value : null );
  26172. this.textureNode = textureNode;
  26173. this.groupNode = groupNode;
  26174. }
  26175. update() {
  26176. this.texture = this.textureNode.value;
  26177. }
  26178. }
  26179. class StorageBuffer extends Buffer {
  26180. constructor( name, attribute ) {
  26181. super( name, attribute ? attribute.array : null );
  26182. this.attribute = attribute;
  26183. this.isStorageBuffer = true;
  26184. }
  26185. }
  26186. let _id = 0;
  26187. class NodeStorageBuffer extends StorageBuffer {
  26188. constructor( nodeUniform, groupNode ) {
  26189. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  26190. this.nodeUniform = nodeUniform;
  26191. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  26192. this.groupNode = groupNode;
  26193. }
  26194. get buffer() {
  26195. return this.nodeUniform.value;
  26196. }
  26197. }
  26198. class WebGPUTexturePassUtils extends DataMap {
  26199. constructor( device ) {
  26200. super();
  26201. this.device = device;
  26202. const mipmapVertexSource = `
  26203. struct VarysStruct {
  26204. @builtin( position ) Position: vec4<f32>,
  26205. @location( 0 ) vTex : vec2<f32>
  26206. };
  26207. @vertex
  26208. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  26209. var Varys : VarysStruct;
  26210. var pos = array< vec2<f32>, 4 >(
  26211. vec2<f32>( -1.0, 1.0 ),
  26212. vec2<f32>( 1.0, 1.0 ),
  26213. vec2<f32>( -1.0, -1.0 ),
  26214. vec2<f32>( 1.0, -1.0 )
  26215. );
  26216. var tex = array< vec2<f32>, 4 >(
  26217. vec2<f32>( 0.0, 0.0 ),
  26218. vec2<f32>( 1.0, 0.0 ),
  26219. vec2<f32>( 0.0, 1.0 ),
  26220. vec2<f32>( 1.0, 1.0 )
  26221. );
  26222. Varys.vTex = tex[ vertexIndex ];
  26223. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  26224. return Varys;
  26225. }
  26226. `;
  26227. const mipmapFragmentSource = `
  26228. @group( 0 ) @binding( 0 )
  26229. var imgSampler : sampler;
  26230. @group( 0 ) @binding( 1 )
  26231. var img : texture_2d<f32>;
  26232. @fragment
  26233. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  26234. return textureSample( img, imgSampler, vTex );
  26235. }
  26236. `;
  26237. const flipYFragmentSource = `
  26238. @group( 0 ) @binding( 0 )
  26239. var imgSampler : sampler;
  26240. @group( 0 ) @binding( 1 )
  26241. var img : texture_2d<f32>;
  26242. @fragment
  26243. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  26244. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  26245. }
  26246. `;
  26247. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  26248. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  26249. // We'll need a new pipeline for every texture format used.
  26250. this.transferPipelines = {};
  26251. this.flipYPipelines = {};
  26252. this.mipmapVertexShaderModule = device.createShaderModule( {
  26253. label: 'mipmapVertex',
  26254. code: mipmapVertexSource
  26255. } );
  26256. this.mipmapFragmentShaderModule = device.createShaderModule( {
  26257. label: 'mipmapFragment',
  26258. code: mipmapFragmentSource
  26259. } );
  26260. this.flipYFragmentShaderModule = device.createShaderModule( {
  26261. label: 'flipYFragment',
  26262. code: flipYFragmentSource
  26263. } );
  26264. }
  26265. getTransferPipeline( format ) {
  26266. let pipeline = this.transferPipelines[ format ];
  26267. if ( pipeline === undefined ) {
  26268. pipeline = this.device.createRenderPipeline( {
  26269. label: `mipmap-${ format }`,
  26270. vertex: {
  26271. module: this.mipmapVertexShaderModule,
  26272. entryPoint: 'main'
  26273. },
  26274. fragment: {
  26275. module: this.mipmapFragmentShaderModule,
  26276. entryPoint: 'main',
  26277. targets: [ { format } ]
  26278. },
  26279. primitive: {
  26280. topology: GPUPrimitiveTopology.TriangleStrip,
  26281. stripIndexFormat: GPUIndexFormat.Uint32
  26282. },
  26283. layout: 'auto'
  26284. } );
  26285. this.transferPipelines[ format ] = pipeline;
  26286. }
  26287. return pipeline;
  26288. }
  26289. getFlipYPipeline( format ) {
  26290. let pipeline = this.flipYPipelines[ format ];
  26291. if ( pipeline === undefined ) {
  26292. pipeline = this.device.createRenderPipeline( {
  26293. label: `flipY-${ format }`,
  26294. vertex: {
  26295. module: this.mipmapVertexShaderModule,
  26296. entryPoint: 'main'
  26297. },
  26298. fragment: {
  26299. module: this.flipYFragmentShaderModule,
  26300. entryPoint: 'main',
  26301. targets: [ { format } ]
  26302. },
  26303. primitive: {
  26304. topology: GPUPrimitiveTopology.TriangleStrip,
  26305. stripIndexFormat: GPUIndexFormat.Uint32
  26306. },
  26307. layout: 'auto'
  26308. } );
  26309. this.flipYPipelines[ format ] = pipeline;
  26310. }
  26311. return pipeline;
  26312. }
  26313. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  26314. const format = textureGPUDescriptor.format;
  26315. const { width, height } = textureGPUDescriptor.size;
  26316. const transferPipeline = this.getTransferPipeline( format );
  26317. const flipYPipeline = this.getFlipYPipeline( format );
  26318. const tempTexture = this.device.createTexture( {
  26319. size: { width, height, depthOrArrayLayers: 1 },
  26320. format,
  26321. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  26322. } );
  26323. const srcView = textureGPU.createView( {
  26324. baseMipLevel: 0,
  26325. mipLevelCount: 1,
  26326. dimension: GPUTextureViewDimension.TwoD,
  26327. baseArrayLayer
  26328. } );
  26329. const dstView = tempTexture.createView( {
  26330. baseMipLevel: 0,
  26331. mipLevelCount: 1,
  26332. dimension: GPUTextureViewDimension.TwoD,
  26333. baseArrayLayer: 0
  26334. } );
  26335. const commandEncoder = this.device.createCommandEncoder( {} );
  26336. const pass = ( pipeline, sourceView, destinationView ) => {
  26337. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  26338. const bindGroup = this.device.createBindGroup( {
  26339. layout: bindGroupLayout,
  26340. entries: [ {
  26341. binding: 0,
  26342. resource: this.flipYSampler
  26343. }, {
  26344. binding: 1,
  26345. resource: sourceView
  26346. } ]
  26347. } );
  26348. const passEncoder = commandEncoder.beginRenderPass( {
  26349. colorAttachments: [ {
  26350. view: destinationView,
  26351. loadOp: GPULoadOp.Clear,
  26352. storeOp: GPUStoreOp.Store,
  26353. clearValue: [ 0, 0, 0, 0 ]
  26354. } ]
  26355. } );
  26356. passEncoder.setPipeline( pipeline );
  26357. passEncoder.setBindGroup( 0, bindGroup );
  26358. passEncoder.draw( 4, 1, 0, 0 );
  26359. passEncoder.end();
  26360. };
  26361. pass( transferPipeline, srcView, dstView );
  26362. pass( flipYPipeline, dstView, srcView );
  26363. this.device.queue.submit( [ commandEncoder.finish() ] );
  26364. tempTexture.destroy();
  26365. }
  26366. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  26367. const textureData = this.get( textureGPU );
  26368. if ( textureData.useCount === undefined ) {
  26369. textureData.useCount = 0;
  26370. textureData.layers = [];
  26371. }
  26372. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  26373. const commandEncoder = this.device.createCommandEncoder( {} );
  26374. this._mipmapRunBundles( commandEncoder, passes );
  26375. this.device.queue.submit( [ commandEncoder.finish() ] );
  26376. if ( textureData.useCount !== 0 ) textureData.layers[ baseArrayLayer ] = passes;
  26377. textureData.useCount ++;
  26378. }
  26379. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  26380. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  26381. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  26382. let srcView = textureGPU.createView( {
  26383. baseMipLevel: 0,
  26384. mipLevelCount: 1,
  26385. dimension: GPUTextureViewDimension.TwoD,
  26386. baseArrayLayer
  26387. } );
  26388. const passes = [];
  26389. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  26390. const bindGroup = this.device.createBindGroup( {
  26391. layout: bindGroupLayout,
  26392. entries: [ {
  26393. binding: 0,
  26394. resource: this.mipmapSampler
  26395. }, {
  26396. binding: 1,
  26397. resource: srcView
  26398. } ]
  26399. } );
  26400. const dstView = textureGPU.createView( {
  26401. baseMipLevel: i,
  26402. mipLevelCount: 1,
  26403. dimension: GPUTextureViewDimension.TwoD,
  26404. baseArrayLayer
  26405. } );
  26406. const passDescriptor = {
  26407. colorAttachments: [ {
  26408. view: dstView,
  26409. loadOp: GPULoadOp.Clear,
  26410. storeOp: GPUStoreOp.Store,
  26411. clearValue: [ 0, 0, 0, 0 ]
  26412. } ]
  26413. };
  26414. const passEncoder = this.device.createRenderBundleEncoder( {
  26415. colorFormats: [ textureGPUDescriptor.format ]
  26416. } );
  26417. passEncoder.setPipeline( pipeline );
  26418. passEncoder.setBindGroup( 0, bindGroup );
  26419. passEncoder.draw( 4, 1, 0, 0 );
  26420. passes.push( {
  26421. renderBundles: [ passEncoder.finish() ],
  26422. passDescriptor
  26423. } );
  26424. srcView = dstView;
  26425. }
  26426. return passes;
  26427. }
  26428. _mipmapRunBundles( commandEncoder, passes ) {
  26429. const levels = passes.length;
  26430. for ( let i = 0; i < levels; i ++ ) {
  26431. const pass = passes[ i ];
  26432. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  26433. passEncoder.executeBundles( pass.renderBundles );
  26434. passEncoder.end();
  26435. }
  26436. }
  26437. }
  26438. const _compareToWebGPU = {
  26439. [ NeverCompare ]: 'never',
  26440. [ LessCompare ]: 'less',
  26441. [ EqualCompare ]: 'equal',
  26442. [ LessEqualCompare ]: 'less-equal',
  26443. [ GreaterCompare ]: 'greater',
  26444. [ GreaterEqualCompare ]: 'greater-equal',
  26445. [ AlwaysCompare ]: 'always',
  26446. [ NotEqualCompare ]: 'not-equal'
  26447. };
  26448. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  26449. class WebGPUTextureUtils {
  26450. constructor( backend ) {
  26451. this.backend = backend;
  26452. this._passUtils = null;
  26453. this.defaultTexture = {};
  26454. this.defaultCubeTexture = {};
  26455. this.defaultVideoFrame = null;
  26456. this.colorBuffer = null;
  26457. this.depthTexture = new DepthTexture();
  26458. this.depthTexture.name = 'depthBuffer';
  26459. }
  26460. createSampler( texture ) {
  26461. const backend = this.backend;
  26462. const device = backend.device;
  26463. const textureGPU = backend.get( texture );
  26464. const samplerDescriptorGPU = {
  26465. addressModeU: this._convertAddressMode( texture.wrapS ),
  26466. addressModeV: this._convertAddressMode( texture.wrapT ),
  26467. addressModeW: this._convertAddressMode( texture.wrapR ),
  26468. magFilter: this._convertFilterMode( texture.magFilter ),
  26469. minFilter: this._convertFilterMode( texture.minFilter ),
  26470. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  26471. maxAnisotropy: 1
  26472. };
  26473. // anisotropy can only be used when all filter modes are set to linear.
  26474. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  26475. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  26476. }
  26477. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  26478. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  26479. }
  26480. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  26481. }
  26482. createDefaultTexture( texture ) {
  26483. let textureGPU;
  26484. const format = getFormat( texture );
  26485. if ( texture.isCubeTexture ) {
  26486. textureGPU = this._getDefaultCubeTextureGPU( format );
  26487. } else if ( texture.isVideoTexture ) {
  26488. this.backend.get( texture ).externalTexture = this._getDefaultVideoFrame();
  26489. } else {
  26490. textureGPU = this._getDefaultTextureGPU( format );
  26491. }
  26492. this.backend.get( texture ).texture = textureGPU;
  26493. }
  26494. createTexture( texture, options = {} ) {
  26495. const backend = this.backend;
  26496. const textureData = backend.get( texture );
  26497. if ( textureData.initialized ) {
  26498. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  26499. }
  26500. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  26501. if ( options.levels === undefined ) options.levels = 1;
  26502. if ( options.depth === undefined ) options.depth = 1;
  26503. const { width, height, depth, levels } = options;
  26504. if ( texture.isFramebufferTexture ) {
  26505. if ( options.renderTarget ) {
  26506. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  26507. } else {
  26508. options.format = this.backend.utils.getPreferredCanvasFormat();
  26509. }
  26510. }
  26511. const dimension = this._getDimension( texture );
  26512. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  26513. textureData.format = format;
  26514. const { samples, primarySamples, isMSAA } = backend.utils.getTextureSampleData( texture );
  26515. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  26516. if ( texture.isStorageTexture === true ) {
  26517. usage |= GPUTextureUsage.STORAGE_BINDING;
  26518. }
  26519. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true ) {
  26520. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  26521. }
  26522. const textureDescriptorGPU = {
  26523. label: texture.name,
  26524. size: {
  26525. width: width,
  26526. height: height,
  26527. depthOrArrayLayers: depth,
  26528. },
  26529. mipLevelCount: levels,
  26530. sampleCount: primarySamples,
  26531. dimension: dimension,
  26532. format: format,
  26533. usage: usage
  26534. };
  26535. // texture creation
  26536. if ( texture.isVideoTexture ) {
  26537. const video = texture.source.data;
  26538. const videoFrame = new VideoFrame( video );
  26539. textureDescriptorGPU.size.width = videoFrame.displayWidth;
  26540. textureDescriptorGPU.size.height = videoFrame.displayHeight;
  26541. videoFrame.close();
  26542. textureData.externalTexture = video;
  26543. } else {
  26544. if ( format === undefined ) {
  26545. console.warn( 'WebGPURenderer: Texture format not supported.' );
  26546. return this.createDefaultTexture( texture );
  26547. }
  26548. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  26549. }
  26550. if ( isMSAA ) {
  26551. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  26552. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  26553. msaaTextureDescriptorGPU.sampleCount = samples;
  26554. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  26555. }
  26556. textureData.initialized = true;
  26557. textureData.textureDescriptorGPU = textureDescriptorGPU;
  26558. }
  26559. destroyTexture( texture ) {
  26560. const backend = this.backend;
  26561. const textureData = backend.get( texture );
  26562. if ( textureData.texture !== undefined ) textureData.texture.destroy();
  26563. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  26564. backend.delete( texture );
  26565. }
  26566. destroySampler( texture ) {
  26567. const backend = this.backend;
  26568. const textureData = backend.get( texture );
  26569. delete textureData.sampler;
  26570. }
  26571. generateMipmaps( texture ) {
  26572. const textureData = this.backend.get( texture );
  26573. if ( texture.isCubeTexture ) {
  26574. for ( let i = 0; i < 6; i ++ ) {
  26575. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  26576. }
  26577. } else {
  26578. const depth = texture.image.depth || 1;
  26579. for ( let i = 0; i < depth; i ++ ) {
  26580. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  26581. }
  26582. }
  26583. }
  26584. getColorBuffer() {
  26585. if ( this.colorBuffer ) this.colorBuffer.destroy();
  26586. const backend = this.backend;
  26587. const { width, height } = backend.getDrawingBufferSize();
  26588. this.colorBuffer = backend.device.createTexture( {
  26589. label: 'colorBuffer',
  26590. size: {
  26591. width: width,
  26592. height: height,
  26593. depthOrArrayLayers: 1
  26594. },
  26595. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  26596. format: backend.utils.getPreferredCanvasFormat(),
  26597. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  26598. } );
  26599. return this.colorBuffer;
  26600. }
  26601. getDepthBuffer( depth = true, stencil = false ) {
  26602. const backend = this.backend;
  26603. const { width, height } = backend.getDrawingBufferSize();
  26604. const depthTexture = this.depthTexture;
  26605. const depthTextureGPU = backend.get( depthTexture ).texture;
  26606. let format, type;
  26607. if ( stencil ) {
  26608. format = DepthStencilFormat;
  26609. type = UnsignedInt248Type;
  26610. } else if ( depth ) {
  26611. format = DepthFormat;
  26612. type = UnsignedIntType;
  26613. }
  26614. if ( depthTextureGPU !== undefined ) {
  26615. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  26616. return depthTextureGPU;
  26617. }
  26618. this.destroyTexture( depthTexture );
  26619. }
  26620. depthTexture.name = 'depthBuffer';
  26621. depthTexture.format = format;
  26622. depthTexture.type = type;
  26623. depthTexture.image.width = width;
  26624. depthTexture.image.height = height;
  26625. this.createTexture( depthTexture, { width, height } );
  26626. return backend.get( depthTexture ).texture;
  26627. }
  26628. updateTexture( texture, options ) {
  26629. const textureData = this.backend.get( texture );
  26630. const { textureDescriptorGPU } = textureData;
  26631. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  26632. return;
  26633. // transfer texture data
  26634. if ( texture.isDataTexture ) {
  26635. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  26636. } else if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  26637. for ( let i = 0; i < options.image.depth; i ++ ) {
  26638. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  26639. }
  26640. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  26641. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  26642. } else if ( texture.isCubeTexture ) {
  26643. this._copyCubeMapToTexture( options.images, textureData.texture, textureDescriptorGPU, texture.flipY );
  26644. } else if ( texture.isVideoTexture ) {
  26645. const video = texture.source.data;
  26646. textureData.externalTexture = video;
  26647. } else {
  26648. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  26649. }
  26650. //
  26651. textureData.version = texture.version;
  26652. if ( texture.onUpdate ) texture.onUpdate( texture );
  26653. }
  26654. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  26655. const device = this.backend.device;
  26656. const textureData = this.backend.get( texture );
  26657. const textureGPU = textureData.texture;
  26658. const format = textureData.textureDescriptorGPU.format;
  26659. const bytesPerTexel = this._getBytesPerTexel( format );
  26660. let bytesPerRow = width * bytesPerTexel;
  26661. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  26662. const readBuffer = device.createBuffer(
  26663. {
  26664. size: width * height * bytesPerTexel,
  26665. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  26666. }
  26667. );
  26668. const encoder = device.createCommandEncoder();
  26669. encoder.copyTextureToBuffer(
  26670. {
  26671. texture: textureGPU,
  26672. origin: { x, y, z: faceIndex },
  26673. },
  26674. {
  26675. buffer: readBuffer,
  26676. bytesPerRow: bytesPerRow
  26677. },
  26678. {
  26679. width: width,
  26680. height: height
  26681. }
  26682. );
  26683. const typedArrayType = this._getTypedArrayType( format );
  26684. device.queue.submit( [ encoder.finish() ] );
  26685. await readBuffer.mapAsync( GPUMapMode.READ );
  26686. const buffer = readBuffer.getMappedRange();
  26687. return new typedArrayType( buffer );
  26688. }
  26689. _isEnvironmentTexture( texture ) {
  26690. const mapping = texture.mapping;
  26691. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  26692. }
  26693. _getDefaultTextureGPU( format ) {
  26694. let defaultTexture = this.defaultTexture[ format ];
  26695. if ( defaultTexture === undefined ) {
  26696. const texture = new Texture();
  26697. texture.minFilter = NearestFilter;
  26698. texture.magFilter = NearestFilter;
  26699. this.createTexture( texture, { width: 1, height: 1, format } );
  26700. this.defaultTexture[ format ] = defaultTexture = texture;
  26701. }
  26702. return this.backend.get( defaultTexture ).texture;
  26703. }
  26704. _getDefaultCubeTextureGPU( format ) {
  26705. let defaultCubeTexture = this.defaultTexture[ format ];
  26706. if ( defaultCubeTexture === undefined ) {
  26707. const texture = new CubeTexture();
  26708. texture.minFilter = NearestFilter;
  26709. texture.magFilter = NearestFilter;
  26710. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  26711. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  26712. }
  26713. return this.backend.get( defaultCubeTexture ).texture;
  26714. }
  26715. _getDefaultVideoFrame() {
  26716. let defaultVideoFrame = this.defaultVideoFrame;
  26717. if ( defaultVideoFrame === null ) {
  26718. const init = {
  26719. timestamp: 0,
  26720. codedWidth: 1,
  26721. codedHeight: 1,
  26722. format: 'RGBA',
  26723. };
  26724. this.defaultVideoFrame = defaultVideoFrame = new VideoFrame( new Uint8Array( [ 0, 0, 0, 0xff ] ), init );
  26725. }
  26726. return defaultVideoFrame;
  26727. }
  26728. _copyCubeMapToTexture( images, textureGPU, textureDescriptorGPU, flipY ) {
  26729. for ( let i = 0; i < 6; i ++ ) {
  26730. const image = images[ i ];
  26731. const flipIndex = flipY === true ? _flipMap[ i ] : i;
  26732. if ( image.isDataTexture ) {
  26733. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  26734. } else {
  26735. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  26736. }
  26737. }
  26738. }
  26739. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY ) {
  26740. const device = this.backend.device;
  26741. device.queue.copyExternalImageToTexture(
  26742. {
  26743. source: image
  26744. }, {
  26745. texture: textureGPU,
  26746. mipLevel: 0,
  26747. origin: { x: 0, y: 0, z: originDepth }
  26748. }, {
  26749. width: image.width,
  26750. height: image.height,
  26751. depthOrArrayLayers: 1
  26752. }
  26753. );
  26754. if ( flipY === true ) {
  26755. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  26756. }
  26757. }
  26758. _getPassUtils() {
  26759. let passUtils = this._passUtils;
  26760. if ( passUtils === null ) {
  26761. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  26762. }
  26763. return passUtils;
  26764. }
  26765. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  26766. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  26767. }
  26768. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  26769. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  26770. }
  26771. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0 ) {
  26772. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  26773. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  26774. const device = this.backend.device;
  26775. const data = image.data;
  26776. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  26777. const bytesPerRow = image.width * bytesPerTexel;
  26778. device.queue.writeTexture(
  26779. {
  26780. texture: textureGPU,
  26781. mipLevel: 0,
  26782. origin: { x: 0, y: 0, z: originDepth }
  26783. },
  26784. data,
  26785. {
  26786. offset: image.width * image.height * bytesPerTexel * depth,
  26787. bytesPerRow
  26788. },
  26789. {
  26790. width: image.width,
  26791. height: image.height,
  26792. depthOrArrayLayers: 1
  26793. } );
  26794. if ( flipY === true ) {
  26795. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  26796. }
  26797. }
  26798. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  26799. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  26800. const device = this.backend.device;
  26801. const blockData = this._getBlockData( textureDescriptorGPU.format );
  26802. const isTextureArray = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  26803. for ( let i = 0; i < mipmaps.length; i ++ ) {
  26804. const mipmap = mipmaps[ i ];
  26805. const width = mipmap.width;
  26806. const height = mipmap.height;
  26807. const depth = isTextureArray ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  26808. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  26809. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  26810. for ( let j = 0; j < depth; j ++ ) {
  26811. device.queue.writeTexture(
  26812. {
  26813. texture: textureGPU,
  26814. mipLevel: i,
  26815. origin: { x: 0, y: 0, z: j }
  26816. },
  26817. mipmap.data,
  26818. {
  26819. offset: j * bytesPerImage,
  26820. bytesPerRow,
  26821. rowsPerImage: Math.ceil( height / blockData.height )
  26822. },
  26823. {
  26824. width: Math.ceil( width / blockData.width ) * blockData.width,
  26825. height: Math.ceil( height / blockData.height ) * blockData.height,
  26826. depthOrArrayLayers: 1
  26827. }
  26828. );
  26829. }
  26830. }
  26831. }
  26832. _getBlockData( format ) {
  26833. // this method is only relevant for compressed texture formats
  26834. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  26835. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  26836. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  26837. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSNorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  26838. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  26839. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  26840. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  26841. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  26842. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  26843. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  26844. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  26845. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  26846. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  26847. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  26848. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  26849. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  26850. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  26851. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  26852. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  26853. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  26854. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  26855. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  26856. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  26857. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  26858. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  26859. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  26860. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  26861. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  26862. }
  26863. _convertAddressMode( value ) {
  26864. let addressMode = GPUAddressMode.ClampToEdge;
  26865. if ( value === RepeatWrapping ) {
  26866. addressMode = GPUAddressMode.Repeat;
  26867. } else if ( value === MirroredRepeatWrapping ) {
  26868. addressMode = GPUAddressMode.MirrorRepeat;
  26869. }
  26870. return addressMode;
  26871. }
  26872. _convertFilterMode( value ) {
  26873. let filterMode = GPUFilterMode.Linear;
  26874. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  26875. filterMode = GPUFilterMode.Nearest;
  26876. }
  26877. return filterMode;
  26878. }
  26879. _getBytesPerTexel( format ) {
  26880. // 8-bit formats
  26881. if ( format === GPUTextureFormat.R8Unorm ||
  26882. format === GPUTextureFormat.R8Snorm ||
  26883. format === GPUTextureFormat.R8Uint ||
  26884. format === GPUTextureFormat.R8Sint ) return 1;
  26885. // 16-bit formats
  26886. if ( format === GPUTextureFormat.R16Uint ||
  26887. format === GPUTextureFormat.R16Sint ||
  26888. format === GPUTextureFormat.R16Float ||
  26889. format === GPUTextureFormat.RG8Unorm ||
  26890. format === GPUTextureFormat.RG8Snorm ||
  26891. format === GPUTextureFormat.RG8Uint ||
  26892. format === GPUTextureFormat.RG8Sint ) return 2;
  26893. // 32-bit formats
  26894. if ( format === GPUTextureFormat.R32Uint ||
  26895. format === GPUTextureFormat.R32Sint ||
  26896. format === GPUTextureFormat.R32Float ||
  26897. format === GPUTextureFormat.RG16Uint ||
  26898. format === GPUTextureFormat.RG16Sint ||
  26899. format === GPUTextureFormat.RG16Float ||
  26900. format === GPUTextureFormat.RGBA8Unorm ||
  26901. format === GPUTextureFormat.RGBA8UnormSRGB ||
  26902. format === GPUTextureFormat.RGBA8Snorm ||
  26903. format === GPUTextureFormat.RGBA8Uint ||
  26904. format === GPUTextureFormat.RGBA8Sint ||
  26905. format === GPUTextureFormat.BGRA8Unorm ||
  26906. format === GPUTextureFormat.BGRA8UnormSRGB ||
  26907. // Packed 32-bit formats
  26908. format === GPUTextureFormat.RGB9E5UFloat ||
  26909. format === GPUTextureFormat.RGB10A2Unorm ||
  26910. format === GPUTextureFormat.RG11B10UFloat ||
  26911. format === GPUTextureFormat.Depth32Float ||
  26912. format === GPUTextureFormat.Depth24Plus ||
  26913. format === GPUTextureFormat.Depth24PlusStencil8 ||
  26914. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  26915. // 64-bit formats
  26916. if ( format === GPUTextureFormat.RG32Uint ||
  26917. format === GPUTextureFormat.RG32Sint ||
  26918. format === GPUTextureFormat.RG32Float ||
  26919. format === GPUTextureFormat.RGBA16Uint ||
  26920. format === GPUTextureFormat.RGBA16Sint ||
  26921. format === GPUTextureFormat.RGBA16Float ) return 8;
  26922. // 128-bit formats
  26923. if ( format === GPUTextureFormat.RGBA32Uint ||
  26924. format === GPUTextureFormat.RGBA32Sint ||
  26925. format === GPUTextureFormat.RGBA32Float ) return 16;
  26926. }
  26927. _getTypedArrayType( format ) {
  26928. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  26929. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  26930. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  26931. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  26932. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  26933. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  26934. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  26935. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  26936. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  26937. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  26938. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  26939. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  26940. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  26941. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  26942. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  26943. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  26944. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  26945. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  26946. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  26947. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  26948. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  26949. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  26950. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  26951. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  26952. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  26953. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  26954. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  26955. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  26956. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  26957. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  26958. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  26959. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  26960. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  26961. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  26962. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  26963. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  26964. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  26965. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  26966. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  26967. }
  26968. _getDimension( texture ) {
  26969. let dimension;
  26970. if ( texture.isData3DTexture ) {
  26971. dimension = GPUTextureDimension.ThreeD;
  26972. } else {
  26973. dimension = GPUTextureDimension.TwoD;
  26974. }
  26975. return dimension;
  26976. }
  26977. }
  26978. function getFormat( texture, device = null ) {
  26979. const format = texture.format;
  26980. const type = texture.type;
  26981. const colorSpace = texture.colorSpace;
  26982. let formatGPU;
  26983. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  26984. switch ( format ) {
  26985. case RGBA_S3TC_DXT1_Format:
  26986. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  26987. break;
  26988. case RGBA_S3TC_DXT3_Format:
  26989. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  26990. break;
  26991. case RGBA_S3TC_DXT5_Format:
  26992. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  26993. break;
  26994. case RGB_ETC2_Format:
  26995. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  26996. break;
  26997. case RGBA_ETC2_EAC_Format:
  26998. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  26999. break;
  27000. case RGBA_ASTC_4x4_Format:
  27001. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  27002. break;
  27003. case RGBA_ASTC_5x4_Format:
  27004. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  27005. break;
  27006. case RGBA_ASTC_5x5_Format:
  27007. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  27008. break;
  27009. case RGBA_ASTC_6x5_Format:
  27010. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  27011. break;
  27012. case RGBA_ASTC_6x6_Format:
  27013. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  27014. break;
  27015. case RGBA_ASTC_8x5_Format:
  27016. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  27017. break;
  27018. case RGBA_ASTC_8x6_Format:
  27019. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  27020. break;
  27021. case RGBA_ASTC_8x8_Format:
  27022. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  27023. break;
  27024. case RGBA_ASTC_10x5_Format:
  27025. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  27026. break;
  27027. case RGBA_ASTC_10x6_Format:
  27028. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  27029. break;
  27030. case RGBA_ASTC_10x8_Format:
  27031. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  27032. break;
  27033. case RGBA_ASTC_10x10_Format:
  27034. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  27035. break;
  27036. case RGBA_ASTC_12x10_Format:
  27037. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  27038. break;
  27039. case RGBA_ASTC_12x12_Format:
  27040. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  27041. break;
  27042. case RGBAFormat:
  27043. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  27044. break;
  27045. default:
  27046. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  27047. }
  27048. } else {
  27049. switch ( format ) {
  27050. case RGBAFormat:
  27051. switch ( type ) {
  27052. case ByteType:
  27053. formatGPU = GPUTextureFormat.RGBA8Snorm;
  27054. break;
  27055. case ShortType:
  27056. formatGPU = GPUTextureFormat.RGBA16Sint;
  27057. break;
  27058. case UnsignedShortType:
  27059. formatGPU = GPUTextureFormat.RGBA16Uint;
  27060. break;
  27061. case UnsignedIntType:
  27062. formatGPU = GPUTextureFormat.RGBA32Uint;
  27063. break;
  27064. case IntType:
  27065. formatGPU = GPUTextureFormat.RGBA32Sint;
  27066. break;
  27067. case UnsignedByteType:
  27068. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  27069. break;
  27070. case HalfFloatType:
  27071. formatGPU = GPUTextureFormat.RGBA16Float;
  27072. break;
  27073. case FloatType:
  27074. formatGPU = GPUTextureFormat.RGBA32Float;
  27075. break;
  27076. default:
  27077. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  27078. }
  27079. break;
  27080. case RGBFormat:
  27081. switch ( type ) {
  27082. case UnsignedInt5999Type:
  27083. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  27084. break;
  27085. default:
  27086. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  27087. }
  27088. break;
  27089. case RedFormat:
  27090. switch ( type ) {
  27091. case ByteType:
  27092. formatGPU = GPUTextureFormat.R8Snorm;
  27093. break;
  27094. case ShortType:
  27095. formatGPU = GPUTextureFormat.R16Sint;
  27096. break;
  27097. case UnsignedShortType:
  27098. formatGPU = GPUTextureFormat.R16Uint;
  27099. break;
  27100. case UnsignedIntType:
  27101. formatGPU = GPUTextureFormat.R32Uint;
  27102. break;
  27103. case IntType:
  27104. formatGPU = GPUTextureFormat.R32Sint;
  27105. break;
  27106. case UnsignedByteType:
  27107. formatGPU = GPUTextureFormat.R8Unorm;
  27108. break;
  27109. case HalfFloatType:
  27110. formatGPU = GPUTextureFormat.R16Float;
  27111. break;
  27112. case FloatType:
  27113. formatGPU = GPUTextureFormat.R32Float;
  27114. break;
  27115. default:
  27116. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  27117. }
  27118. break;
  27119. case RGFormat:
  27120. switch ( type ) {
  27121. case ByteType:
  27122. formatGPU = GPUTextureFormat.RG8Snorm;
  27123. break;
  27124. case ShortType:
  27125. formatGPU = GPUTextureFormat.RG16Sint;
  27126. break;
  27127. case UnsignedShortType:
  27128. formatGPU = GPUTextureFormat.RG16Uint;
  27129. break;
  27130. case UnsignedIntType:
  27131. formatGPU = GPUTextureFormat.RG32Uint;
  27132. break;
  27133. case IntType:
  27134. formatGPU = GPUTextureFormat.RG32Sint;
  27135. break;
  27136. case UnsignedByteType:
  27137. formatGPU = GPUTextureFormat.RG8Unorm;
  27138. break;
  27139. case HalfFloatType:
  27140. formatGPU = GPUTextureFormat.RG16Float;
  27141. break;
  27142. case FloatType:
  27143. formatGPU = GPUTextureFormat.RG32Float;
  27144. break;
  27145. default:
  27146. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  27147. }
  27148. break;
  27149. case DepthFormat:
  27150. switch ( type ) {
  27151. case UnsignedShortType:
  27152. formatGPU = GPUTextureFormat.Depth16Unorm;
  27153. break;
  27154. case UnsignedIntType:
  27155. formatGPU = GPUTextureFormat.Depth24Plus;
  27156. break;
  27157. case FloatType:
  27158. formatGPU = GPUTextureFormat.Depth32Float;
  27159. break;
  27160. default:
  27161. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  27162. }
  27163. break;
  27164. case DepthStencilFormat:
  27165. switch ( type ) {
  27166. case UnsignedInt248Type:
  27167. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  27168. break;
  27169. case FloatType:
  27170. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  27171. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  27172. }
  27173. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  27174. break;
  27175. default:
  27176. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  27177. }
  27178. break;
  27179. case RedIntegerFormat:
  27180. switch ( type ) {
  27181. case IntType:
  27182. formatGPU = GPUTextureFormat.R32Sint;
  27183. break;
  27184. case UnsignedIntType:
  27185. formatGPU = GPUTextureFormat.R32Uint;
  27186. break;
  27187. default:
  27188. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  27189. }
  27190. break;
  27191. case RGIntegerFormat:
  27192. switch ( type ) {
  27193. case IntType:
  27194. formatGPU = GPUTextureFormat.RG32Sint;
  27195. break;
  27196. case UnsignedIntType:
  27197. formatGPU = GPUTextureFormat.RG32Uint;
  27198. break;
  27199. default:
  27200. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  27201. }
  27202. break;
  27203. case RGBAIntegerFormat:
  27204. switch ( type ) {
  27205. case IntType:
  27206. formatGPU = GPUTextureFormat.RGBA32Sint;
  27207. break;
  27208. case UnsignedIntType:
  27209. formatGPU = GPUTextureFormat.RGBA32Uint;
  27210. break;
  27211. default:
  27212. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  27213. }
  27214. break;
  27215. default:
  27216. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  27217. }
  27218. }
  27219. return formatGPU;
  27220. }
  27221. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  27222. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  27223. const wgslTypeLib$1 = {
  27224. 'f32': 'float',
  27225. 'i32': 'int',
  27226. 'u32': 'uint',
  27227. 'bool': 'bool',
  27228. 'vec2<f32>': 'vec2',
  27229. 'vec2<i32>': 'ivec2',
  27230. 'vec2<u32>': 'uvec2',
  27231. 'vec2<bool>': 'bvec2',
  27232. 'vec2f': 'vec2',
  27233. 'vec2i': 'ivec2',
  27234. 'vec2u': 'uvec2',
  27235. 'vec2b': 'bvec2',
  27236. 'vec3<f32>': 'vec3',
  27237. 'vec3<i32>': 'ivec3',
  27238. 'vec3<u32>': 'uvec3',
  27239. 'vec3<bool>': 'bvec3',
  27240. 'vec3f': 'vec3',
  27241. 'vec3i': 'ivec3',
  27242. 'vec3u': 'uvec3',
  27243. 'vec3b': 'bvec3',
  27244. 'vec4<f32>': 'vec4',
  27245. 'vec4<i32>': 'ivec4',
  27246. 'vec4<u32>': 'uvec4',
  27247. 'vec4<bool>': 'bvec4',
  27248. 'vec4f': 'vec4',
  27249. 'vec4i': 'ivec4',
  27250. 'vec4u': 'uvec4',
  27251. 'vec4b': 'bvec4',
  27252. 'mat2x2<f32>': 'mat2',
  27253. 'mat2x2f': 'mat2',
  27254. 'mat3x3<f32>': 'mat3',
  27255. 'mat3x3f': 'mat3',
  27256. 'mat4x4<f32>': 'mat4',
  27257. 'mat4x4f': 'mat4',
  27258. 'sampler': 'sampler',
  27259. 'texture_1d': 'texture',
  27260. 'texture_2d': 'texture',
  27261. 'texture_2d_array': 'texture',
  27262. 'texture_multisampled_2d': 'cubeTexture',
  27263. 'texture_depth_2d': 'depthTexture',
  27264. 'texture_3d': 'texture3D',
  27265. 'texture_cube': 'cubeTexture',
  27266. 'texture_cube_array': 'cubeTexture',
  27267. 'texture_storage_1d': 'storageTexture',
  27268. 'texture_storage_2d': 'storageTexture',
  27269. 'texture_storage_2d_array': 'storageTexture',
  27270. 'texture_storage_3d': 'storageTexture'
  27271. };
  27272. const parse = ( source ) => {
  27273. source = source.trim();
  27274. const declaration = source.match( declarationRegexp );
  27275. if ( declaration !== null && declaration.length === 4 ) {
  27276. const inputsCode = declaration[ 2 ];
  27277. const propsMatches = [];
  27278. let match = null;
  27279. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  27280. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  27281. }
  27282. // Process matches to correctly pair names and types
  27283. const inputs = [];
  27284. for ( let i = 0; i < propsMatches.length; i ++ ) {
  27285. const { name, type } = propsMatches[ i ];
  27286. let resolvedType = type;
  27287. if ( resolvedType.startsWith( 'ptr' ) ) {
  27288. resolvedType = 'pointer';
  27289. } else {
  27290. if ( resolvedType.startsWith( 'texture' ) ) {
  27291. resolvedType = type.split( '<' )[ 0 ];
  27292. }
  27293. resolvedType = wgslTypeLib$1[ resolvedType ];
  27294. }
  27295. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  27296. }
  27297. const blockCode = source.substring( declaration[ 0 ].length );
  27298. const outputType = declaration[ 3 ] || 'void';
  27299. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  27300. const type = wgslTypeLib$1[ outputType ] || outputType;
  27301. return {
  27302. type,
  27303. inputs,
  27304. name,
  27305. inputsCode,
  27306. blockCode,
  27307. outputType
  27308. };
  27309. } else {
  27310. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  27311. }
  27312. };
  27313. /**
  27314. * This class represents a WSL node function.
  27315. *
  27316. * @augments NodeFunction
  27317. */
  27318. class WGSLNodeFunction extends NodeFunction {
  27319. /**
  27320. * Constructs a new WGSL node function.
  27321. *
  27322. * @param {String} source - The WGSL source.
  27323. */
  27324. constructor( source ) {
  27325. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  27326. super( type, inputs, name );
  27327. this.inputsCode = inputsCode;
  27328. this.blockCode = blockCode;
  27329. this.outputType = outputType;
  27330. }
  27331. /**
  27332. * This method returns the WGSL code of the node function.
  27333. *
  27334. * @param {String} [name=this.name] - The function's name.
  27335. * @return {String} The shader code.
  27336. */
  27337. getCode( name = this.name ) {
  27338. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  27339. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  27340. }
  27341. }
  27342. /**
  27343. * A WGSL node parser.
  27344. *
  27345. * @augments NodeParser
  27346. */
  27347. class WGSLNodeParser extends NodeParser {
  27348. /**
  27349. * The method parses the given WGSL code an returns a node function.
  27350. *
  27351. * @param {String} source - The WGSL code.
  27352. * @return {WGSLNodeFunction} A node function.
  27353. */
  27354. parseFunction( source ) {
  27355. return new WGSLNodeFunction( source );
  27356. }
  27357. }
  27358. // GPUShaderStage is not defined in browsers not supporting WebGPU
  27359. const GPUShaderStage = ( typeof self !== 'undefined' ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  27360. const accessNames = {
  27361. [ NodeAccess.READ_ONLY ]: 'read',
  27362. [ NodeAccess.WRITE_ONLY ]: 'write',
  27363. [ NodeAccess.READ_WRITE ]: 'read_write'
  27364. };
  27365. const wrapNames = {
  27366. [ RepeatWrapping ]: 'repeat',
  27367. [ ClampToEdgeWrapping ]: 'clamp',
  27368. [ MirroredRepeatWrapping ]: 'mirror'
  27369. };
  27370. const gpuShaderStageLib = {
  27371. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  27372. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  27373. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  27374. };
  27375. const supports = {
  27376. instance: true,
  27377. swizzleAssign: false,
  27378. storageBuffer: true
  27379. };
  27380. const wgslFnOpLib = {
  27381. '^^': 'tsl_xor'
  27382. };
  27383. const wgslTypeLib = {
  27384. float: 'f32',
  27385. int: 'i32',
  27386. uint: 'u32',
  27387. bool: 'bool',
  27388. color: 'vec3<f32>',
  27389. vec2: 'vec2<f32>',
  27390. ivec2: 'vec2<i32>',
  27391. uvec2: 'vec2<u32>',
  27392. bvec2: 'vec2<bool>',
  27393. vec3: 'vec3<f32>',
  27394. ivec3: 'vec3<i32>',
  27395. uvec3: 'vec3<u32>',
  27396. bvec3: 'vec3<bool>',
  27397. vec4: 'vec4<f32>',
  27398. ivec4: 'vec4<i32>',
  27399. uvec4: 'vec4<u32>',
  27400. bvec4: 'vec4<bool>',
  27401. mat2: 'mat2x2<f32>',
  27402. mat3: 'mat3x3<f32>',
  27403. mat4: 'mat4x4<f32>'
  27404. };
  27405. const wgslCodeCache = {};
  27406. const wgslPolyfill = {
  27407. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  27408. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  27409. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  27410. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  27411. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  27412. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  27413. 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 ); }' ),
  27414. 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 ); }' ),
  27415. 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 ); }' ),
  27416. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  27417. 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 ); }' ),
  27418. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  27419. biquadraticTexture: new CodeNode( /* wgsl */`
  27420. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  27421. let res = vec2f( iRes );
  27422. let uvScaled = coord * res;
  27423. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  27424. // https://www.shadertoy.com/view/WtyXRy
  27425. let uv = uvWrapping - 0.5;
  27426. let iuv = floor( uv );
  27427. let f = fract( uv );
  27428. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  27429. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  27430. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  27431. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  27432. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  27433. }
  27434. ` )
  27435. };
  27436. const wgslMethods = {
  27437. dFdx: 'dpdx',
  27438. dFdy: '- dpdy',
  27439. mod_float: 'tsl_mod_float',
  27440. mod_vec2: 'tsl_mod_vec2',
  27441. mod_vec3: 'tsl_mod_vec3',
  27442. mod_vec4: 'tsl_mod_vec4',
  27443. equals_bool: 'tsl_equals_bool',
  27444. equals_bvec2: 'tsl_equals_bvec2',
  27445. equals_bvec3: 'tsl_equals_bvec3',
  27446. equals_bvec4: 'tsl_equals_bvec4',
  27447. inversesqrt: 'inverseSqrt',
  27448. bitcast: 'bitcast<f32>'
  27449. };
  27450. // WebGPU issue: does not support pow() with negative base on Windows
  27451. if ( typeof navigator !== 'undefined' && /Windows/g.test( navigator.userAgent ) ) {
  27452. 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 ); }' );
  27453. 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 ] );
  27454. 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 ] );
  27455. 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 ] );
  27456. wgslMethods.pow_float = 'tsl_pow_float';
  27457. wgslMethods.pow_vec2 = 'tsl_pow_vec2';
  27458. wgslMethods.pow_vec3 = 'tsl_pow_vec3';
  27459. wgslMethods.pow_vec4 = 'tsl_pow_vec4';
  27460. }
  27461. //
  27462. let diagnostics = '';
  27463. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  27464. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  27465. }
  27466. //
  27467. class WGSLNodeBuilder extends NodeBuilder {
  27468. constructor( object, renderer ) {
  27469. super( object, renderer, new WGSLNodeParser() );
  27470. this.uniformGroups = {};
  27471. this.builtins = {};
  27472. this.directives = {};
  27473. this.scopedArrays = new Map();
  27474. }
  27475. needsToWorkingColorSpace( texture ) {
  27476. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  27477. }
  27478. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  27479. if ( shaderStage === 'fragment' ) {
  27480. if ( depthSnippet ) {
  27481. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  27482. } else {
  27483. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  27484. }
  27485. } else if ( this.isFilteredTexture( texture ) ) {
  27486. return this.generateFilteredTexture( texture, textureProperty, uvSnippet );
  27487. } else {
  27488. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0' );
  27489. }
  27490. }
  27491. _generateVideoSample( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  27492. if ( shaderStage === 'fragment' ) {
  27493. return `textureSampleBaseClampToEdge( ${ textureProperty }, ${ textureProperty }_sampler, vec2<f32>( ${ uvSnippet }.x, 1.0 - ${ uvSnippet }.y ) )`;
  27494. } else {
  27495. console.error( `WebGPURenderer: THREE.VideoTexture does not support ${ shaderStage } shader.` );
  27496. }
  27497. }
  27498. _generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  27499. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( texture ) === false ) {
  27500. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  27501. } else if ( this.isFilteredTexture( texture ) ) {
  27502. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  27503. } else {
  27504. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet );
  27505. }
  27506. }
  27507. generateWrapFunction( texture ) {
  27508. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }T`;
  27509. let nodeCode = wgslCodeCache[ functionName ];
  27510. if ( nodeCode === undefined ) {
  27511. const includes = [];
  27512. let code = `fn ${ functionName }( coord : vec2f ) -> vec2f {\n\n\treturn vec2f(\n`;
  27513. const addWrapSnippet = ( wrap, axis ) => {
  27514. if ( wrap === RepeatWrapping ) {
  27515. includes.push( wgslPolyfill.repeatWrapping_float );
  27516. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  27517. } else if ( wrap === ClampToEdgeWrapping ) {
  27518. includes.push( wgslPolyfill.clampWrapping_float );
  27519. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  27520. } else if ( wrap === MirroredRepeatWrapping ) {
  27521. includes.push( wgslPolyfill.mirrorWrapping_float );
  27522. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  27523. } else {
  27524. code += `\t\tcoord.${ axis }`;
  27525. console.warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  27526. }
  27527. };
  27528. addWrapSnippet( texture.wrapS, 'x' );
  27529. code += ',\n';
  27530. addWrapSnippet( texture.wrapT, 'y' );
  27531. code += '\n\t);\n\n}\n';
  27532. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  27533. }
  27534. nodeCode.build( this );
  27535. return functionName;
  27536. }
  27537. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  27538. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  27539. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  27540. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  27541. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  27542. let textureDimensionsParams;
  27543. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  27544. if ( primarySamples > 1 ) {
  27545. textureDimensionsParams = textureProperty;
  27546. } else {
  27547. textureDimensionsParams = `${ textureProperty }, u32( ${ levelSnippet } )`;
  27548. }
  27549. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, 'uvec2' ) );
  27550. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  27551. }
  27552. return textureDimensionNode.build( this );
  27553. }
  27554. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0u' ) {
  27555. this._include( 'biquadraticTexture' );
  27556. const wrapFunction = this.generateWrapFunction( texture );
  27557. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  27558. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  27559. }
  27560. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet = '0u' ) {
  27561. const wrapFunction = this.generateWrapFunction( texture );
  27562. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  27563. const coordSnippet = `vec2u( ${ wrapFunction }( ${ uvSnippet } ) * vec2f( ${ textureDimension } ) )`;
  27564. return this.generateTextureLoad( texture, textureProperty, coordSnippet, depthSnippet, levelSnippet );
  27565. }
  27566. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  27567. if ( texture.isVideoTexture === true || texture.isStorageTexture === true ) {
  27568. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet } )`;
  27569. } else if ( depthSnippet ) {
  27570. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  27571. } else {
  27572. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  27573. }
  27574. }
  27575. generateTextureStore( texture, textureProperty, uvIndexSnippet, valueSnippet ) {
  27576. return `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  27577. }
  27578. isSampleCompare( texture ) {
  27579. return texture.isDepthTexture === true && texture.compareFunction !== null;
  27580. }
  27581. isUnfilterable( texture ) {
  27582. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  27583. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  27584. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  27585. this.renderer.backend.utils.getTextureSampleData( texture ).primarySamples > 1;
  27586. }
  27587. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  27588. let snippet = null;
  27589. if ( texture.isVideoTexture === true ) {
  27590. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  27591. } else if ( this.isUnfilterable( texture ) ) {
  27592. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0', shaderStage );
  27593. } else {
  27594. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  27595. }
  27596. return snippet;
  27597. }
  27598. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  27599. if ( shaderStage === 'fragment' ) {
  27600. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  27601. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  27602. } else {
  27603. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  27604. }
  27605. }
  27606. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  27607. if ( shaderStage === 'fragment' ) {
  27608. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  27609. } else {
  27610. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  27611. }
  27612. }
  27613. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  27614. let snippet = null;
  27615. if ( texture.isVideoTexture === true ) {
  27616. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  27617. } else {
  27618. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage );
  27619. }
  27620. return snippet;
  27621. }
  27622. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  27623. if ( shaderStage === 'fragment' ) {
  27624. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  27625. } else {
  27626. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  27627. }
  27628. }
  27629. getPropertyName( node, shaderStage = this.shaderStage ) {
  27630. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  27631. if ( shaderStage === 'vertex' ) {
  27632. return `varyings.${ node.name }`;
  27633. }
  27634. } else if ( node.isNodeUniform === true ) {
  27635. const name = node.name;
  27636. const type = node.type;
  27637. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  27638. return name;
  27639. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  27640. return `NodeBuffer_${ node.id }.${name}`;
  27641. } else {
  27642. return node.groupNode.name + '.' + name;
  27643. }
  27644. }
  27645. return super.getPropertyName( node );
  27646. }
  27647. getOutputStructName() {
  27648. return 'output';
  27649. }
  27650. _getUniformGroupCount( shaderStage ) {
  27651. return Object.keys( this.uniforms[ shaderStage ] ).length;
  27652. }
  27653. getFunctionOperator( op ) {
  27654. const fnOp = wgslFnOpLib[ op ];
  27655. if ( fnOp !== undefined ) {
  27656. this._include( fnOp );
  27657. return fnOp;
  27658. }
  27659. return null;
  27660. }
  27661. getNodeAccess( node, shaderStage ) {
  27662. if ( shaderStage !== 'compute' )
  27663. return NodeAccess.READ_ONLY;
  27664. return node.access;
  27665. }
  27666. getStorageAccess( node, shaderStage ) {
  27667. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  27668. }
  27669. getUniformFromNode( node, type, shaderStage, name = null ) {
  27670. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  27671. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  27672. if ( nodeData.uniformGPU === undefined ) {
  27673. let uniformGPU;
  27674. const group = node.groupNode;
  27675. const groupName = group.name;
  27676. const bindings = this.getBindGroupArray( groupName, shaderStage );
  27677. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  27678. let texture = null;
  27679. const access = this.getNodeAccess( node, shaderStage );
  27680. if ( type === 'texture' || type === 'storageTexture' ) {
  27681. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  27682. } else if ( type === 'cubeTexture' ) {
  27683. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  27684. } else if ( type === 'texture3D' ) {
  27685. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  27686. }
  27687. texture.store = node.isStorageTextureNode === true;
  27688. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  27689. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( node.value ) === false && texture.store === false ) {
  27690. const sampler = new NodeSampler( `${uniformNode.name}_sampler`, uniformNode.node, group );
  27691. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  27692. bindings.push( sampler, texture );
  27693. uniformGPU = [ sampler, texture ];
  27694. } else {
  27695. bindings.push( texture );
  27696. uniformGPU = [ texture ];
  27697. }
  27698. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  27699. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  27700. const buffer = new bufferClass( node, group );
  27701. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  27702. bindings.push( buffer );
  27703. uniformGPU = buffer;
  27704. } else {
  27705. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  27706. let uniformsGroup = uniformsStage[ groupName ];
  27707. if ( uniformsGroup === undefined ) {
  27708. uniformsGroup = new NodeUniformsGroup( groupName, group );
  27709. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  27710. uniformsStage[ groupName ] = uniformsGroup;
  27711. bindings.push( uniformsGroup );
  27712. }
  27713. uniformGPU = this.getNodeUniform( uniformNode, type );
  27714. uniformsGroup.addUniform( uniformGPU );
  27715. }
  27716. nodeData.uniformGPU = uniformGPU;
  27717. }
  27718. return uniformNode;
  27719. }
  27720. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  27721. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  27722. if ( map.has( name ) === false ) {
  27723. map.set( name, {
  27724. name,
  27725. property,
  27726. type
  27727. } );
  27728. }
  27729. return property;
  27730. }
  27731. hasBuiltin( name, shaderStage = this.shaderStage ) {
  27732. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  27733. }
  27734. getVertexIndex() {
  27735. if ( this.shaderStage === 'vertex' ) {
  27736. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  27737. }
  27738. return 'vertexIndex';
  27739. }
  27740. buildFunctionCode( shaderNode ) {
  27741. const layout = shaderNode.layout;
  27742. const flowData = this.flowShaderNode( shaderNode );
  27743. const parameters = [];
  27744. for ( const input of layout.inputs ) {
  27745. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  27746. }
  27747. //
  27748. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  27749. ${ flowData.vars }
  27750. ${ flowData.code }
  27751. `;
  27752. if ( flowData.result ) {
  27753. code += `\treturn ${ flowData.result };\n`;
  27754. }
  27755. code += '\n}\n';
  27756. //
  27757. return code;
  27758. }
  27759. getInstanceIndex() {
  27760. if ( this.shaderStage === 'vertex' ) {
  27761. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  27762. }
  27763. return 'instanceIndex';
  27764. }
  27765. getInvocationLocalIndex() {
  27766. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  27767. }
  27768. getSubgroupSize() {
  27769. this.enableSubGroups();
  27770. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  27771. }
  27772. getInvocationSubgroupIndex() {
  27773. this.enableSubGroups();
  27774. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  27775. }
  27776. getSubgroupIndex() {
  27777. this.enableSubGroups();
  27778. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  27779. }
  27780. getDrawIndex() {
  27781. return null;
  27782. }
  27783. getFrontFacing() {
  27784. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  27785. }
  27786. getFragCoord() {
  27787. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  27788. }
  27789. getFragDepth() {
  27790. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  27791. }
  27792. getClipDistance() {
  27793. return 'varyings.hw_clip_distances';
  27794. }
  27795. isFlipY() {
  27796. return false;
  27797. }
  27798. enableDirective( name, shaderStage = this.shaderStage ) {
  27799. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  27800. stage.add( name );
  27801. }
  27802. getDirectives( shaderStage ) {
  27803. const snippets = [];
  27804. const directives = this.directives[ shaderStage ];
  27805. if ( directives !== undefined ) {
  27806. for ( const directive of directives ) {
  27807. snippets.push( `enable ${directive};` );
  27808. }
  27809. }
  27810. return snippets.join( '\n' );
  27811. }
  27812. enableSubGroups() {
  27813. this.enableDirective( 'subgroups' );
  27814. }
  27815. enableSubgroupsF16() {
  27816. this.enableDirective( 'subgroups-f16' );
  27817. }
  27818. enableClipDistances() {
  27819. this.enableDirective( 'clip_distances' );
  27820. }
  27821. enableShaderF16() {
  27822. this.enableDirective( 'f16' );
  27823. }
  27824. enableDualSourceBlending() {
  27825. this.enableDirective( 'dual_source_blending' );
  27826. }
  27827. enableHardwareClipping( planeCount ) {
  27828. this.enableClipDistances();
  27829. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  27830. }
  27831. getBuiltins( shaderStage ) {
  27832. const snippets = [];
  27833. const builtins = this.builtins[ shaderStage ];
  27834. if ( builtins !== undefined ) {
  27835. for ( const { name, property, type } of builtins.values() ) {
  27836. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  27837. }
  27838. }
  27839. return snippets.join( ',\n\t' );
  27840. }
  27841. getScopedArray( name, scope, bufferType, bufferCount ) {
  27842. if ( this.scopedArrays.has( name ) === false ) {
  27843. this.scopedArrays.set( name, {
  27844. name,
  27845. scope,
  27846. bufferType,
  27847. bufferCount
  27848. } );
  27849. }
  27850. return name;
  27851. }
  27852. getScopedArrays( shaderStage ) {
  27853. if ( shaderStage !== 'compute' ) {
  27854. return;
  27855. }
  27856. const snippets = [];
  27857. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  27858. const type = this.getType( bufferType );
  27859. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  27860. }
  27861. return snippets.join( '\n' );
  27862. }
  27863. getAttributes( shaderStage ) {
  27864. const snippets = [];
  27865. if ( shaderStage === 'compute' ) {
  27866. this.getBuiltin( 'global_invocation_id', 'id', 'vec3<u32>', 'attribute' );
  27867. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  27868. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  27869. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  27870. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  27871. this.enableDirective( 'subgroups', shaderStage );
  27872. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  27873. }
  27874. }
  27875. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  27876. const builtins = this.getBuiltins( 'attribute' );
  27877. if ( builtins ) snippets.push( builtins );
  27878. const attributes = this.getAttributesArray();
  27879. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  27880. const attribute = attributes[ index ];
  27881. const name = attribute.name;
  27882. const type = this.getType( attribute.type );
  27883. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  27884. }
  27885. }
  27886. return snippets.join( ',\n\t' );
  27887. }
  27888. getStructMembers( struct ) {
  27889. const snippets = [];
  27890. const members = struct.getMemberTypes();
  27891. for ( let i = 0; i < members.length; i ++ ) {
  27892. const member = members[ i ];
  27893. snippets.push( `\t@location( ${i} ) m${i} : ${ member }<f32>` );
  27894. }
  27895. const builtins = this.getBuiltins( 'output' );
  27896. if ( builtins ) snippets.push( '\t' + builtins );
  27897. return snippets.join( ',\n' );
  27898. }
  27899. getStructs( shaderStage ) {
  27900. const snippets = [];
  27901. const structs = this.structs[ shaderStage ];
  27902. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  27903. const struct = structs[ index ];
  27904. const name = struct.name;
  27905. let snippet = `\struct ${ name } {\n`;
  27906. snippet += this.getStructMembers( struct );
  27907. snippet += '\n}';
  27908. snippets.push( snippet );
  27909. snippets.push( `\nvar<private> output : ${ name };\n\n` );
  27910. }
  27911. return snippets.join( '\n\n' );
  27912. }
  27913. getVar( type, name ) {
  27914. return `var ${ name } : ${ this.getType( type ) }`;
  27915. }
  27916. getVars( shaderStage ) {
  27917. const snippets = [];
  27918. const vars = this.vars[ shaderStage ];
  27919. if ( vars !== undefined ) {
  27920. for ( const variable of vars ) {
  27921. snippets.push( `\t${ this.getVar( variable.type, variable.name ) };` );
  27922. }
  27923. }
  27924. return `\n${ snippets.join( '\n' ) }\n`;
  27925. }
  27926. getVaryings( shaderStage ) {
  27927. const snippets = [];
  27928. if ( shaderStage === 'vertex' ) {
  27929. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  27930. }
  27931. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  27932. const varyings = this.varyings;
  27933. const vars = this.vars[ shaderStage ];
  27934. for ( let index = 0; index < varyings.length; index ++ ) {
  27935. const varying = varyings[ index ];
  27936. if ( varying.needsInterpolation ) {
  27937. let attributesSnippet = `@location( ${index} )`;
  27938. if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  27939. attributesSnippet += ' @interpolate( flat )';
  27940. }
  27941. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  27942. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  27943. vars.push( varying );
  27944. }
  27945. }
  27946. }
  27947. const builtins = this.getBuiltins( shaderStage );
  27948. if ( builtins ) snippets.push( builtins );
  27949. const code = snippets.join( ',\n\t' );
  27950. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  27951. }
  27952. getUniforms( shaderStage ) {
  27953. const uniforms = this.uniforms[ shaderStage ];
  27954. const bindingSnippets = [];
  27955. const bufferSnippets = [];
  27956. const structSnippets = [];
  27957. const uniformGroups = {};
  27958. for ( const uniform of uniforms ) {
  27959. const groupName = uniform.groupNode.name;
  27960. const uniformIndexes = this.bindingsIndexes[ groupName ];
  27961. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  27962. const texture = uniform.node.value;
  27963. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  27964. if ( this.isSampleCompare( texture ) ) {
  27965. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  27966. } else {
  27967. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  27968. }
  27969. }
  27970. let textureType;
  27971. let multisampled = '';
  27972. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  27973. if ( primarySamples > 1 ) {
  27974. multisampled = '_multisampled';
  27975. }
  27976. if ( texture.isCubeTexture === true ) {
  27977. textureType = 'texture_cube<f32>';
  27978. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  27979. textureType = 'texture_2d_array<f32>';
  27980. } else if ( texture.isDepthTexture === true ) {
  27981. textureType = `texture_depth${multisampled}_2d`;
  27982. } else if ( texture.isVideoTexture === true ) {
  27983. textureType = 'texture_external';
  27984. } else if ( texture.isData3DTexture === true ) {
  27985. textureType = 'texture_3d<f32>';
  27986. } else if ( uniform.node.isStorageTextureNode === true ) {
  27987. const format = getFormat( texture );
  27988. const access = this.getStorageAccess( uniform.node, shaderStage );
  27989. textureType = `texture_storage_2d<${ format }, ${ access }>`;
  27990. } else {
  27991. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  27992. textureType = `texture${multisampled}_2d<${ componentPrefix }32>`;
  27993. }
  27994. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  27995. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  27996. const bufferNode = uniform.node;
  27997. const bufferType = this.getType( bufferNode.bufferType );
  27998. const bufferCount = bufferNode.bufferCount;
  27999. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  28000. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${bufferType}>` : `${bufferType}`;
  28001. const bufferSnippet = `\t${ uniform.name } : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >\n`;
  28002. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  28003. bufferSnippets.push( this._getWGSLStructBinding( 'NodeBuffer_' + bufferNode.id, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  28004. } else {
  28005. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  28006. const groupName = uniform.groupNode.name;
  28007. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  28008. index: uniformIndexes.binding ++,
  28009. id: uniformIndexes.group,
  28010. snippets: []
  28011. } );
  28012. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  28013. }
  28014. }
  28015. for ( const name in uniformGroups ) {
  28016. const group = uniformGroups[ name ];
  28017. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  28018. }
  28019. let code = bindingSnippets.join( '\n' );
  28020. code += bufferSnippets.join( '\n' );
  28021. code += structSnippets.join( '\n' );
  28022. return code;
  28023. }
  28024. buildCode() {
  28025. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  28026. this.sortBindingGroups();
  28027. for ( const shaderStage in shadersData ) {
  28028. const stageData = shadersData[ shaderStage ];
  28029. stageData.uniforms = this.getUniforms( shaderStage );
  28030. stageData.attributes = this.getAttributes( shaderStage );
  28031. stageData.varyings = this.getVaryings( shaderStage );
  28032. stageData.structs = this.getStructs( shaderStage );
  28033. stageData.vars = this.getVars( shaderStage );
  28034. stageData.codes = this.getCodes( shaderStage );
  28035. stageData.directives = this.getDirectives( shaderStage );
  28036. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  28037. //
  28038. let flow = '// code\n\n';
  28039. flow += this.flowCode[ shaderStage ];
  28040. const flowNodes = this.flowNodes[ shaderStage ];
  28041. const mainNode = flowNodes[ flowNodes.length - 1 ];
  28042. const outputNode = mainNode.outputNode;
  28043. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  28044. for ( const node of flowNodes ) {
  28045. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  28046. const slotName = node.name;
  28047. if ( slotName ) {
  28048. if ( flow.length > 0 ) flow += '\n';
  28049. flow += `\t// flow -> ${ slotName }\n\t`;
  28050. }
  28051. flow += `${ flowSlotData.code }\n\t`;
  28052. if ( node === mainNode && shaderStage !== 'compute' ) {
  28053. flow += '// result\n\n\t';
  28054. if ( shaderStage === 'vertex' ) {
  28055. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  28056. } else if ( shaderStage === 'fragment' ) {
  28057. if ( isOutputStruct ) {
  28058. stageData.returnType = outputNode.nodeType;
  28059. flow += `return ${ flowSlotData.result };`;
  28060. } else {
  28061. let structSnippet = '\t@location(0) color: vec4<f32>';
  28062. const builtins = this.getBuiltins( 'output' );
  28063. if ( builtins ) structSnippet += ',\n\t' + builtins;
  28064. stageData.returnType = 'OutputStruct';
  28065. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  28066. stageData.structs += '\nvar<private> output : OutputStruct;\n\n';
  28067. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  28068. }
  28069. }
  28070. }
  28071. }
  28072. stageData.flow = flow;
  28073. }
  28074. if ( this.material !== null ) {
  28075. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  28076. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  28077. } else {
  28078. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  28079. }
  28080. }
  28081. getMethod( method, output = null ) {
  28082. let wgslMethod;
  28083. if ( output !== null ) {
  28084. wgslMethod = this._getWGSLMethod( method + '_' + output );
  28085. }
  28086. if ( wgslMethod === undefined ) {
  28087. wgslMethod = this._getWGSLMethod( method );
  28088. }
  28089. return wgslMethod || method;
  28090. }
  28091. getType( type ) {
  28092. return wgslTypeLib[ type ] || type;
  28093. }
  28094. isAvailable( name ) {
  28095. let result = supports[ name ];
  28096. if ( result === undefined ) {
  28097. if ( name === 'float32Filterable' ) {
  28098. result = this.renderer.hasFeature( 'float32-filterable' );
  28099. } else if ( name === 'clipDistance' ) {
  28100. result = this.renderer.hasFeature( 'clip-distances' );
  28101. }
  28102. supports[ name ] = result;
  28103. }
  28104. return result;
  28105. }
  28106. _getWGSLMethod( method ) {
  28107. if ( wgslPolyfill[ method ] !== undefined ) {
  28108. this._include( method );
  28109. }
  28110. return wgslMethods[ method ];
  28111. }
  28112. _include( name ) {
  28113. const codeNode = wgslPolyfill[ name ];
  28114. codeNode.build( this );
  28115. if ( this.currentFunctionNode !== null ) {
  28116. this.currentFunctionNode.includes.push( codeNode );
  28117. }
  28118. return codeNode;
  28119. }
  28120. _getWGSLVertexCode( shaderData ) {
  28121. return `${ this.getSignature() }
  28122. // directives
  28123. ${shaderData.directives}
  28124. // uniforms
  28125. ${shaderData.uniforms}
  28126. // varyings
  28127. ${shaderData.varyings}
  28128. var<private> varyings : VaryingsStruct;
  28129. // codes
  28130. ${shaderData.codes}
  28131. @vertex
  28132. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  28133. // vars
  28134. ${shaderData.vars}
  28135. // flow
  28136. ${shaderData.flow}
  28137. return varyings;
  28138. }
  28139. `;
  28140. }
  28141. _getWGSLFragmentCode( shaderData ) {
  28142. return `${ this.getSignature() }
  28143. // global
  28144. ${ diagnostics }
  28145. // uniforms
  28146. ${shaderData.uniforms}
  28147. // structs
  28148. ${shaderData.structs}
  28149. // codes
  28150. ${shaderData.codes}
  28151. @fragment
  28152. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  28153. // vars
  28154. ${shaderData.vars}
  28155. // flow
  28156. ${shaderData.flow}
  28157. }
  28158. `;
  28159. }
  28160. _getWGSLComputeCode( shaderData, workgroupSize ) {
  28161. return `${ this.getSignature() }
  28162. // directives
  28163. ${shaderData.directives}
  28164. // system
  28165. var<private> instanceIndex : u32;
  28166. // locals
  28167. ${shaderData.scopedArrays}
  28168. // uniforms
  28169. ${shaderData.uniforms}
  28170. // codes
  28171. ${shaderData.codes}
  28172. @compute @workgroup_size( ${workgroupSize} )
  28173. fn main( ${shaderData.attributes} ) {
  28174. // system
  28175. instanceIndex = id.x + id.y * numWorkgroups.x * u32(${workgroupSize}) + id.z * numWorkgroups.x * numWorkgroups.y * u32(${workgroupSize});
  28176. // vars
  28177. ${shaderData.vars}
  28178. // flow
  28179. ${shaderData.flow}
  28180. }
  28181. `;
  28182. }
  28183. _getWGSLStruct( name, vars ) {
  28184. return `
  28185. struct ${name} {
  28186. ${vars}
  28187. };`;
  28188. }
  28189. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  28190. const structName = name + 'Struct';
  28191. const structSnippet = this._getWGSLStruct( structName, vars );
  28192. return `${structSnippet}
  28193. @binding( ${binding} ) @group( ${group} )
  28194. var<${access}> ${name} : ${structName};`;
  28195. }
  28196. }
  28197. class WebGPUUtils {
  28198. constructor( backend ) {
  28199. this.backend = backend;
  28200. }
  28201. getCurrentDepthStencilFormat( renderContext ) {
  28202. let format;
  28203. if ( renderContext.depthTexture !== null ) {
  28204. format = this.getTextureFormatGPU( renderContext.depthTexture );
  28205. } else if ( renderContext.depth && renderContext.stencil ) {
  28206. format = GPUTextureFormat.Depth24PlusStencil8;
  28207. } else if ( renderContext.depth ) {
  28208. format = GPUTextureFormat.Depth24Plus;
  28209. }
  28210. return format;
  28211. }
  28212. getTextureFormatGPU( texture ) {
  28213. return this.backend.get( texture ).format;
  28214. }
  28215. getTextureSampleData( texture ) {
  28216. let samples;
  28217. if ( texture.isFramebufferTexture ) {
  28218. samples = 1;
  28219. } else if ( texture.isDepthTexture && ! texture.renderTarget ) {
  28220. const renderer = this.backend.renderer;
  28221. const renderTarget = renderer.getRenderTarget();
  28222. samples = renderTarget ? renderTarget.samples : renderer.samples;
  28223. } else if ( texture.renderTarget ) {
  28224. samples = texture.renderTarget.samples;
  28225. }
  28226. samples = samples || 1;
  28227. const isMSAA = samples > 1 && texture.renderTarget !== null && ( texture.isDepthTexture !== true && texture.isFramebufferTexture !== true );
  28228. const primarySamples = isMSAA ? 1 : samples;
  28229. return { samples, primarySamples, isMSAA };
  28230. }
  28231. getCurrentColorFormat( renderContext ) {
  28232. let format;
  28233. if ( renderContext.textures !== null ) {
  28234. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  28235. } else {
  28236. format = this.getPreferredCanvasFormat(); // default context format
  28237. }
  28238. return format;
  28239. }
  28240. getCurrentColorSpace( renderContext ) {
  28241. if ( renderContext.textures !== null ) {
  28242. return renderContext.textures[ 0 ].colorSpace;
  28243. }
  28244. return this.backend.renderer.outputColorSpace;
  28245. }
  28246. getPrimitiveTopology( object, material ) {
  28247. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  28248. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  28249. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  28250. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  28251. }
  28252. getSampleCount( sampleCount ) {
  28253. let count = 1;
  28254. if ( sampleCount > 1 ) {
  28255. // WebGPU only supports power-of-two sample counts and 2 is not a valid value
  28256. count = Math.pow( 2, Math.floor( Math.log2( sampleCount ) ) );
  28257. if ( count === 2 ) {
  28258. count = 4;
  28259. }
  28260. }
  28261. return count;
  28262. }
  28263. getSampleCountRenderContext( renderContext ) {
  28264. if ( renderContext.textures !== null ) {
  28265. return this.getSampleCount( renderContext.sampleCount );
  28266. }
  28267. return this.getSampleCount( this.backend.renderer.samples );
  28268. }
  28269. getPreferredCanvasFormat() {
  28270. // TODO: Remove this check when Quest 34.5 is out
  28271. // https://github.com/mrdoob/three.js/pull/29221/files#r1731833949
  28272. if ( navigator.userAgent.includes( 'Quest' ) ) {
  28273. return GPUTextureFormat.BGRA8Unorm;
  28274. } else {
  28275. return navigator.gpu.getPreferredCanvasFormat();
  28276. }
  28277. }
  28278. }
  28279. const typedArraysToVertexFormatPrefix = new Map( [
  28280. [ Int8Array, [ 'sint8', 'snorm8' ]],
  28281. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  28282. [ Int16Array, [ 'sint16', 'snorm16' ]],
  28283. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  28284. [ Int32Array, [ 'sint32', 'snorm32' ]],
  28285. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  28286. [ Float32Array, [ 'float32', ]],
  28287. ] );
  28288. const typedAttributeToVertexFormatPrefix = new Map( [
  28289. [ Float16BufferAttribute, [ 'float16', ]],
  28290. ] );
  28291. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  28292. [ Int32Array, 'sint32' ],
  28293. [ Int16Array, 'sint32' ], // patch for INT16
  28294. [ Uint32Array, 'uint32' ],
  28295. [ Uint16Array, 'uint32' ], // patch for UINT16
  28296. [ Float32Array, 'float32' ]
  28297. ] );
  28298. class WebGPUAttributeUtils {
  28299. constructor( backend ) {
  28300. this.backend = backend;
  28301. }
  28302. createAttribute( attribute, usage ) {
  28303. const bufferAttribute = this._getBufferAttribute( attribute );
  28304. const backend = this.backend;
  28305. const bufferData = backend.get( bufferAttribute );
  28306. let buffer = bufferData.buffer;
  28307. if ( buffer === undefined ) {
  28308. const device = backend.device;
  28309. let array = bufferAttribute.array;
  28310. // patch for INT16 and UINT16
  28311. if ( attribute.normalized === false && ( array.constructor === Int16Array || array.constructor === Uint16Array ) ) {
  28312. const tempArray = new Uint32Array( array.length );
  28313. for ( let i = 0; i < array.length; i ++ ) {
  28314. tempArray[ i ] = array[ i ];
  28315. }
  28316. array = tempArray;
  28317. }
  28318. bufferAttribute.array = array;
  28319. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  28320. array = new array.constructor( bufferAttribute.count * 4 );
  28321. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  28322. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  28323. }
  28324. // Update BufferAttribute
  28325. bufferAttribute.itemSize = 4;
  28326. bufferAttribute.array = array;
  28327. }
  28328. const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441
  28329. buffer = device.createBuffer( {
  28330. label: bufferAttribute.name,
  28331. size: size,
  28332. usage: usage,
  28333. mappedAtCreation: true
  28334. } );
  28335. new array.constructor( buffer.getMappedRange() ).set( array );
  28336. buffer.unmap();
  28337. bufferData.buffer = buffer;
  28338. }
  28339. }
  28340. updateAttribute( attribute ) {
  28341. const bufferAttribute = this._getBufferAttribute( attribute );
  28342. const backend = this.backend;
  28343. const device = backend.device;
  28344. const buffer = backend.get( bufferAttribute ).buffer;
  28345. const array = bufferAttribute.array;
  28346. const isTypedArray = this._isTypedArray( array );
  28347. const updateRanges = bufferAttribute.updateRanges;
  28348. if ( updateRanges.length === 0 ) {
  28349. // Not using update ranges
  28350. device.queue.writeBuffer(
  28351. buffer,
  28352. 0,
  28353. array,
  28354. 0
  28355. );
  28356. } else {
  28357. const byteOffsetFactor = isTypedArray ? 1 : array.BYTES_PER_ELEMENT;
  28358. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  28359. const range = updateRanges[ i ];
  28360. const dataOffset = range.start * byteOffsetFactor;
  28361. const size = range.count * byteOffsetFactor;
  28362. device.queue.writeBuffer(
  28363. buffer,
  28364. 0,
  28365. array,
  28366. dataOffset,
  28367. size
  28368. );
  28369. }
  28370. bufferAttribute.clearUpdateRanges();
  28371. }
  28372. }
  28373. createShaderVertexBuffers( renderObject ) {
  28374. const attributes = renderObject.getAttributes();
  28375. const vertexBuffers = new Map();
  28376. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  28377. const geometryAttribute = attributes[ slot ];
  28378. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  28379. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  28380. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  28381. if ( vertexBufferLayout === undefined ) {
  28382. let arrayStride, stepMode;
  28383. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  28384. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  28385. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  28386. } else {
  28387. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  28388. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  28389. }
  28390. // patch for INT16 and UINT16
  28391. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  28392. arrayStride = 4;
  28393. }
  28394. vertexBufferLayout = {
  28395. arrayStride,
  28396. attributes: [],
  28397. stepMode
  28398. };
  28399. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  28400. }
  28401. const format = this._getVertexFormat( geometryAttribute );
  28402. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  28403. vertexBufferLayout.attributes.push( {
  28404. shaderLocation: slot,
  28405. offset,
  28406. format
  28407. } );
  28408. }
  28409. return Array.from( vertexBuffers.values() );
  28410. }
  28411. destroyAttribute( attribute ) {
  28412. const backend = this.backend;
  28413. const data = backend.get( this._getBufferAttribute( attribute ) );
  28414. data.buffer.destroy();
  28415. backend.delete( attribute );
  28416. }
  28417. async getArrayBufferAsync( attribute ) {
  28418. const backend = this.backend;
  28419. const device = backend.device;
  28420. const data = backend.get( this._getBufferAttribute( attribute ) );
  28421. const bufferGPU = data.buffer;
  28422. const size = bufferGPU.size;
  28423. const readBufferGPU = device.createBuffer( {
  28424. label: attribute.name,
  28425. size,
  28426. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  28427. } );
  28428. const cmdEncoder = device.createCommandEncoder( {} );
  28429. cmdEncoder.copyBufferToBuffer(
  28430. bufferGPU,
  28431. 0,
  28432. readBufferGPU,
  28433. 0,
  28434. size
  28435. );
  28436. readBufferGPU.unmap();
  28437. const gpuCommands = cmdEncoder.finish();
  28438. device.queue.submit( [ gpuCommands ] );
  28439. await readBufferGPU.mapAsync( GPUMapMode.READ );
  28440. const arrayBuffer = readBufferGPU.getMappedRange();
  28441. return arrayBuffer;
  28442. }
  28443. _getVertexFormat( geometryAttribute ) {
  28444. const { itemSize, normalized } = geometryAttribute;
  28445. const ArrayType = geometryAttribute.array.constructor;
  28446. const AttributeType = geometryAttribute.constructor;
  28447. let format;
  28448. if ( itemSize == 1 ) {
  28449. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  28450. } else {
  28451. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  28452. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  28453. if ( prefix ) {
  28454. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  28455. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  28456. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  28457. if ( paddedItemSize % 1 ) {
  28458. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  28459. }
  28460. format = `${prefix}x${paddedItemSize}`;
  28461. }
  28462. }
  28463. if ( ! format ) {
  28464. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  28465. }
  28466. return format;
  28467. }
  28468. _isTypedArray( array ) {
  28469. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  28470. }
  28471. _getBufferAttribute( attribute ) {
  28472. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  28473. return attribute;
  28474. }
  28475. }
  28476. class WebGPUBindingUtils {
  28477. constructor( backend ) {
  28478. this.backend = backend;
  28479. this.bindGroupLayoutCache = new WeakMap();
  28480. }
  28481. createBindingsLayout( bindGroup ) {
  28482. const backend = this.backend;
  28483. const device = backend.device;
  28484. const entries = [];
  28485. let index = 0;
  28486. for ( const binding of bindGroup.bindings ) {
  28487. const bindingGPU = {
  28488. binding: index ++,
  28489. visibility: binding.visibility
  28490. };
  28491. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  28492. const buffer = {}; // GPUBufferBindingLayout
  28493. if ( binding.isStorageBuffer ) {
  28494. if ( binding.visibility & 4 ) {
  28495. // compute
  28496. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  28497. buffer.type = GPUBufferBindingType.Storage;
  28498. } else {
  28499. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  28500. }
  28501. } else {
  28502. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  28503. }
  28504. }
  28505. bindingGPU.buffer = buffer;
  28506. } else if ( binding.isSampler ) {
  28507. const sampler = {}; // GPUSamplerBindingLayout
  28508. if ( binding.texture.isDepthTexture ) {
  28509. if ( binding.texture.compareFunction !== null ) {
  28510. sampler.type = 'comparison';
  28511. }
  28512. }
  28513. bindingGPU.sampler = sampler;
  28514. } else if ( binding.isSampledTexture && binding.texture.isVideoTexture ) {
  28515. bindingGPU.externalTexture = {}; // GPUExternalTextureBindingLayout
  28516. } else if ( binding.isSampledTexture && binding.store ) {
  28517. const storageTexture = {}; // GPUStorageTextureBindingLayout
  28518. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  28519. const access = binding.access;
  28520. if ( access === NodeAccess.READ_WRITE ) {
  28521. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  28522. } else if ( access === NodeAccess.WRITE_ONLY ) {
  28523. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  28524. } else {
  28525. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  28526. }
  28527. bindingGPU.storageTexture = storageTexture;
  28528. } else if ( binding.isSampledTexture ) {
  28529. const texture = {}; // GPUTextureBindingLayout
  28530. const { primarySamples } = backend.utils.getTextureSampleData( binding.texture );
  28531. if ( primarySamples > 1 ) {
  28532. texture.multisampled = true;
  28533. if ( ! binding.texture.isDepthTexture ) {
  28534. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  28535. }
  28536. }
  28537. if ( binding.texture.isDepthTexture ) {
  28538. texture.sampleType = GPUTextureSampleType.Depth;
  28539. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  28540. const type = binding.texture.type;
  28541. if ( type === IntType ) {
  28542. texture.sampleType = GPUTextureSampleType.SInt;
  28543. } else if ( type === UnsignedIntType ) {
  28544. texture.sampleType = GPUTextureSampleType.UInt;
  28545. } else if ( type === FloatType ) {
  28546. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  28547. texture.sampleType = GPUTextureSampleType.Float;
  28548. } else {
  28549. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  28550. }
  28551. }
  28552. }
  28553. if ( binding.isSampledCubeTexture ) {
  28554. texture.viewDimension = GPUTextureViewDimension.Cube;
  28555. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  28556. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  28557. } else if ( binding.isSampledTexture3D ) {
  28558. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  28559. }
  28560. bindingGPU.texture = texture;
  28561. } else {
  28562. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  28563. }
  28564. entries.push( bindingGPU );
  28565. }
  28566. return device.createBindGroupLayout( { entries } );
  28567. }
  28568. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  28569. const { backend, bindGroupLayoutCache } = this;
  28570. const bindingsData = backend.get( bindGroup );
  28571. // setup (static) binding layout and (dynamic) binding group
  28572. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  28573. if ( bindLayoutGPU === undefined ) {
  28574. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  28575. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  28576. }
  28577. let bindGroupGPU;
  28578. if ( cacheIndex > 0 ) {
  28579. if ( bindingsData.groups === undefined ) {
  28580. bindingsData.groups = [];
  28581. bindingsData.versions = [];
  28582. }
  28583. if ( bindingsData.versions[ cacheIndex ] === version ) {
  28584. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  28585. }
  28586. }
  28587. if ( bindGroupGPU === undefined ) {
  28588. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  28589. if ( cacheIndex > 0 ) {
  28590. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  28591. bindingsData.versions[ cacheIndex ] = version;
  28592. }
  28593. }
  28594. bindingsData.group = bindGroupGPU;
  28595. bindingsData.layout = bindLayoutGPU;
  28596. }
  28597. updateBinding( binding ) {
  28598. const backend = this.backend;
  28599. const device = backend.device;
  28600. const buffer = binding.buffer;
  28601. const bufferGPU = backend.get( binding ).buffer;
  28602. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  28603. }
  28604. createBindGroup( bindGroup, layoutGPU ) {
  28605. const backend = this.backend;
  28606. const device = backend.device;
  28607. let bindingPoint = 0;
  28608. const entriesGPU = [];
  28609. for ( const binding of bindGroup.bindings ) {
  28610. if ( binding.isUniformBuffer ) {
  28611. const bindingData = backend.get( binding );
  28612. if ( bindingData.buffer === undefined ) {
  28613. const byteLength = binding.byteLength;
  28614. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  28615. const bufferGPU = device.createBuffer( {
  28616. label: 'bindingBuffer_' + binding.name,
  28617. size: byteLength,
  28618. usage: usage
  28619. } );
  28620. bindingData.buffer = bufferGPU;
  28621. }
  28622. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  28623. } else if ( binding.isStorageBuffer ) {
  28624. const bindingData = backend.get( binding );
  28625. if ( bindingData.buffer === undefined ) {
  28626. const attribute = binding.attribute;
  28627. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  28628. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  28629. bindingData.buffer = backend.get( attribute ).buffer;
  28630. }
  28631. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  28632. } else if ( binding.isSampler ) {
  28633. const textureGPU = backend.get( binding.texture );
  28634. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  28635. } else if ( binding.isSampledTexture ) {
  28636. const textureData = backend.get( binding.texture );
  28637. let resourceGPU;
  28638. if ( textureData.externalTexture !== undefined ) {
  28639. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  28640. } else {
  28641. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  28642. const propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }-${ mipLevelCount }`;
  28643. resourceGPU = textureData[ propertyName ];
  28644. if ( resourceGPU === undefined ) {
  28645. const aspectGPU = GPUTextureAspect.All;
  28646. let dimensionViewGPU;
  28647. if ( binding.isSampledCubeTexture ) {
  28648. dimensionViewGPU = GPUTextureViewDimension.Cube;
  28649. } else if ( binding.isSampledTexture3D ) {
  28650. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  28651. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  28652. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  28653. } else {
  28654. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  28655. }
  28656. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount } );
  28657. }
  28658. }
  28659. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  28660. }
  28661. bindingPoint ++;
  28662. }
  28663. return device.createBindGroup( {
  28664. label: 'bindGroup_' + bindGroup.name,
  28665. layout: layoutGPU,
  28666. entries: entriesGPU
  28667. } );
  28668. }
  28669. }
  28670. class WebGPUPipelineUtils {
  28671. constructor( backend ) {
  28672. this.backend = backend;
  28673. }
  28674. _getSampleCount( renderObjectContext ) {
  28675. return this.backend.utils.getSampleCountRenderContext( renderObjectContext );
  28676. }
  28677. createRenderPipeline( renderObject, promises ) {
  28678. const { object, material, geometry, pipeline } = renderObject;
  28679. const { vertexProgram, fragmentProgram } = pipeline;
  28680. const backend = this.backend;
  28681. const device = backend.device;
  28682. const utils = backend.utils;
  28683. const pipelineData = backend.get( pipeline );
  28684. // bind group layouts
  28685. const bindGroupLayouts = [];
  28686. for ( const bindGroup of renderObject.getBindings() ) {
  28687. const bindingsData = backend.get( bindGroup );
  28688. bindGroupLayouts.push( bindingsData.layout );
  28689. }
  28690. // vertex buffers
  28691. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  28692. // blending
  28693. let blending;
  28694. if ( material.transparent === true && material.blending !== NoBlending ) {
  28695. blending = this._getBlending( material );
  28696. }
  28697. // stencil
  28698. let stencilFront = {};
  28699. if ( material.stencilWrite === true ) {
  28700. stencilFront = {
  28701. compare: this._getStencilCompare( material ),
  28702. failOp: this._getStencilOperation( material.stencilFail ),
  28703. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  28704. passOp: this._getStencilOperation( material.stencilZPass )
  28705. };
  28706. }
  28707. const colorWriteMask = this._getColorWriteMask( material );
  28708. const targets = [];
  28709. if ( renderObject.context.textures !== null ) {
  28710. const textures = renderObject.context.textures;
  28711. for ( let i = 0; i < textures.length; i ++ ) {
  28712. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  28713. targets.push( {
  28714. format: colorFormat,
  28715. blend: blending,
  28716. writeMask: colorWriteMask
  28717. } );
  28718. }
  28719. } else {
  28720. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  28721. targets.push( {
  28722. format: colorFormat,
  28723. blend: blending,
  28724. writeMask: colorWriteMask
  28725. } );
  28726. }
  28727. const vertexModule = backend.get( vertexProgram ).module;
  28728. const fragmentModule = backend.get( fragmentProgram ).module;
  28729. const primitiveState = this._getPrimitiveState( object, geometry, material );
  28730. const depthCompare = this._getDepthCompare( material );
  28731. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  28732. const sampleCount = this._getSampleCount( renderObject.context );
  28733. const pipelineDescriptor = {
  28734. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  28735. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  28736. fragment: Object.assign( {}, fragmentModule, { targets } ),
  28737. primitive: primitiveState,
  28738. multisample: {
  28739. count: sampleCount,
  28740. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  28741. },
  28742. layout: device.createPipelineLayout( {
  28743. bindGroupLayouts
  28744. } )
  28745. };
  28746. const depthStencil = {};
  28747. const renderDepth = renderObject.context.depth;
  28748. const renderStencil = renderObject.context.stencil;
  28749. if ( renderDepth === true || renderStencil === true ) {
  28750. if ( renderDepth === true ) {
  28751. depthStencil.format = depthStencilFormat;
  28752. depthStencil.depthWriteEnabled = material.depthWrite;
  28753. depthStencil.depthCompare = depthCompare;
  28754. }
  28755. if ( renderStencil === true ) {
  28756. depthStencil.stencilFront = stencilFront;
  28757. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  28758. depthStencil.stencilReadMask = material.stencilFuncMask;
  28759. depthStencil.stencilWriteMask = material.stencilWriteMask;
  28760. }
  28761. pipelineDescriptor.depthStencil = depthStencil;
  28762. }
  28763. if ( promises === null ) {
  28764. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  28765. } else {
  28766. const p = new Promise( ( resolve /*, reject*/ ) => {
  28767. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  28768. pipelineData.pipeline = pipeline;
  28769. resolve();
  28770. } );
  28771. } );
  28772. promises.push( p );
  28773. }
  28774. }
  28775. createBundleEncoder( renderContext ) {
  28776. const backend = this.backend;
  28777. const { utils, device } = backend;
  28778. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  28779. const colorFormat = utils.getCurrentColorFormat( renderContext );
  28780. const sampleCount = this._getSampleCount( renderContext );
  28781. const descriptor = {
  28782. label: 'renderBundleEncoder',
  28783. colorFormats: [ colorFormat ],
  28784. depthStencilFormat,
  28785. sampleCount
  28786. };
  28787. return device.createRenderBundleEncoder( descriptor );
  28788. }
  28789. createComputePipeline( pipeline, bindings ) {
  28790. const backend = this.backend;
  28791. const device = backend.device;
  28792. const computeProgram = backend.get( pipeline.computeProgram ).module;
  28793. const pipelineGPU = backend.get( pipeline );
  28794. // bind group layouts
  28795. const bindGroupLayouts = [];
  28796. for ( const bindingsGroup of bindings ) {
  28797. const bindingsData = backend.get( bindingsGroup );
  28798. bindGroupLayouts.push( bindingsData.layout );
  28799. }
  28800. pipelineGPU.pipeline = device.createComputePipeline( {
  28801. compute: computeProgram,
  28802. layout: device.createPipelineLayout( {
  28803. bindGroupLayouts
  28804. } )
  28805. } );
  28806. }
  28807. _getBlending( material ) {
  28808. let color, alpha;
  28809. const blending = material.blending;
  28810. const blendSrc = material.blendSrc;
  28811. const blendDst = material.blendDst;
  28812. const blendEquation = material.blendEquation;
  28813. if ( blending === CustomBlending ) {
  28814. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  28815. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  28816. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  28817. color = {
  28818. srcFactor: this._getBlendFactor( blendSrc ),
  28819. dstFactor: this._getBlendFactor( blendDst ),
  28820. operation: this._getBlendOperation( blendEquation )
  28821. };
  28822. alpha = {
  28823. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  28824. dstFactor: this._getBlendFactor( blendDstAlpha ),
  28825. operation: this._getBlendOperation( blendEquationAlpha )
  28826. };
  28827. } else {
  28828. const premultipliedAlpha = material.premultipliedAlpha;
  28829. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  28830. color = {
  28831. srcFactor: srcRGB,
  28832. dstFactor: dstRGB,
  28833. operation: GPUBlendOperation.Add
  28834. };
  28835. alpha = {
  28836. srcFactor: srcAlpha,
  28837. dstFactor: dstAlpha,
  28838. operation: GPUBlendOperation.Add
  28839. };
  28840. };
  28841. if ( premultipliedAlpha ) {
  28842. switch ( blending ) {
  28843. case NormalBlending:
  28844. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  28845. break;
  28846. case AdditiveBlending:
  28847. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  28848. break;
  28849. case SubtractiveBlending:
  28850. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  28851. break;
  28852. case MultiplyBlending:
  28853. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.SrcAlpha );
  28854. break;
  28855. }
  28856. } else {
  28857. switch ( blending ) {
  28858. case NormalBlending:
  28859. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  28860. break;
  28861. case AdditiveBlending:
  28862. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.SrcAlpha, GPUBlendFactor.One );
  28863. break;
  28864. case SubtractiveBlending:
  28865. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  28866. break;
  28867. case MultiplyBlending:
  28868. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.Src );
  28869. break;
  28870. }
  28871. }
  28872. }
  28873. if ( color !== undefined && alpha !== undefined ) {
  28874. return { color, alpha };
  28875. } else {
  28876. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  28877. }
  28878. }
  28879. _getBlendFactor( blend ) {
  28880. let blendFactor;
  28881. switch ( blend ) {
  28882. case ZeroFactor:
  28883. blendFactor = GPUBlendFactor.Zero;
  28884. break;
  28885. case OneFactor:
  28886. blendFactor = GPUBlendFactor.One;
  28887. break;
  28888. case SrcColorFactor:
  28889. blendFactor = GPUBlendFactor.Src;
  28890. break;
  28891. case OneMinusSrcColorFactor:
  28892. blendFactor = GPUBlendFactor.OneMinusSrc;
  28893. break;
  28894. case SrcAlphaFactor:
  28895. blendFactor = GPUBlendFactor.SrcAlpha;
  28896. break;
  28897. case OneMinusSrcAlphaFactor:
  28898. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  28899. break;
  28900. case DstColorFactor:
  28901. blendFactor = GPUBlendFactor.Dst;
  28902. break;
  28903. case OneMinusDstColorFactor:
  28904. blendFactor = GPUBlendFactor.OneMinusDstColor;
  28905. break;
  28906. case DstAlphaFactor:
  28907. blendFactor = GPUBlendFactor.DstAlpha;
  28908. break;
  28909. case OneMinusDstAlphaFactor:
  28910. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  28911. break;
  28912. case SrcAlphaSaturateFactor:
  28913. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  28914. break;
  28915. case BlendColorFactor:
  28916. blendFactor = GPUBlendFactor.Constant;
  28917. break;
  28918. case OneMinusBlendColorFactor:
  28919. blendFactor = GPUBlendFactor.OneMinusConstant;
  28920. break;
  28921. default:
  28922. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  28923. }
  28924. return blendFactor;
  28925. }
  28926. _getStencilCompare( material ) {
  28927. let stencilCompare;
  28928. const stencilFunc = material.stencilFunc;
  28929. switch ( stencilFunc ) {
  28930. case NeverStencilFunc:
  28931. stencilCompare = GPUCompareFunction.Never;
  28932. break;
  28933. case AlwaysStencilFunc:
  28934. stencilCompare = GPUCompareFunction.Always;
  28935. break;
  28936. case LessStencilFunc:
  28937. stencilCompare = GPUCompareFunction.Less;
  28938. break;
  28939. case LessEqualStencilFunc:
  28940. stencilCompare = GPUCompareFunction.LessEqual;
  28941. break;
  28942. case EqualStencilFunc:
  28943. stencilCompare = GPUCompareFunction.Equal;
  28944. break;
  28945. case GreaterEqualStencilFunc:
  28946. stencilCompare = GPUCompareFunction.GreaterEqual;
  28947. break;
  28948. case GreaterStencilFunc:
  28949. stencilCompare = GPUCompareFunction.Greater;
  28950. break;
  28951. case NotEqualStencilFunc:
  28952. stencilCompare = GPUCompareFunction.NotEqual;
  28953. break;
  28954. default:
  28955. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  28956. }
  28957. return stencilCompare;
  28958. }
  28959. _getStencilOperation( op ) {
  28960. let stencilOperation;
  28961. switch ( op ) {
  28962. case KeepStencilOp:
  28963. stencilOperation = GPUStencilOperation.Keep;
  28964. break;
  28965. case ZeroStencilOp:
  28966. stencilOperation = GPUStencilOperation.Zero;
  28967. break;
  28968. case ReplaceStencilOp:
  28969. stencilOperation = GPUStencilOperation.Replace;
  28970. break;
  28971. case InvertStencilOp:
  28972. stencilOperation = GPUStencilOperation.Invert;
  28973. break;
  28974. case IncrementStencilOp:
  28975. stencilOperation = GPUStencilOperation.IncrementClamp;
  28976. break;
  28977. case DecrementStencilOp:
  28978. stencilOperation = GPUStencilOperation.DecrementClamp;
  28979. break;
  28980. case IncrementWrapStencilOp:
  28981. stencilOperation = GPUStencilOperation.IncrementWrap;
  28982. break;
  28983. case DecrementWrapStencilOp:
  28984. stencilOperation = GPUStencilOperation.DecrementWrap;
  28985. break;
  28986. default:
  28987. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  28988. }
  28989. return stencilOperation;
  28990. }
  28991. _getBlendOperation( blendEquation ) {
  28992. let blendOperation;
  28993. switch ( blendEquation ) {
  28994. case AddEquation:
  28995. blendOperation = GPUBlendOperation.Add;
  28996. break;
  28997. case SubtractEquation:
  28998. blendOperation = GPUBlendOperation.Subtract;
  28999. break;
  29000. case ReverseSubtractEquation:
  29001. blendOperation = GPUBlendOperation.ReverseSubtract;
  29002. break;
  29003. case MinEquation:
  29004. blendOperation = GPUBlendOperation.Min;
  29005. break;
  29006. case MaxEquation:
  29007. blendOperation = GPUBlendOperation.Max;
  29008. break;
  29009. default:
  29010. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  29011. }
  29012. return blendOperation;
  29013. }
  29014. _getPrimitiveState( object, geometry, material ) {
  29015. const descriptor = {};
  29016. const utils = this.backend.utils;
  29017. descriptor.topology = utils.getPrimitiveTopology( object, material );
  29018. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  29019. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  29020. }
  29021. switch ( material.side ) {
  29022. case FrontSide:
  29023. descriptor.frontFace = GPUFrontFace.CCW;
  29024. descriptor.cullMode = GPUCullMode.Back;
  29025. break;
  29026. case BackSide:
  29027. descriptor.frontFace = GPUFrontFace.CCW;
  29028. descriptor.cullMode = GPUCullMode.Front;
  29029. break;
  29030. case DoubleSide:
  29031. descriptor.frontFace = GPUFrontFace.CCW;
  29032. descriptor.cullMode = GPUCullMode.None;
  29033. break;
  29034. default:
  29035. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  29036. break;
  29037. }
  29038. return descriptor;
  29039. }
  29040. _getColorWriteMask( material ) {
  29041. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  29042. }
  29043. _getDepthCompare( material ) {
  29044. let depthCompare;
  29045. if ( material.depthTest === false ) {
  29046. depthCompare = GPUCompareFunction.Always;
  29047. } else {
  29048. const depthFunc = material.depthFunc;
  29049. switch ( depthFunc ) {
  29050. case NeverDepth:
  29051. depthCompare = GPUCompareFunction.Never;
  29052. break;
  29053. case AlwaysDepth:
  29054. depthCompare = GPUCompareFunction.Always;
  29055. break;
  29056. case LessDepth:
  29057. depthCompare = GPUCompareFunction.Less;
  29058. break;
  29059. case LessEqualDepth:
  29060. depthCompare = GPUCompareFunction.LessEqual;
  29061. break;
  29062. case EqualDepth:
  29063. depthCompare = GPUCompareFunction.Equal;
  29064. break;
  29065. case GreaterEqualDepth:
  29066. depthCompare = GPUCompareFunction.GreaterEqual;
  29067. break;
  29068. case GreaterDepth:
  29069. depthCompare = GPUCompareFunction.Greater;
  29070. break;
  29071. case NotEqualDepth:
  29072. depthCompare = GPUCompareFunction.NotEqual;
  29073. break;
  29074. default:
  29075. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  29076. }
  29077. }
  29078. return depthCompare;
  29079. }
  29080. }
  29081. /*// debugger tools
  29082. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  29083. //*/
  29084. //
  29085. class WebGPUBackend extends Backend {
  29086. constructor( parameters = {} ) {
  29087. super( parameters );
  29088. this.isWebGPUBackend = true;
  29089. // some parameters require default values other than "undefined"
  29090. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  29091. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  29092. this.trackTimestamp = ( parameters.trackTimestamp === true );
  29093. this.device = null;
  29094. this.context = null;
  29095. this.colorBuffer = null;
  29096. this.defaultRenderPassdescriptor = null;
  29097. this.utils = new WebGPUUtils( this );
  29098. this.attributeUtils = new WebGPUAttributeUtils( this );
  29099. this.bindingUtils = new WebGPUBindingUtils( this );
  29100. this.pipelineUtils = new WebGPUPipelineUtils( this );
  29101. this.textureUtils = new WebGPUTextureUtils( this );
  29102. this.occludedResolveCache = new Map();
  29103. }
  29104. async init( renderer ) {
  29105. await super.init( renderer );
  29106. //
  29107. const parameters = this.parameters;
  29108. // create the device if it is not passed with parameters
  29109. let device;
  29110. if ( parameters.device === undefined ) {
  29111. const adapterOptions = {
  29112. powerPreference: parameters.powerPreference
  29113. };
  29114. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  29115. if ( adapter === null ) {
  29116. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  29117. }
  29118. // feature support
  29119. const features = Object.values( GPUFeatureName );
  29120. const supportedFeatures = [];
  29121. for ( const name of features ) {
  29122. if ( adapter.features.has( name ) ) {
  29123. supportedFeatures.push( name );
  29124. }
  29125. }
  29126. const deviceDescriptor = {
  29127. requiredFeatures: supportedFeatures,
  29128. requiredLimits: parameters.requiredLimits
  29129. };
  29130. device = await adapter.requestDevice( deviceDescriptor );
  29131. } else {
  29132. device = parameters.device;
  29133. }
  29134. device.lost.then( ( info ) => {
  29135. const deviceLossInfo = {
  29136. api: 'WebGPU',
  29137. message: info.message || 'Unknown reason',
  29138. reason: info.reason || null,
  29139. originalEvent: info
  29140. };
  29141. renderer.onDeviceLost( deviceLossInfo );
  29142. } );
  29143. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  29144. this.device = device;
  29145. this.context = context;
  29146. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  29147. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  29148. this.context.configure( {
  29149. device: this.device,
  29150. format: this.utils.getPreferredCanvasFormat(),
  29151. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  29152. alphaMode: alphaMode
  29153. } );
  29154. this.updateSize();
  29155. }
  29156. get coordinateSystem() {
  29157. return WebGPUCoordinateSystem;
  29158. }
  29159. async getArrayBufferAsync( attribute ) {
  29160. return await this.attributeUtils.getArrayBufferAsync( attribute );
  29161. }
  29162. getContext() {
  29163. return this.context;
  29164. }
  29165. _getDefaultRenderPassDescriptor() {
  29166. let descriptor = this.defaultRenderPassdescriptor;
  29167. if ( descriptor === null ) {
  29168. const renderer = this.renderer;
  29169. descriptor = {
  29170. colorAttachments: [ {
  29171. view: null
  29172. } ],
  29173. };
  29174. if ( this.renderer.depth === true || this.renderer.stencil === true ) {
  29175. descriptor.depthStencilAttachment = {
  29176. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  29177. };
  29178. }
  29179. const colorAttachment = descriptor.colorAttachments[ 0 ];
  29180. if ( this.renderer.samples > 0 ) {
  29181. colorAttachment.view = this.colorBuffer.createView();
  29182. } else {
  29183. colorAttachment.resolveTarget = undefined;
  29184. }
  29185. this.defaultRenderPassdescriptor = descriptor;
  29186. }
  29187. const colorAttachment = descriptor.colorAttachments[ 0 ];
  29188. if ( this.renderer.samples > 0 ) {
  29189. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  29190. } else {
  29191. colorAttachment.view = this.context.getCurrentTexture().createView();
  29192. }
  29193. return descriptor;
  29194. }
  29195. _getRenderPassDescriptor( renderContext ) {
  29196. const renderTarget = renderContext.renderTarget;
  29197. const renderTargetData = this.get( renderTarget );
  29198. let descriptors = renderTargetData.descriptors;
  29199. if ( descriptors === undefined ||
  29200. renderTargetData.width !== renderTarget.width ||
  29201. renderTargetData.height !== renderTarget.height ||
  29202. renderTargetData.activeMipmapLevel !== renderTarget.activeMipmapLevel ||
  29203. renderTargetData.samples !== renderTarget.samples
  29204. ) {
  29205. descriptors = {};
  29206. renderTargetData.descriptors = descriptors;
  29207. // dispose
  29208. const onDispose = () => {
  29209. renderTarget.removeEventListener( 'dispose', onDispose );
  29210. this.delete( renderTarget );
  29211. };
  29212. renderTarget.addEventListener( 'dispose', onDispose );
  29213. }
  29214. const cacheKey = renderContext.getCacheKey();
  29215. let descriptor = descriptors[ cacheKey ];
  29216. if ( descriptor === undefined ) {
  29217. const textures = renderContext.textures;
  29218. const colorAttachments = [];
  29219. for ( let i = 0; i < textures.length; i ++ ) {
  29220. const textureData = this.get( textures[ i ] );
  29221. const textureView = textureData.texture.createView( {
  29222. baseMipLevel: renderContext.activeMipmapLevel,
  29223. mipLevelCount: 1,
  29224. baseArrayLayer: renderContext.activeCubeFace,
  29225. dimension: GPUTextureViewDimension.TwoD
  29226. } );
  29227. let view, resolveTarget;
  29228. if ( textureData.msaaTexture !== undefined ) {
  29229. view = textureData.msaaTexture.createView();
  29230. resolveTarget = textureView;
  29231. } else {
  29232. view = textureView;
  29233. resolveTarget = undefined;
  29234. }
  29235. colorAttachments.push( {
  29236. view,
  29237. resolveTarget,
  29238. loadOp: GPULoadOp.Load,
  29239. storeOp: GPUStoreOp.Store
  29240. } );
  29241. }
  29242. descriptor = {
  29243. colorAttachments,
  29244. };
  29245. if ( renderContext.depth ) {
  29246. const depthTextureData = this.get( renderContext.depthTexture );
  29247. const depthStencilAttachment = {
  29248. view: depthTextureData.texture.createView()
  29249. };
  29250. descriptor.depthStencilAttachment = depthStencilAttachment;
  29251. }
  29252. descriptors[ cacheKey ] = descriptor;
  29253. renderTargetData.width = renderTarget.width;
  29254. renderTargetData.height = renderTarget.height;
  29255. renderTargetData.samples = renderTarget.samples;
  29256. renderTargetData.activeMipmapLevel = renderTarget.activeMipmapLevel;
  29257. }
  29258. return descriptor;
  29259. }
  29260. beginRender( renderContext ) {
  29261. const renderContextData = this.get( renderContext );
  29262. const device = this.device;
  29263. const occlusionQueryCount = renderContext.occlusionQueryCount;
  29264. let occlusionQuerySet;
  29265. if ( occlusionQueryCount > 0 ) {
  29266. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  29267. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  29268. // Get a reference to the array of objects with queries. The renderContextData property
  29269. // can be changed by another render pass before the buffer.mapAsyc() completes.
  29270. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  29271. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  29272. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  29273. //
  29274. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  29275. renderContextData.occlusionQuerySet = occlusionQuerySet;
  29276. renderContextData.occlusionQueryIndex = 0;
  29277. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  29278. renderContextData.lastOcclusionObject = null;
  29279. }
  29280. let descriptor;
  29281. if ( renderContext.textures === null ) {
  29282. descriptor = this._getDefaultRenderPassDescriptor();
  29283. } else {
  29284. descriptor = this._getRenderPassDescriptor( renderContext );
  29285. }
  29286. this.initTimestampQuery( renderContext, descriptor );
  29287. descriptor.occlusionQuerySet = occlusionQuerySet;
  29288. const depthStencilAttachment = descriptor.depthStencilAttachment;
  29289. if ( renderContext.textures !== null ) {
  29290. const colorAttachments = descriptor.colorAttachments;
  29291. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  29292. const colorAttachment = colorAttachments[ i ];
  29293. if ( renderContext.clearColor ) {
  29294. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  29295. colorAttachment.loadOp = GPULoadOp.Clear;
  29296. colorAttachment.storeOp = GPUStoreOp.Store;
  29297. } else {
  29298. colorAttachment.loadOp = GPULoadOp.Load;
  29299. colorAttachment.storeOp = GPUStoreOp.Store;
  29300. }
  29301. }
  29302. } else {
  29303. const colorAttachment = descriptor.colorAttachments[ 0 ];
  29304. if ( renderContext.clearColor ) {
  29305. colorAttachment.clearValue = renderContext.clearColorValue;
  29306. colorAttachment.loadOp = GPULoadOp.Clear;
  29307. colorAttachment.storeOp = GPUStoreOp.Store;
  29308. } else {
  29309. colorAttachment.loadOp = GPULoadOp.Load;
  29310. colorAttachment.storeOp = GPUStoreOp.Store;
  29311. }
  29312. }
  29313. //
  29314. if ( renderContext.depth ) {
  29315. if ( renderContext.clearDepth ) {
  29316. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  29317. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  29318. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  29319. } else {
  29320. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  29321. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  29322. }
  29323. }
  29324. if ( renderContext.stencil ) {
  29325. if ( renderContext.clearStencil ) {
  29326. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  29327. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  29328. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  29329. } else {
  29330. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  29331. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  29332. }
  29333. }
  29334. //
  29335. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  29336. const currentPass = encoder.beginRenderPass( descriptor );
  29337. //
  29338. renderContextData.descriptor = descriptor;
  29339. renderContextData.encoder = encoder;
  29340. renderContextData.currentPass = currentPass;
  29341. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  29342. renderContextData.renderBundles = [];
  29343. //
  29344. if ( renderContext.viewport ) {
  29345. this.updateViewport( renderContext );
  29346. }
  29347. if ( renderContext.scissor ) {
  29348. const { x, y, width, height } = renderContext.scissorValue;
  29349. currentPass.setScissorRect( x, y, width, height );
  29350. }
  29351. }
  29352. finishRender( renderContext ) {
  29353. const renderContextData = this.get( renderContext );
  29354. const occlusionQueryCount = renderContext.occlusionQueryCount;
  29355. if ( renderContextData.renderBundles.length > 0 ) {
  29356. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  29357. }
  29358. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  29359. renderContextData.currentPass.endOcclusionQuery();
  29360. }
  29361. renderContextData.currentPass.end();
  29362. if ( occlusionQueryCount > 0 ) {
  29363. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  29364. //
  29365. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  29366. if ( queryResolveBuffer === undefined ) {
  29367. queryResolveBuffer = this.device.createBuffer(
  29368. {
  29369. size: bufferSize,
  29370. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  29371. }
  29372. );
  29373. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  29374. }
  29375. //
  29376. const readBuffer = this.device.createBuffer(
  29377. {
  29378. size: bufferSize,
  29379. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  29380. }
  29381. );
  29382. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  29383. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  29384. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  29385. renderContextData.occlusionQueryBuffer = readBuffer;
  29386. //
  29387. this.resolveOccludedAsync( renderContext );
  29388. }
  29389. this.prepareTimestampBuffer( renderContext, renderContextData.encoder );
  29390. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  29391. //
  29392. if ( renderContext.textures !== null ) {
  29393. const textures = renderContext.textures;
  29394. for ( let i = 0; i < textures.length; i ++ ) {
  29395. const texture = textures[ i ];
  29396. if ( texture.generateMipmaps === true ) {
  29397. this.textureUtils.generateMipmaps( texture );
  29398. }
  29399. }
  29400. }
  29401. }
  29402. isOccluded( renderContext, object ) {
  29403. const renderContextData = this.get( renderContext );
  29404. return renderContextData.occluded && renderContextData.occluded.has( object );
  29405. }
  29406. async resolveOccludedAsync( renderContext ) {
  29407. const renderContextData = this.get( renderContext );
  29408. // handle occlusion query results
  29409. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  29410. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  29411. const occluded = new WeakSet();
  29412. renderContextData.currentOcclusionQueryObjects = null;
  29413. renderContextData.currentOcclusionQueryBuffer = null;
  29414. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  29415. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  29416. const results = new BigUint64Array( buffer );
  29417. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  29418. if ( results[ i ] !== BigInt( 0 ) ) {
  29419. occluded.add( currentOcclusionQueryObjects[ i ] );
  29420. }
  29421. }
  29422. currentOcclusionQueryBuffer.destroy();
  29423. renderContextData.occluded = occluded;
  29424. }
  29425. }
  29426. updateViewport( renderContext ) {
  29427. const { currentPass } = this.get( renderContext );
  29428. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  29429. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  29430. }
  29431. clear( color, depth, stencil, renderTargetData = null ) {
  29432. const device = this.device;
  29433. const renderer = this.renderer;
  29434. let colorAttachments = [];
  29435. let depthStencilAttachment;
  29436. let clearValue;
  29437. let supportsDepth;
  29438. let supportsStencil;
  29439. if ( color ) {
  29440. const clearColor = this.getClearColor();
  29441. if ( this.renderer.alpha === true ) {
  29442. // premultiply alpha
  29443. const a = clearColor.a;
  29444. clearValue = { r: clearColor.r * a, g: clearColor.g * a, b: clearColor.b * a, a: a };
  29445. } else {
  29446. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  29447. }
  29448. }
  29449. if ( renderTargetData === null ) {
  29450. supportsDepth = renderer.depth;
  29451. supportsStencil = renderer.stencil;
  29452. const descriptor = this._getDefaultRenderPassDescriptor();
  29453. if ( color ) {
  29454. colorAttachments = descriptor.colorAttachments;
  29455. const colorAttachment = colorAttachments[ 0 ];
  29456. colorAttachment.clearValue = clearValue;
  29457. colorAttachment.loadOp = GPULoadOp.Clear;
  29458. colorAttachment.storeOp = GPUStoreOp.Store;
  29459. }
  29460. if ( supportsDepth || supportsStencil ) {
  29461. depthStencilAttachment = descriptor.depthStencilAttachment;
  29462. }
  29463. } else {
  29464. supportsDepth = renderTargetData.depth;
  29465. supportsStencil = renderTargetData.stencil;
  29466. if ( color ) {
  29467. for ( const texture of renderTargetData.textures ) {
  29468. const textureData = this.get( texture );
  29469. const textureView = textureData.texture.createView();
  29470. let view, resolveTarget;
  29471. if ( textureData.msaaTexture !== undefined ) {
  29472. view = textureData.msaaTexture.createView();
  29473. resolveTarget = textureView;
  29474. } else {
  29475. view = textureView;
  29476. resolveTarget = undefined;
  29477. }
  29478. colorAttachments.push( {
  29479. view,
  29480. resolveTarget,
  29481. clearValue,
  29482. loadOp: GPULoadOp.Clear,
  29483. storeOp: GPUStoreOp.Store
  29484. } );
  29485. }
  29486. }
  29487. if ( supportsDepth || supportsStencil ) {
  29488. const depthTextureData = this.get( renderTargetData.depthTexture );
  29489. depthStencilAttachment = {
  29490. view: depthTextureData.texture.createView()
  29491. };
  29492. }
  29493. }
  29494. //
  29495. if ( supportsDepth ) {
  29496. if ( depth ) {
  29497. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  29498. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  29499. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  29500. } else {
  29501. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  29502. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  29503. }
  29504. }
  29505. //
  29506. if ( supportsStencil ) {
  29507. if ( stencil ) {
  29508. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  29509. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  29510. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  29511. } else {
  29512. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  29513. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  29514. }
  29515. }
  29516. //
  29517. const encoder = device.createCommandEncoder( {} );
  29518. const currentPass = encoder.beginRenderPass( {
  29519. colorAttachments,
  29520. depthStencilAttachment
  29521. } );
  29522. currentPass.end();
  29523. device.queue.submit( [ encoder.finish() ] );
  29524. }
  29525. // compute
  29526. beginCompute( computeGroup ) {
  29527. const groupGPU = this.get( computeGroup );
  29528. const descriptor = {};
  29529. this.initTimestampQuery( computeGroup, descriptor );
  29530. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder();
  29531. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  29532. }
  29533. compute( computeGroup, computeNode, bindings, pipeline ) {
  29534. const { passEncoderGPU } = this.get( computeGroup );
  29535. // pipeline
  29536. const pipelineGPU = this.get( pipeline ).pipeline;
  29537. passEncoderGPU.setPipeline( pipelineGPU );
  29538. // bind groups
  29539. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  29540. const bindGroup = bindings[ i ];
  29541. const bindingsData = this.get( bindGroup );
  29542. passEncoderGPU.setBindGroup( i, bindingsData.group );
  29543. }
  29544. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  29545. const computeNodeData = this.get( computeNode );
  29546. if ( computeNodeData.dispatchSize === undefined ) computeNodeData.dispatchSize = { x: 0, y: 1, z: 1 };
  29547. const { dispatchSize } = computeNodeData;
  29548. if ( computeNode.dispatchCount > maxComputeWorkgroupsPerDimension ) {
  29549. dispatchSize.x = Math.min( computeNode.dispatchCount, maxComputeWorkgroupsPerDimension );
  29550. dispatchSize.y = Math.ceil( computeNode.dispatchCount / maxComputeWorkgroupsPerDimension );
  29551. } else {
  29552. dispatchSize.x = computeNode.dispatchCount;
  29553. }
  29554. passEncoderGPU.dispatchWorkgroups(
  29555. dispatchSize.x,
  29556. dispatchSize.y,
  29557. dispatchSize.z
  29558. );
  29559. }
  29560. finishCompute( computeGroup ) {
  29561. const groupData = this.get( computeGroup );
  29562. groupData.passEncoderGPU.end();
  29563. this.prepareTimestampBuffer( computeGroup, groupData.cmdEncoderGPU );
  29564. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  29565. }
  29566. async waitForGPU() {
  29567. await this.device.queue.onSubmittedWorkDone();
  29568. }
  29569. // render object
  29570. draw( renderObject, info ) {
  29571. const { object, context, pipeline } = renderObject;
  29572. const bindings = renderObject.getBindings();
  29573. const renderContextData = this.get( context );
  29574. const pipelineGPU = this.get( pipeline ).pipeline;
  29575. const currentSets = renderContextData.currentSets;
  29576. const passEncoderGPU = renderContextData.currentPass;
  29577. const drawParams = renderObject.getDrawParameters();
  29578. if ( drawParams === null ) return;
  29579. // pipeline
  29580. if ( currentSets.pipeline !== pipelineGPU ) {
  29581. passEncoderGPU.setPipeline( pipelineGPU );
  29582. currentSets.pipeline = pipelineGPU;
  29583. }
  29584. // bind groups
  29585. const currentBindingGroups = currentSets.bindingGroups;
  29586. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  29587. const bindGroup = bindings[ i ];
  29588. const bindingsData = this.get( bindGroup );
  29589. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  29590. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  29591. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  29592. }
  29593. }
  29594. // attributes
  29595. const index = renderObject.getIndex();
  29596. const hasIndex = ( index !== null );
  29597. // index
  29598. if ( hasIndex === true ) {
  29599. if ( currentSets.index !== index ) {
  29600. const buffer = this.get( index ).buffer;
  29601. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  29602. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  29603. currentSets.index = index;
  29604. }
  29605. }
  29606. // vertex buffers
  29607. const vertexBuffers = renderObject.getVertexBuffers();
  29608. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  29609. const vertexBuffer = vertexBuffers[ i ];
  29610. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  29611. const buffer = this.get( vertexBuffer ).buffer;
  29612. passEncoderGPU.setVertexBuffer( i, buffer );
  29613. currentSets.attributes[ i ] = vertexBuffer;
  29614. }
  29615. }
  29616. // occlusion queries - handle multiple consecutive draw calls for an object
  29617. if ( renderContextData.occlusionQuerySet !== undefined ) {
  29618. const lastObject = renderContextData.lastOcclusionObject;
  29619. if ( lastObject !== object ) {
  29620. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  29621. passEncoderGPU.endOcclusionQuery();
  29622. renderContextData.occlusionQueryIndex ++;
  29623. }
  29624. if ( object.occlusionTest === true ) {
  29625. passEncoderGPU.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  29626. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  29627. }
  29628. renderContextData.lastOcclusionObject = object;
  29629. }
  29630. }
  29631. // draw
  29632. if ( object.isBatchedMesh === true ) {
  29633. const starts = object._multiDrawStarts;
  29634. const counts = object._multiDrawCounts;
  29635. const drawCount = object._multiDrawCount;
  29636. const drawInstances = object._multiDrawInstances;
  29637. const bytesPerElement = hasIndex ? index.array.BYTES_PER_ELEMENT : 1;
  29638. for ( let i = 0; i < drawCount; i ++ ) {
  29639. const count = drawInstances ? drawInstances[ i ] : 1;
  29640. const firstInstance = count > 1 ? 0 : i;
  29641. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / bytesPerElement, 0, firstInstance );
  29642. }
  29643. } else if ( hasIndex === true ) {
  29644. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  29645. const indirect = renderObject.getIndirect();
  29646. if ( indirect !== null ) {
  29647. const buffer = this.get( indirect ).buffer;
  29648. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  29649. } else {
  29650. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  29651. }
  29652. info.update( object, indexCount, instanceCount );
  29653. } else {
  29654. const { vertexCount, instanceCount, firstVertex } = drawParams;
  29655. const indirect = renderObject.getIndirect();
  29656. if ( indirect !== null ) {
  29657. const buffer = this.get( indirect ).buffer;
  29658. passEncoderGPU.drawIndirect( buffer, 0 );
  29659. } else {
  29660. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  29661. }
  29662. info.update( object, vertexCount, instanceCount );
  29663. }
  29664. }
  29665. // cache key
  29666. needsRenderUpdate( renderObject ) {
  29667. const data = this.get( renderObject );
  29668. const { object, material } = renderObject;
  29669. const utils = this.utils;
  29670. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  29671. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  29672. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  29673. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  29674. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  29675. let needsUpdate = false;
  29676. if ( data.material !== material || data.materialVersion !== material.version ||
  29677. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  29678. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  29679. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  29680. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  29681. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  29682. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  29683. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  29684. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  29685. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  29686. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  29687. data.primitiveTopology !== primitiveTopology ||
  29688. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  29689. ) {
  29690. data.material = material; data.materialVersion = material.version;
  29691. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  29692. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  29693. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  29694. data.colorWrite = material.colorWrite;
  29695. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  29696. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  29697. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  29698. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  29699. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  29700. data.sampleCount = sampleCount;
  29701. data.colorSpace = colorSpace;
  29702. data.colorFormat = colorFormat;
  29703. data.depthStencilFormat = depthStencilFormat;
  29704. data.primitiveTopology = primitiveTopology;
  29705. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  29706. needsUpdate = true;
  29707. }
  29708. return needsUpdate;
  29709. }
  29710. getRenderCacheKey( renderObject ) {
  29711. const { object, material } = renderObject;
  29712. const utils = this.utils;
  29713. const renderContext = renderObject.context;
  29714. return [
  29715. material.transparent, material.blending, material.premultipliedAlpha,
  29716. material.blendSrc, material.blendDst, material.blendEquation,
  29717. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  29718. material.colorWrite,
  29719. material.depthWrite, material.depthTest, material.depthFunc,
  29720. material.stencilWrite, material.stencilFunc,
  29721. material.stencilFail, material.stencilZFail, material.stencilZPass,
  29722. material.stencilFuncMask, material.stencilWriteMask,
  29723. material.side,
  29724. utils.getSampleCountRenderContext( renderContext ),
  29725. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  29726. utils.getPrimitiveTopology( object, material ),
  29727. renderObject.getGeometryCacheKey(),
  29728. renderObject.clippingContextCacheKey
  29729. ].join();
  29730. }
  29731. // textures
  29732. createSampler( texture ) {
  29733. this.textureUtils.createSampler( texture );
  29734. }
  29735. destroySampler( texture ) {
  29736. this.textureUtils.destroySampler( texture );
  29737. }
  29738. createDefaultTexture( texture ) {
  29739. this.textureUtils.createDefaultTexture( texture );
  29740. }
  29741. createTexture( texture, options ) {
  29742. this.textureUtils.createTexture( texture, options );
  29743. }
  29744. updateTexture( texture, options ) {
  29745. this.textureUtils.updateTexture( texture, options );
  29746. }
  29747. generateMipmaps( texture ) {
  29748. this.textureUtils.generateMipmaps( texture );
  29749. }
  29750. destroyTexture( texture ) {
  29751. this.textureUtils.destroyTexture( texture );
  29752. }
  29753. copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  29754. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  29755. }
  29756. initTimestampQuery( renderContext, descriptor ) {
  29757. if ( ! this.trackTimestamp ) return;
  29758. const renderContextData = this.get( renderContext );
  29759. if ( ! renderContextData.timeStampQuerySet ) {
  29760. const type = renderContext.isComputeNode ? 'compute' : 'render';
  29761. const timeStampQuerySet = this.device.createQuerySet( { type: 'timestamp', count: 2, label: `timestamp_${type}_${renderContext.id}` } );
  29762. const timestampWrites = {
  29763. querySet: timeStampQuerySet,
  29764. beginningOfPassWriteIndex: 0, // Write timestamp in index 0 when pass begins.
  29765. endOfPassWriteIndex: 1, // Write timestamp in index 1 when pass ends.
  29766. };
  29767. Object.assign( descriptor, { timestampWrites } );
  29768. renderContextData.timeStampQuerySet = timeStampQuerySet;
  29769. }
  29770. }
  29771. // timestamp utils
  29772. prepareTimestampBuffer( renderContext, encoder ) {
  29773. if ( ! this.trackTimestamp ) return;
  29774. const renderContextData = this.get( renderContext );
  29775. const size = 2 * BigInt64Array.BYTES_PER_ELEMENT;
  29776. if ( renderContextData.currentTimestampQueryBuffers === undefined ) {
  29777. renderContextData.currentTimestampQueryBuffers = {
  29778. resolveBuffer: this.device.createBuffer( {
  29779. label: 'timestamp resolve buffer',
  29780. size: size,
  29781. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC,
  29782. } ),
  29783. resultBuffer: this.device.createBuffer( {
  29784. label: 'timestamp result buffer',
  29785. size: size,
  29786. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
  29787. } )
  29788. };
  29789. }
  29790. const { resolveBuffer, resultBuffer } = renderContextData.currentTimestampQueryBuffers;
  29791. encoder.resolveQuerySet( renderContextData.timeStampQuerySet, 0, 2, resolveBuffer, 0 );
  29792. if ( resultBuffer.mapState === 'unmapped' ) {
  29793. encoder.copyBufferToBuffer( resolveBuffer, 0, resultBuffer, 0, size );
  29794. }
  29795. }
  29796. async resolveTimestampAsync( renderContext, type = 'render' ) {
  29797. if ( ! this.trackTimestamp ) return;
  29798. const renderContextData = this.get( renderContext );
  29799. if ( renderContextData.currentTimestampQueryBuffers === undefined ) return;
  29800. const { resultBuffer } = renderContextData.currentTimestampQueryBuffers;
  29801. if ( resultBuffer.mapState === 'unmapped' ) {
  29802. resultBuffer.mapAsync( GPUMapMode.READ ).then( () => {
  29803. const times = new BigUint64Array( resultBuffer.getMappedRange() );
  29804. const duration = Number( times[ 1 ] - times[ 0 ] ) / 1000000;
  29805. this.renderer.info.updateTimestamp( type, duration );
  29806. resultBuffer.unmap();
  29807. } );
  29808. }
  29809. }
  29810. // node builder
  29811. createNodeBuilder( object, renderer ) {
  29812. return new WGSLNodeBuilder( object, renderer );
  29813. }
  29814. // program
  29815. createProgram( program ) {
  29816. const programGPU = this.get( program );
  29817. programGPU.module = {
  29818. module: this.device.createShaderModule( { code: program.code, label: program.stage } ),
  29819. entryPoint: 'main'
  29820. };
  29821. }
  29822. destroyProgram( program ) {
  29823. this.delete( program );
  29824. }
  29825. // pipelines
  29826. createRenderPipeline( renderObject, promises ) {
  29827. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  29828. }
  29829. createComputePipeline( computePipeline, bindings ) {
  29830. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  29831. }
  29832. beginBundle( renderContext ) {
  29833. const renderContextData = this.get( renderContext );
  29834. renderContextData._currentPass = renderContextData.currentPass;
  29835. renderContextData._currentSets = renderContextData.currentSets;
  29836. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  29837. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  29838. }
  29839. finishBundle( renderContext, bundle ) {
  29840. const renderContextData = this.get( renderContext );
  29841. const bundleEncoder = renderContextData.currentPass;
  29842. const bundleGPU = bundleEncoder.finish();
  29843. this.get( bundle ).bundleGPU = bundleGPU;
  29844. // restore render pass state
  29845. renderContextData.currentSets = renderContextData._currentSets;
  29846. renderContextData.currentPass = renderContextData._currentPass;
  29847. }
  29848. addBundle( renderContext, bundle ) {
  29849. const renderContextData = this.get( renderContext );
  29850. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  29851. }
  29852. // bindings
  29853. createBindings( bindGroup, bindings, cacheIndex, version ) {
  29854. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  29855. }
  29856. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  29857. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  29858. }
  29859. updateBinding( binding ) {
  29860. this.bindingUtils.updateBinding( binding );
  29861. }
  29862. // attributes
  29863. createIndexAttribute( attribute ) {
  29864. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  29865. }
  29866. createAttribute( attribute ) {
  29867. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  29868. }
  29869. createStorageAttribute( attribute ) {
  29870. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  29871. }
  29872. createIndirectStorageAttribute( attribute ) {
  29873. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  29874. }
  29875. updateAttribute( attribute ) {
  29876. this.attributeUtils.updateAttribute( attribute );
  29877. }
  29878. destroyAttribute( attribute ) {
  29879. this.attributeUtils.destroyAttribute( attribute );
  29880. }
  29881. // canvas
  29882. updateSize() {
  29883. this.colorBuffer = this.textureUtils.getColorBuffer();
  29884. this.defaultRenderPassdescriptor = null;
  29885. }
  29886. // utils public
  29887. getMaxAnisotropy() {
  29888. return 16;
  29889. }
  29890. hasFeature( name ) {
  29891. return this.device.features.has( name );
  29892. }
  29893. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  29894. let dstX = 0;
  29895. let dstY = 0;
  29896. let dstLayer = 0;
  29897. let srcX = 0;
  29898. let srcY = 0;
  29899. let srcLayer = 0;
  29900. let srcWidth = srcTexture.image.width;
  29901. let srcHeight = srcTexture.image.height;
  29902. if ( srcRegion !== null ) {
  29903. srcX = srcRegion.x;
  29904. srcY = srcRegion.y;
  29905. srcLayer = srcRegion.z || 0;
  29906. srcWidth = srcRegion.width;
  29907. srcHeight = srcRegion.height;
  29908. }
  29909. if ( dstPosition !== null ) {
  29910. dstX = dstPosition.x;
  29911. dstY = dstPosition.y;
  29912. dstLayer = dstPosition.z || 0;
  29913. }
  29914. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  29915. const sourceGPU = this.get( srcTexture ).texture;
  29916. const destinationGPU = this.get( dstTexture ).texture;
  29917. encoder.copyTextureToTexture(
  29918. {
  29919. texture: sourceGPU,
  29920. mipLevel: level,
  29921. origin: { x: srcX, y: srcY, z: srcLayer }
  29922. },
  29923. {
  29924. texture: destinationGPU,
  29925. mipLevel: level,
  29926. origin: { x: dstX, y: dstY, z: dstLayer }
  29927. },
  29928. [
  29929. srcWidth,
  29930. srcHeight,
  29931. 1
  29932. ]
  29933. );
  29934. this.device.queue.submit( [ encoder.finish() ] );
  29935. }
  29936. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  29937. const renderContextData = this.get( renderContext );
  29938. let sourceGPU = null;
  29939. if ( renderContext.renderTarget ) {
  29940. if ( texture.isDepthTexture ) {
  29941. sourceGPU = this.get( renderContext.depthTexture ).texture;
  29942. } else {
  29943. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  29944. }
  29945. } else {
  29946. if ( texture.isDepthTexture ) {
  29947. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  29948. } else {
  29949. sourceGPU = this.context.getCurrentTexture();
  29950. }
  29951. }
  29952. const destinationGPU = this.get( texture ).texture;
  29953. if ( sourceGPU.format !== destinationGPU.format ) {
  29954. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  29955. return;
  29956. }
  29957. let encoder;
  29958. if ( renderContextData.currentPass ) {
  29959. renderContextData.currentPass.end();
  29960. encoder = renderContextData.encoder;
  29961. } else {
  29962. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  29963. }
  29964. encoder.copyTextureToTexture(
  29965. {
  29966. texture: sourceGPU,
  29967. origin: [ rectangle.x, rectangle.y, 0 ],
  29968. },
  29969. {
  29970. texture: destinationGPU
  29971. },
  29972. [
  29973. rectangle.z,
  29974. rectangle.w
  29975. ]
  29976. );
  29977. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  29978. if ( renderContextData.currentPass ) {
  29979. const { descriptor } = renderContextData;
  29980. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  29981. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  29982. }
  29983. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  29984. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  29985. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  29986. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  29987. if ( renderContext.viewport ) {
  29988. this.updateViewport( renderContext );
  29989. }
  29990. if ( renderContext.scissor ) {
  29991. const { x, y, width, height } = renderContext.scissorValue;
  29992. renderContextData.currentPass.setScissorRect( x, y, width, height );
  29993. }
  29994. } else {
  29995. this.device.queue.submit( [ encoder.finish() ] );
  29996. }
  29997. }
  29998. }
  29999. class IESSpotLight extends SpotLight {
  30000. constructor( color, intensity, distance, angle, penumbra, decay ) {
  30001. super( color, intensity, distance, angle, penumbra, decay );
  30002. this.iesMap = null;
  30003. }
  30004. copy( source, recursive ) {
  30005. super.copy( source, recursive );
  30006. this.iesMap = source.iesMap;
  30007. return this;
  30008. }
  30009. }
  30010. class BasicNodeLibrary extends NodeLibrary {
  30011. constructor() {
  30012. super();
  30013. this.addLight( PointLightNode, PointLight );
  30014. this.addLight( DirectionalLightNode, DirectionalLight );
  30015. this.addLight( RectAreaLightNode, RectAreaLight );
  30016. this.addLight( SpotLightNode, SpotLight );
  30017. this.addLight( AmbientLightNode, AmbientLight );
  30018. this.addLight( HemisphereLightNode, HemisphereLight );
  30019. this.addLight( LightProbeNode, LightProbe );
  30020. this.addLight( IESSpotLightNode, IESSpotLight );
  30021. this.addToneMapping( linearToneMapping, LinearToneMapping );
  30022. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  30023. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  30024. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  30025. this.addToneMapping( agxToneMapping, AgXToneMapping );
  30026. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  30027. }
  30028. }
  30029. class WebGPURenderer extends Renderer {
  30030. constructor( parameters = {} ) {
  30031. let BackendClass;
  30032. if ( parameters.forceWebGL ) {
  30033. BackendClass = WebGLBackend;
  30034. } else {
  30035. BackendClass = WebGPUBackend;
  30036. parameters.getFallback = () => {
  30037. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  30038. return new WebGLBackend( parameters );
  30039. };
  30040. }
  30041. const backend = new BackendClass( parameters );
  30042. super( backend, parameters );
  30043. this.library = new BasicNodeLibrary();
  30044. this.isWebGPURenderer = true;
  30045. }
  30046. }
  30047. class BundleGroup extends Group {
  30048. constructor() {
  30049. super();
  30050. this.isBundleGroup = true;
  30051. this.type = 'BundleGroup';
  30052. this.static = true;
  30053. this.version = 0;
  30054. }
  30055. set needsUpdate( value ) {
  30056. if ( value === true ) this.version ++;
  30057. }
  30058. }
  30059. const _material = /*@__PURE__*/ new NodeMaterial();
  30060. const _quadMesh = /*@__PURE__*/ new QuadMesh( _material );
  30061. class PostProcessing {
  30062. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  30063. this.renderer = renderer;
  30064. this.outputNode = outputNode;
  30065. this.outputColorTransform = true;
  30066. this.needsUpdate = true;
  30067. _material.name = 'PostProcessing';
  30068. }
  30069. render() {
  30070. this.update();
  30071. const renderer = this.renderer;
  30072. const toneMapping = renderer.toneMapping;
  30073. const outputColorSpace = renderer.outputColorSpace;
  30074. renderer.toneMapping = NoToneMapping;
  30075. renderer.outputColorSpace = LinearSRGBColorSpace;
  30076. //
  30077. _quadMesh.render( renderer );
  30078. //
  30079. renderer.toneMapping = toneMapping;
  30080. renderer.outputColorSpace = outputColorSpace;
  30081. }
  30082. update() {
  30083. if ( this.needsUpdate === true ) {
  30084. const renderer = this.renderer;
  30085. const toneMapping = renderer.toneMapping;
  30086. const outputColorSpace = renderer.outputColorSpace;
  30087. _quadMesh.material.fragmentNode = this.outputColorTransform === true ? renderOutput( this.outputNode, toneMapping, outputColorSpace ) : this.outputNode.context( { toneMapping, outputColorSpace } );
  30088. _quadMesh.material.needsUpdate = true;
  30089. this.needsUpdate = false;
  30090. }
  30091. }
  30092. async renderAsync() {
  30093. this.update();
  30094. const renderer = this.renderer;
  30095. const toneMapping = renderer.toneMapping;
  30096. const outputColorSpace = renderer.outputColorSpace;
  30097. renderer.toneMapping = NoToneMapping;
  30098. renderer.outputColorSpace = LinearSRGBColorSpace;
  30099. //
  30100. await _quadMesh.renderAsync( renderer );
  30101. //
  30102. renderer.toneMapping = toneMapping;
  30103. renderer.outputColorSpace = outputColorSpace;
  30104. }
  30105. }
  30106. // renderer state
  30107. function saveRendererState( renderer, state = {} ) {
  30108. state.toneMapping = renderer.toneMapping;
  30109. state.toneMappingExposure = renderer.toneMappingExposure;
  30110. state.outputColorSpace = renderer.outputColorSpace;
  30111. state.renderTarget = renderer.getRenderTarget();
  30112. state.activeCubeFace = renderer.getActiveCubeFace();
  30113. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  30114. state.renderObjectFunction = renderer.getRenderObjectFunction();
  30115. state.pixelRatio = renderer.getPixelRatio();
  30116. state.mrt = renderer.getMRT();
  30117. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  30118. state.clearAlpha = renderer.getClearAlpha();
  30119. state.autoClear = renderer.autoClear;
  30120. state.scissorTest = renderer.getScissorTest();
  30121. return state;
  30122. }
  30123. function resetRendererState( renderer, state ) {
  30124. state = saveRendererState( renderer, state );
  30125. renderer.setMRT( null );
  30126. renderer.setRenderObjectFunction( null );
  30127. renderer.setClearColor( 0x000000, 1 );
  30128. renderer.autoClear = true;
  30129. return state;
  30130. }
  30131. function restoreRendererState( renderer, state ) {
  30132. renderer.toneMapping = state.toneMapping;
  30133. renderer.toneMappingExposure = state.toneMappingExposure;
  30134. renderer.outputColorSpace = state.outputColorSpace;
  30135. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  30136. renderer.setRenderObjectFunction( state.renderObjectFunction );
  30137. renderer.setPixelRatio( state.pixelRatio );
  30138. renderer.setMRT( state.mrt );
  30139. renderer.setClearColor( state.clearColor, state.clearAlpha );
  30140. renderer.autoClear = state.autoClear;
  30141. renderer.setScissorTest( state.scissorTest );
  30142. }
  30143. // renderer and scene state
  30144. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  30145. state = saveRendererState( renderer, state );
  30146. state.background = scene.background;
  30147. state.backgroundNode = scene.backgroundNode;
  30148. state.overrideMaterial = scene.overrideMaterial;
  30149. return state;
  30150. }
  30151. function resetRendererAndSceneState( renderer, scene, state ) {
  30152. state = saveRendererAndSceneState( renderer, scene, state );
  30153. scene.background = null;
  30154. scene.backgroundNode = null;
  30155. scene.overrideMaterial = null;
  30156. return state;
  30157. }
  30158. function restoreRendererAndSceneState( renderer, scene, state ) {
  30159. restoreRendererState( renderer, state );
  30160. scene.background = state.background;
  30161. scene.backgroundNode = state.backgroundNode;
  30162. scene.overrideMaterial = state.overrideMaterial;
  30163. }
  30164. var PostProcessingUtils = /*#__PURE__*/Object.freeze({
  30165. __proto__: null,
  30166. resetRendererAndSceneState: resetRendererAndSceneState,
  30167. resetRendererState: resetRendererState,
  30168. restoreRendererAndSceneState: restoreRendererAndSceneState,
  30169. restoreRendererState: restoreRendererState,
  30170. saveRendererAndSceneState: saveRendererAndSceneState,
  30171. saveRendererState: saveRendererState
  30172. });
  30173. class StorageTexture extends Texture {
  30174. constructor( width = 1, height = 1 ) {
  30175. super();
  30176. this.image = { width, height };
  30177. this.magFilter = LinearFilter;
  30178. this.minFilter = LinearFilter;
  30179. this.isStorageTexture = true;
  30180. }
  30181. }
  30182. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  30183. constructor( array, itemSize ) {
  30184. super( array, itemSize, Uint32Array );
  30185. this.isIndirectStorageBufferAttribute = true;
  30186. }
  30187. }
  30188. class NodeLoader extends Loader {
  30189. constructor( manager ) {
  30190. super( manager );
  30191. this.textures = {};
  30192. this.nodes = {};
  30193. }
  30194. load( url, onLoad, onProgress, onError ) {
  30195. const loader = new FileLoader( this.manager );
  30196. loader.setPath( this.path );
  30197. loader.setRequestHeader( this.requestHeader );
  30198. loader.setWithCredentials( this.withCredentials );
  30199. loader.load( url, ( text ) => {
  30200. try {
  30201. onLoad( this.parse( JSON.parse( text ) ) );
  30202. } catch ( e ) {
  30203. if ( onError ) {
  30204. onError( e );
  30205. } else {
  30206. console.error( e );
  30207. }
  30208. this.manager.itemError( url );
  30209. }
  30210. }, onProgress, onError );
  30211. }
  30212. parseNodes( json ) {
  30213. const nodes = {};
  30214. if ( json !== undefined ) {
  30215. for ( const nodeJSON of json ) {
  30216. const { uuid, type } = nodeJSON;
  30217. nodes[ uuid ] = this.createNodeFromType( type );
  30218. nodes[ uuid ].uuid = uuid;
  30219. }
  30220. const meta = { nodes, textures: this.textures };
  30221. for ( const nodeJSON of json ) {
  30222. nodeJSON.meta = meta;
  30223. const node = nodes[ nodeJSON.uuid ];
  30224. node.deserialize( nodeJSON );
  30225. delete nodeJSON.meta;
  30226. }
  30227. }
  30228. return nodes;
  30229. }
  30230. parse( json ) {
  30231. const node = this.createNodeFromType( json.type );
  30232. node.uuid = json.uuid;
  30233. const nodes = this.parseNodes( json.nodes );
  30234. const meta = { nodes, textures: this.textures };
  30235. json.meta = meta;
  30236. node.deserialize( json );
  30237. delete json.meta;
  30238. return node;
  30239. }
  30240. setTextures( value ) {
  30241. this.textures = value;
  30242. return this;
  30243. }
  30244. setNodes( value ) {
  30245. this.nodes = value;
  30246. return this;
  30247. }
  30248. createNodeFromType( type ) {
  30249. if ( this.nodes[ type ] === undefined ) {
  30250. console.error( 'THREE.NodeLoader: Node type not found:', type );
  30251. return float();
  30252. }
  30253. return nodeObject( new this.nodes[ type ]() );
  30254. }
  30255. }
  30256. class NodeMaterialLoader extends MaterialLoader {
  30257. constructor( manager ) {
  30258. super( manager );
  30259. this.nodes = {};
  30260. this.nodeMaterials = {};
  30261. }
  30262. parse( json ) {
  30263. const material = super.parse( json );
  30264. const nodes = this.nodes;
  30265. const inputNodes = json.inputNodes;
  30266. for ( const property in inputNodes ) {
  30267. const uuid = inputNodes[ property ];
  30268. material[ property ] = nodes[ uuid ];
  30269. }
  30270. return material;
  30271. }
  30272. setNodes( value ) {
  30273. this.nodes = value;
  30274. return this;
  30275. }
  30276. setNodeMaterials( value ) {
  30277. this.nodeMaterials = value;
  30278. return this;
  30279. }
  30280. createMaterialFromType( type ) {
  30281. const materialClass = this.nodeMaterials[ type ];
  30282. if ( materialClass !== undefined ) {
  30283. return new materialClass();
  30284. }
  30285. return super.createMaterialFromType( type );
  30286. }
  30287. }
  30288. class NodeObjectLoader extends ObjectLoader {
  30289. constructor( manager ) {
  30290. super( manager );
  30291. this.nodes = {};
  30292. this.nodeMaterials = {};
  30293. this._nodesJSON = null;
  30294. }
  30295. setNodes( value ) {
  30296. this.nodes = value;
  30297. return this;
  30298. }
  30299. setNodeMaterials( value ) {
  30300. this.nodeMaterials = value;
  30301. return this;
  30302. }
  30303. parse( json, onLoad ) {
  30304. this._nodesJSON = json.nodes;
  30305. const data = super.parse( json, onLoad );
  30306. this._nodesJSON = null; // dispose
  30307. return data;
  30308. }
  30309. parseNodes( json, textures ) {
  30310. if ( json !== undefined ) {
  30311. const loader = new NodeLoader();
  30312. loader.setNodes( this.nodes );
  30313. loader.setTextures( textures );
  30314. return loader.parseNodes( json );
  30315. }
  30316. return {};
  30317. }
  30318. parseMaterials( json, textures ) {
  30319. const materials = {};
  30320. if ( json !== undefined ) {
  30321. const nodes = this.parseNodes( this._nodesJSON, textures );
  30322. const loader = new NodeMaterialLoader();
  30323. loader.setTextures( textures );
  30324. loader.setNodes( nodes );
  30325. loader.setNodeMaterials( this.nodeMaterials );
  30326. for ( let i = 0, l = json.length; i < l; i ++ ) {
  30327. const data = json[ i ];
  30328. materials[ data.uuid ] = loader.parse( data );
  30329. }
  30330. }
  30331. return materials;
  30332. }
  30333. }
  30334. class ClippingGroup extends Group {
  30335. constructor() {
  30336. super();
  30337. this.isClippingGroup = true;
  30338. this.clippingPlanes = [];
  30339. this.enabled = true;
  30340. this.clipIntersection = false;
  30341. this.clipShadows = false;
  30342. }
  30343. }
  30344. export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnalyticLightNode, ArrayElementNode, AssignNode, AttributeNode, BackSide, BasicEnvironmentNode, BasicShadowMap, BatchNode, BoxGeometry, BufferAttribute, BufferAttributeNode, BufferGeometry, BufferNode, BumpMapNode, BundleGroup, BypassNode, ByteType, CacheNode, 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, FogExp2Node, FogNode, FogRangeNode, 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, InstancedPointsNodeMaterial, 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, ModelViewProjectionNode, 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, PostProcessingUtils, 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, 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, ZeroFactor, ZeroStencilOp, createCanvasElement, defaultBuildStages, defaultShaderStages, shaderStages, vectorComponents };
粤ICP备19079148号