three.webgpu.nodes.js 943 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586
  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, MeshNormalMaterial, WebGLCubeRenderTarget, BoxGeometry, NoBlending, 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, UVMapping, Euler, LinearSRGBColorSpace, LessCompare, VSMShadowMap, RGFormat, BasicShadowMap, SphereGeometry, BufferAttribute, 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, WebGLMultipleRenderTargets, 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. // cyrb53 (c) 2018 bryc (github.com/bryc). License: Public domain. Attribution appreciated.
  259. // A fast and simple 64-bit (or 53-bit) string hash function with decent collision resistance.
  260. // Largely inspired by MurmurHash2/3, but with a focus on speed/simplicity.
  261. // See https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript/52171480#52171480
  262. // https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js
  263. function cyrb53( value, seed = 0 ) {
  264. let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
  265. if ( value instanceof Array ) {
  266. for ( let i = 0, val; i < value.length; i ++ ) {
  267. val = value[ i ];
  268. h1 = Math.imul( h1 ^ val, 2654435761 );
  269. h2 = Math.imul( h2 ^ val, 1597334677 );
  270. }
  271. } else {
  272. for ( let i = 0, ch; i < value.length; i ++ ) {
  273. ch = value.charCodeAt( i );
  274. h1 = Math.imul( h1 ^ ch, 2654435761 );
  275. h2 = Math.imul( h2 ^ ch, 1597334677 );
  276. }
  277. }
  278. h1 = Math.imul( h1 ^ ( h1 >>> 16 ), 2246822507 );
  279. h1 ^= Math.imul( h2 ^ ( h2 >>> 13 ), 3266489909 );
  280. h2 = Math.imul( h2 ^ ( h2 >>> 16 ), 2246822507 );
  281. h2 ^= Math.imul( h1 ^ ( h1 >>> 13 ), 3266489909 );
  282. return 4294967296 * ( 2097151 & h2 ) + ( h1 >>> 0 );
  283. }
  284. const hashString = ( str ) => cyrb53( str );
  285. const hashArray = ( array ) => cyrb53( array );
  286. const hash$1 = ( ...params ) => cyrb53( params );
  287. function getCacheKey$1( object, force = false ) {
  288. const values = [];
  289. if ( object.isNode === true ) {
  290. values.push( object.id );
  291. object = object.getSelf();
  292. }
  293. for ( const { property, childNode } of getNodeChildren( object ) ) {
  294. values.push( values, cyrb53( property.slice( 0, - 4 ) ), childNode.getCacheKey( force ) );
  295. }
  296. return cyrb53( values );
  297. }
  298. function* getNodeChildren( node, toJSON = false ) {
  299. for ( const property in node ) {
  300. // Ignore private properties.
  301. if ( property.startsWith( '_' ) === true ) continue;
  302. const object = node[ property ];
  303. if ( Array.isArray( object ) === true ) {
  304. for ( let i = 0; i < object.length; i ++ ) {
  305. const child = object[ i ];
  306. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  307. yield { property, index: i, childNode: child };
  308. }
  309. }
  310. } else if ( object && object.isNode === true ) {
  311. yield { property, childNode: object };
  312. } else if ( typeof object === 'object' ) {
  313. for ( const subProperty in object ) {
  314. const child = object[ subProperty ];
  315. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  316. yield { property, index: subProperty, childNode: child };
  317. }
  318. }
  319. }
  320. }
  321. }
  322. function getValueType( value ) {
  323. if ( value === undefined || value === null ) return null;
  324. const typeOf = typeof value;
  325. if ( value.isNode === true ) {
  326. return 'node';
  327. } else if ( typeOf === 'number' ) {
  328. return 'float';
  329. } else if ( typeOf === 'boolean' ) {
  330. return 'bool';
  331. } else if ( typeOf === 'string' ) {
  332. return 'string';
  333. } else if ( typeOf === 'function' ) {
  334. return 'shader';
  335. } else if ( value.isVector2 === true ) {
  336. return 'vec2';
  337. } else if ( value.isVector3 === true ) {
  338. return 'vec3';
  339. } else if ( value.isVector4 === true ) {
  340. return 'vec4';
  341. } else if ( value.isMatrix3 === true ) {
  342. return 'mat3';
  343. } else if ( value.isMatrix4 === true ) {
  344. return 'mat4';
  345. } else if ( value.isColor === true ) {
  346. return 'color';
  347. } else if ( value instanceof ArrayBuffer ) {
  348. return 'ArrayBuffer';
  349. }
  350. return null;
  351. }
  352. function getValueFromType( type, ...params ) {
  353. const last4 = type ? type.slice( - 4 ) : undefined;
  354. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  355. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  356. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  357. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  358. }
  359. if ( type === 'color' ) {
  360. return new Color( ...params );
  361. } else if ( last4 === 'vec2' ) {
  362. return new Vector2( ...params );
  363. } else if ( last4 === 'vec3' ) {
  364. return new Vector3( ...params );
  365. } else if ( last4 === 'vec4' ) {
  366. return new Vector4( ...params );
  367. } else if ( last4 === 'mat3' ) {
  368. return new Matrix3( ...params );
  369. } else if ( last4 === 'mat4' ) {
  370. return new Matrix4( ...params );
  371. } else if ( type === 'bool' ) {
  372. return params[ 0 ] || false;
  373. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  374. return params[ 0 ] || 0;
  375. } else if ( type === 'string' ) {
  376. return params[ 0 ] || '';
  377. } else if ( type === 'ArrayBuffer' ) {
  378. return base64ToArrayBuffer( params[ 0 ] );
  379. }
  380. return null;
  381. }
  382. function arrayBufferToBase64( arrayBuffer ) {
  383. let chars = '';
  384. const array = new Uint8Array( arrayBuffer );
  385. for ( let i = 0; i < array.length; i ++ ) {
  386. chars += String.fromCharCode( array[ i ] );
  387. }
  388. return btoa( chars );
  389. }
  390. function base64ToArrayBuffer( base64 ) {
  391. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  392. }
  393. var NodeUtils = /*#__PURE__*/Object.freeze({
  394. __proto__: null,
  395. arrayBufferToBase64: arrayBufferToBase64,
  396. base64ToArrayBuffer: base64ToArrayBuffer,
  397. getCacheKey: getCacheKey$1,
  398. getNodeChildren: getNodeChildren,
  399. getValueFromType: getValueFromType,
  400. getValueType: getValueType,
  401. hash: hash$1,
  402. hashArray: hashArray,
  403. hashString: hashString
  404. });
  405. const NodeShaderStage = {
  406. VERTEX: 'vertex',
  407. FRAGMENT: 'fragment'
  408. };
  409. const NodeUpdateType = {
  410. NONE: 'none',
  411. FRAME: 'frame',
  412. RENDER: 'render',
  413. OBJECT: 'object'
  414. };
  415. const NodeType = {
  416. BOOLEAN: 'bool',
  417. INTEGER: 'int',
  418. FLOAT: 'float',
  419. VECTOR2: 'vec2',
  420. VECTOR3: 'vec3',
  421. VECTOR4: 'vec4',
  422. MATRIX2: 'mat2',
  423. MATRIX3: 'mat3',
  424. MATRIX4: 'mat4'
  425. };
  426. const defaultShaderStages = [ 'fragment', 'vertex' ];
  427. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  428. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  429. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  430. let _nodeId = 0;
  431. class Node extends EventDispatcher {
  432. static get type() {
  433. return 'Node';
  434. }
  435. constructor( nodeType = null ) {
  436. super();
  437. this.nodeType = nodeType;
  438. this.updateType = NodeUpdateType.NONE;
  439. this.updateBeforeType = NodeUpdateType.NONE;
  440. this.updateAfterType = NodeUpdateType.NONE;
  441. this.uuid = MathUtils.generateUUID();
  442. this.version = 0;
  443. this._cacheKey = null;
  444. this._cacheKeyVersion = 0;
  445. this.global = false;
  446. this.isNode = true;
  447. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  448. }
  449. set needsUpdate( value ) {
  450. if ( value === true ) {
  451. this.version ++;
  452. }
  453. }
  454. get type() {
  455. return this.constructor.type;
  456. }
  457. onUpdate( callback, updateType ) {
  458. this.updateType = updateType;
  459. this.update = callback.bind( this.getSelf() );
  460. return this;
  461. }
  462. onFrameUpdate( callback ) {
  463. return this.onUpdate( callback, NodeUpdateType.FRAME );
  464. }
  465. onRenderUpdate( callback ) {
  466. return this.onUpdate( callback, NodeUpdateType.RENDER );
  467. }
  468. onObjectUpdate( callback ) {
  469. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  470. }
  471. onReference( callback ) {
  472. this.updateReference = callback.bind( this.getSelf() );
  473. return this;
  474. }
  475. getSelf() {
  476. // Returns non-node object.
  477. return this.self || this;
  478. }
  479. updateReference( /*state*/ ) {
  480. return this;
  481. }
  482. isGlobal( /*builder*/ ) {
  483. return this.global;
  484. }
  485. * getChildren() {
  486. for ( const { childNode } of getNodeChildren( this ) ) {
  487. yield childNode;
  488. }
  489. }
  490. dispose() {
  491. this.dispatchEvent( { type: 'dispose' } );
  492. }
  493. traverse( callback ) {
  494. callback( this );
  495. for ( const childNode of this.getChildren() ) {
  496. childNode.traverse( callback );
  497. }
  498. }
  499. getCacheKey( force = false ) {
  500. force = force || this.version !== this._cacheKeyVersion;
  501. if ( force === true || this._cacheKey === null ) {
  502. this._cacheKey = getCacheKey$1( this, force );
  503. this._cacheKeyVersion = this.version;
  504. }
  505. return this._cacheKey;
  506. }
  507. getScope() {
  508. return this;
  509. }
  510. getHash( /*builder*/ ) {
  511. return this.uuid;
  512. }
  513. getUpdateType() {
  514. return this.updateType;
  515. }
  516. getUpdateBeforeType() {
  517. return this.updateBeforeType;
  518. }
  519. getUpdateAfterType() {
  520. return this.updateAfterType;
  521. }
  522. getElementType( builder ) {
  523. const type = this.getNodeType( builder );
  524. const elementType = builder.getElementType( type );
  525. return elementType;
  526. }
  527. getNodeType( builder ) {
  528. const nodeProperties = builder.getNodeProperties( this );
  529. if ( nodeProperties.outputNode ) {
  530. return nodeProperties.outputNode.getNodeType( builder );
  531. }
  532. return this.nodeType;
  533. }
  534. getShared( builder ) {
  535. const hash = this.getHash( builder );
  536. const nodeFromHash = builder.getNodeFromHash( hash );
  537. return nodeFromHash || this;
  538. }
  539. setup( builder ) {
  540. const nodeProperties = builder.getNodeProperties( this );
  541. let index = 0;
  542. for ( const childNode of this.getChildren() ) {
  543. nodeProperties[ 'node' + index ++ ] = childNode;
  544. }
  545. // return a outputNode if exists
  546. return null;
  547. }
  548. analyze( builder ) {
  549. const usageCount = builder.increaseUsage( this );
  550. if ( usageCount === 1 ) {
  551. // node flow children
  552. const nodeProperties = builder.getNodeProperties( this );
  553. for ( const childNode of Object.values( nodeProperties ) ) {
  554. if ( childNode && childNode.isNode === true ) {
  555. childNode.build( builder );
  556. }
  557. }
  558. }
  559. }
  560. generate( builder, output ) {
  561. const { outputNode } = builder.getNodeProperties( this );
  562. if ( outputNode && outputNode.isNode === true ) {
  563. return outputNode.build( builder, output );
  564. }
  565. }
  566. updateBefore( /*frame*/ ) {
  567. console.warn( 'Abstract function.' );
  568. }
  569. updateAfter( /*frame*/ ) {
  570. console.warn( 'Abstract function.' );
  571. }
  572. update( /*frame*/ ) {
  573. console.warn( 'Abstract function.' );
  574. }
  575. build( builder, output = null ) {
  576. const refNode = this.getShared( builder );
  577. if ( this !== refNode ) {
  578. return refNode.build( builder, output );
  579. }
  580. builder.addNode( this );
  581. builder.addChain( this );
  582. /* Build stages expected results:
  583. - "setup" -> Node
  584. - "analyze" -> null
  585. - "generate" -> String
  586. */
  587. let result = null;
  588. const buildStage = builder.getBuildStage();
  589. if ( buildStage === 'setup' ) {
  590. this.updateReference( builder );
  591. const properties = builder.getNodeProperties( this );
  592. if ( properties.initialized !== true ) {
  593. const stackNodesBeforeSetup = builder.stack.nodes.length;
  594. properties.initialized = true;
  595. properties.outputNode = this.setup( builder );
  596. if ( properties.outputNode !== null && builder.stack.nodes.length !== stackNodesBeforeSetup ) ;
  597. for ( const childNode of Object.values( properties ) ) {
  598. if ( childNode && childNode.isNode === true ) {
  599. childNode.build( builder );
  600. }
  601. }
  602. }
  603. } else if ( buildStage === 'analyze' ) {
  604. this.analyze( builder );
  605. } else if ( buildStage === 'generate' ) {
  606. const isGenerateOnce = this.generate.length === 1;
  607. if ( isGenerateOnce ) {
  608. const type = this.getNodeType( builder );
  609. const nodeData = builder.getDataFromNode( this );
  610. result = nodeData.snippet;
  611. if ( result === undefined ) {
  612. result = this.generate( builder ) || '';
  613. nodeData.snippet = result;
  614. } else if ( nodeData.flowCodes !== undefined && builder.context.nodeBlock !== undefined ) {
  615. builder.addFlowCodeHierarchy( this, builder.context.nodeBlock );
  616. }
  617. result = builder.format( result, type, output );
  618. } else {
  619. result = this.generate( builder, output ) || '';
  620. }
  621. }
  622. builder.removeChain( this );
  623. builder.addSequentialNode( this );
  624. return result;
  625. }
  626. getSerializeChildren() {
  627. return getNodeChildren( this );
  628. }
  629. serialize( json ) {
  630. const nodeChildren = this.getSerializeChildren();
  631. const inputNodes = {};
  632. for ( const { property, index, childNode } of nodeChildren ) {
  633. if ( index !== undefined ) {
  634. if ( inputNodes[ property ] === undefined ) {
  635. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  636. }
  637. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  638. } else {
  639. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  640. }
  641. }
  642. if ( Object.keys( inputNodes ).length > 0 ) {
  643. json.inputNodes = inputNodes;
  644. }
  645. }
  646. deserialize( json ) {
  647. if ( json.inputNodes !== undefined ) {
  648. const nodes = json.meta.nodes;
  649. for ( const property in json.inputNodes ) {
  650. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  651. const inputArray = [];
  652. for ( const uuid of json.inputNodes[ property ] ) {
  653. inputArray.push( nodes[ uuid ] );
  654. }
  655. this[ property ] = inputArray;
  656. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  657. const inputObject = {};
  658. for ( const subProperty in json.inputNodes[ property ] ) {
  659. const uuid = json.inputNodes[ property ][ subProperty ];
  660. inputObject[ subProperty ] = nodes[ uuid ];
  661. }
  662. this[ property ] = inputObject;
  663. } else {
  664. const uuid = json.inputNodes[ property ];
  665. this[ property ] = nodes[ uuid ];
  666. }
  667. }
  668. }
  669. }
  670. toJSON( meta ) {
  671. const { uuid, type } = this;
  672. const isRoot = ( meta === undefined || typeof meta === 'string' );
  673. if ( isRoot ) {
  674. meta = {
  675. textures: {},
  676. images: {},
  677. nodes: {}
  678. };
  679. }
  680. // serialize
  681. let data = meta.nodes[ uuid ];
  682. if ( data === undefined ) {
  683. data = {
  684. uuid,
  685. type,
  686. meta,
  687. metadata: {
  688. version: 4.6,
  689. type: 'Node',
  690. generator: 'Node.toJSON'
  691. }
  692. };
  693. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  694. this.serialize( data );
  695. delete data.meta;
  696. }
  697. // TODO: Copied from Object3D.toJSON
  698. function extractFromCache( cache ) {
  699. const values = [];
  700. for ( const key in cache ) {
  701. const data = cache[ key ];
  702. delete data.metadata;
  703. values.push( data );
  704. }
  705. return values;
  706. }
  707. if ( isRoot ) {
  708. const textures = extractFromCache( meta.textures );
  709. const images = extractFromCache( meta.images );
  710. const nodes = extractFromCache( meta.nodes );
  711. if ( textures.length > 0 ) data.textures = textures;
  712. if ( images.length > 0 ) data.images = images;
  713. if ( nodes.length > 0 ) data.nodes = nodes;
  714. }
  715. return data;
  716. }
  717. }
  718. class ArrayElementNode extends Node {
  719. static get type() {
  720. return 'ArrayElementNode';
  721. } // @TODO: If extending from TempNode it breaks webgpu_compute
  722. constructor( node, indexNode ) {
  723. super();
  724. this.node = node;
  725. this.indexNode = indexNode;
  726. this.isArrayElementNode = true;
  727. }
  728. getNodeType( builder ) {
  729. return this.node.getElementType( builder );
  730. }
  731. generate( builder ) {
  732. const nodeSnippet = this.node.build( builder );
  733. const indexSnippet = this.indexNode.build( builder, 'uint' );
  734. return `${nodeSnippet}[ ${indexSnippet} ]`;
  735. }
  736. }
  737. class ConvertNode extends Node {
  738. static get type() {
  739. return 'ConvertNode';
  740. }
  741. constructor( node, convertTo ) {
  742. super();
  743. this.node = node;
  744. this.convertTo = convertTo;
  745. }
  746. getNodeType( builder ) {
  747. const requestType = this.node.getNodeType( builder );
  748. let convertTo = null;
  749. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  750. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  751. convertTo = overloadingType;
  752. }
  753. }
  754. return convertTo;
  755. }
  756. serialize( data ) {
  757. super.serialize( data );
  758. data.convertTo = this.convertTo;
  759. }
  760. deserialize( data ) {
  761. super.deserialize( data );
  762. this.convertTo = data.convertTo;
  763. }
  764. generate( builder, output ) {
  765. const node = this.node;
  766. const type = this.getNodeType( builder );
  767. const snippet = node.build( builder, type );
  768. return builder.format( snippet, type, output );
  769. }
  770. }
  771. class TempNode extends Node {
  772. static get type() {
  773. return 'TempNode';
  774. }
  775. constructor( type ) {
  776. super( type );
  777. this.isTempNode = true;
  778. }
  779. hasDependencies( builder ) {
  780. return builder.getDataFromNode( this ).usageCount > 1;
  781. }
  782. build( builder, output ) {
  783. const buildStage = builder.getBuildStage();
  784. if ( buildStage === 'generate' ) {
  785. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  786. const nodeData = builder.getDataFromNode( this );
  787. if ( nodeData.propertyName !== undefined ) {
  788. return builder.format( nodeData.propertyName, type, output );
  789. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  790. const snippet = super.build( builder, type );
  791. const nodeVar = builder.getVarFromNode( this, null, type );
  792. const propertyName = builder.getPropertyName( nodeVar );
  793. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  794. nodeData.snippet = snippet;
  795. nodeData.propertyName = propertyName;
  796. return builder.format( nodeData.propertyName, type, output );
  797. }
  798. }
  799. return super.build( builder, output );
  800. }
  801. }
  802. class JoinNode extends TempNode {
  803. static get type() {
  804. return 'JoinNode';
  805. }
  806. constructor( nodes = [], nodeType = null ) {
  807. super( nodeType );
  808. this.nodes = nodes;
  809. }
  810. getNodeType( builder ) {
  811. if ( this.nodeType !== null ) {
  812. return builder.getVectorType( this.nodeType );
  813. }
  814. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  815. }
  816. generate( builder, output ) {
  817. const type = this.getNodeType( builder );
  818. const nodes = this.nodes;
  819. const primitiveType = builder.getComponentType( type );
  820. const snippetValues = [];
  821. for ( const input of nodes ) {
  822. let inputSnippet = input.build( builder );
  823. const inputPrimitiveType = builder.getComponentType( input.getNodeType( builder ) );
  824. if ( inputPrimitiveType !== primitiveType ) {
  825. inputSnippet = builder.format( inputSnippet, inputPrimitiveType, primitiveType );
  826. }
  827. snippetValues.push( inputSnippet );
  828. }
  829. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  830. return builder.format( snippet, type, output );
  831. }
  832. }
  833. const stringVectorComponents = vectorComponents.join( '' );
  834. class SplitNode extends Node {
  835. static get type() {
  836. return 'SplitNode';
  837. }
  838. constructor( node, components = 'x' ) {
  839. super();
  840. this.node = node;
  841. this.components = components;
  842. this.isSplitNode = true;
  843. }
  844. getVectorLength() {
  845. let vectorLength = this.components.length;
  846. for ( const c of this.components ) {
  847. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  848. }
  849. return vectorLength;
  850. }
  851. getComponentType( builder ) {
  852. return builder.getComponentType( this.node.getNodeType( builder ) );
  853. }
  854. getNodeType( builder ) {
  855. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  856. }
  857. generate( builder, output ) {
  858. const node = this.node;
  859. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  860. let snippet = null;
  861. if ( nodeTypeLength > 1 ) {
  862. let type = null;
  863. const componentsLength = this.getVectorLength();
  864. if ( componentsLength >= nodeTypeLength ) {
  865. // needed expand the input node
  866. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  867. }
  868. const nodeSnippet = node.build( builder, type );
  869. if ( this.components.length === nodeTypeLength && this.components === stringVectorComponents.slice( 0, this.components.length ) ) {
  870. // unnecessary swizzle
  871. snippet = builder.format( nodeSnippet, type, output );
  872. } else {
  873. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  874. }
  875. } else {
  876. // ignore .components if .node returns float/integer
  877. snippet = node.build( builder, output );
  878. }
  879. return snippet;
  880. }
  881. serialize( data ) {
  882. super.serialize( data );
  883. data.components = this.components;
  884. }
  885. deserialize( data ) {
  886. super.deserialize( data );
  887. this.components = data.components;
  888. }
  889. }
  890. class SetNode extends TempNode {
  891. static get type() {
  892. return 'SetNode';
  893. }
  894. constructor( sourceNode, components, targetNode ) {
  895. super();
  896. this.sourceNode = sourceNode;
  897. this.components = components;
  898. this.targetNode = targetNode;
  899. }
  900. getNodeType( builder ) {
  901. return this.sourceNode.getNodeType( builder );
  902. }
  903. generate( builder ) {
  904. const { sourceNode, components, targetNode } = this;
  905. const sourceType = this.getNodeType( builder );
  906. const targetType = builder.getTypeFromLength( components.length, targetNode.getNodeType( builder ) );
  907. const targetSnippet = targetNode.build( builder, targetType );
  908. const sourceSnippet = sourceNode.build( builder, sourceType );
  909. const length = builder.getTypeLength( sourceType );
  910. const snippetValues = [];
  911. for ( let i = 0; i < length; i ++ ) {
  912. const component = vectorComponents[ i ];
  913. if ( component === components[ 0 ] ) {
  914. snippetValues.push( targetSnippet );
  915. i += components.length - 1;
  916. } else {
  917. snippetValues.push( sourceSnippet + '.' + component );
  918. }
  919. }
  920. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  921. }
  922. }
  923. class FlipNode extends TempNode {
  924. static get type() {
  925. return 'FlipNode';
  926. }
  927. constructor( sourceNode, components ) {
  928. super();
  929. this.sourceNode = sourceNode;
  930. this.components = components;
  931. }
  932. getNodeType( builder ) {
  933. return this.sourceNode.getNodeType( builder );
  934. }
  935. generate( builder ) {
  936. const { components, sourceNode } = this;
  937. const sourceType = this.getNodeType( builder );
  938. const sourceSnippet = sourceNode.build( builder );
  939. const sourceCache = builder.getVarFromNode( this );
  940. const sourceProperty = builder.getPropertyName( sourceCache );
  941. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  942. const length = builder.getTypeLength( sourceType );
  943. const snippetValues = [];
  944. let componentIndex = 0;
  945. for ( let i = 0; i < length; i ++ ) {
  946. const component = vectorComponents[ i ];
  947. if ( component === components[ componentIndex ] ) {
  948. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  949. componentIndex ++;
  950. } else {
  951. snippetValues.push( sourceProperty + '.' + component );
  952. }
  953. }
  954. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  955. }
  956. }
  957. class InputNode extends Node {
  958. static get type() {
  959. return 'InputNode';
  960. }
  961. constructor( value, nodeType = null ) {
  962. super( nodeType );
  963. this.isInputNode = true;
  964. this.value = value;
  965. this.precision = null;
  966. }
  967. getNodeType( /*builder*/ ) {
  968. if ( this.nodeType === null ) {
  969. return getValueType( this.value );
  970. }
  971. return this.nodeType;
  972. }
  973. getInputType( builder ) {
  974. return this.getNodeType( builder );
  975. }
  976. setPrecision( precision ) {
  977. this.precision = precision;
  978. return this;
  979. }
  980. serialize( data ) {
  981. super.serialize( data );
  982. data.value = this.value;
  983. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  984. data.valueType = getValueType( this.value );
  985. data.nodeType = this.nodeType;
  986. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  987. data.precision = this.precision;
  988. }
  989. deserialize( data ) {
  990. super.deserialize( data );
  991. this.nodeType = data.nodeType;
  992. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  993. this.precision = data.precision || null;
  994. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  995. }
  996. generate( /*builder, output*/ ) {
  997. console.warn( 'Abstract function.' );
  998. }
  999. }
  1000. class ConstNode extends InputNode {
  1001. static get type() {
  1002. return 'ConstNode';
  1003. }
  1004. constructor( value, nodeType = null ) {
  1005. super( value, nodeType );
  1006. this.isConstNode = true;
  1007. }
  1008. generateConst( builder ) {
  1009. return builder.generateConst( this.getNodeType( builder ), this.value );
  1010. }
  1011. generate( builder, output ) {
  1012. const type = this.getNodeType( builder );
  1013. return builder.format( this.generateConst( builder ), type, output );
  1014. }
  1015. }
  1016. //
  1017. let currentStack = null;
  1018. const NodeElements = new Map();
  1019. function addMethodChaining( name, nodeElement ) {
  1020. if ( NodeElements.has( name ) ) {
  1021. console.warn( `Redefinition of method chaining ${ name }` );
  1022. return;
  1023. }
  1024. if ( typeof nodeElement !== 'function' ) throw new Error( `Node element ${ name } is not a function` );
  1025. NodeElements.set( name, nodeElement );
  1026. }
  1027. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  1028. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  1029. const shaderNodeHandler = {
  1030. setup( NodeClosure, params ) {
  1031. const inputs = params.shift();
  1032. return NodeClosure( nodeObjects( inputs ), ...params );
  1033. },
  1034. get( node, prop, nodeObj ) {
  1035. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  1036. if ( node.isStackNode !== true && prop === 'assign' ) {
  1037. return ( ...params ) => {
  1038. currentStack.assign( nodeObj, ...params );
  1039. return nodeObj;
  1040. };
  1041. } else if ( NodeElements.has( prop ) ) {
  1042. const nodeElement = NodeElements.get( prop );
  1043. return node.isStackNode ? ( ...params ) => nodeObj.add( nodeElement( ...params ) ) : ( ...params ) => nodeElement( nodeObj, ...params );
  1044. } else if ( prop === 'self' ) {
  1045. return node;
  1046. } else if ( prop.endsWith( 'Assign' ) && NodeElements.has( prop.slice( 0, prop.length - 'Assign'.length ) ) ) {
  1047. const nodeElement = NodeElements.get( prop.slice( 0, prop.length - 'Assign'.length ) );
  1048. return node.isStackNode ? ( ...params ) => nodeObj.assign( params[ 0 ], nodeElement( ...params ) ) : ( ...params ) => nodeObj.assign( nodeElement( nodeObj, ...params ) );
  1049. } else if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true ) {
  1050. // accessing properties ( swizzle )
  1051. prop = parseSwizzle( prop );
  1052. return nodeObject( new SplitNode( nodeObj, prop ) );
  1053. } else if ( /^set[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  1054. // set properties ( swizzle ) and sort to xyzw sequence
  1055. prop = parseSwizzleAndSort( prop.slice( 3 ).toLowerCase() );
  1056. return ( value ) => nodeObject( new SetNode( node, prop, value ) );
  1057. } else if ( /^flip[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  1058. // set properties ( swizzle ) and sort to xyzw sequence
  1059. prop = parseSwizzleAndSort( prop.slice( 4 ).toLowerCase() );
  1060. return () => nodeObject( new FlipNode( nodeObject( node ), prop ) );
  1061. } else if ( prop === 'width' || prop === 'height' || prop === 'depth' ) {
  1062. // accessing property
  1063. if ( prop === 'width' ) prop = 'x';
  1064. else if ( prop === 'height' ) prop = 'y';
  1065. else if ( prop === 'depth' ) prop = 'z';
  1066. return nodeObject( new SplitNode( node, prop ) );
  1067. } else if ( /^\d+$/.test( prop ) === true ) {
  1068. // accessing array
  1069. return nodeObject( new ArrayElementNode( nodeObj, new ConstNode( Number( prop ), 'uint' ) ) );
  1070. }
  1071. }
  1072. return Reflect.get( node, prop, nodeObj );
  1073. },
  1074. set( node, prop, value, nodeObj ) {
  1075. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  1076. // setting properties
  1077. if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true || prop === 'width' || prop === 'height' || prop === 'depth' || /^\d+$/.test( prop ) === true ) {
  1078. nodeObj[ prop ].assign( value );
  1079. return true;
  1080. }
  1081. }
  1082. return Reflect.set( node, prop, value, nodeObj );
  1083. }
  1084. };
  1085. const nodeObjectsCacheMap = new WeakMap();
  1086. const nodeBuilderFunctionsCacheMap = new WeakMap();
  1087. const ShaderNodeObject = function ( obj, altType = null ) {
  1088. const type = getValueType( obj );
  1089. if ( type === 'node' ) {
  1090. let nodeObject = nodeObjectsCacheMap.get( obj );
  1091. if ( nodeObject === undefined ) {
  1092. nodeObject = new Proxy( obj, shaderNodeHandler );
  1093. nodeObjectsCacheMap.set( obj, nodeObject );
  1094. nodeObjectsCacheMap.set( nodeObject, nodeObject );
  1095. }
  1096. return nodeObject;
  1097. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  1098. return nodeObject( getConstNode( obj, altType ) );
  1099. } else if ( type === 'shader' ) {
  1100. return Fn( obj );
  1101. }
  1102. return obj;
  1103. };
  1104. const ShaderNodeObjects = function ( objects, altType = null ) {
  1105. for ( const name in objects ) {
  1106. objects[ name ] = nodeObject( objects[ name ], altType );
  1107. }
  1108. return objects;
  1109. };
  1110. const ShaderNodeArray = function ( array, altType = null ) {
  1111. const len = array.length;
  1112. for ( let i = 0; i < len; i ++ ) {
  1113. array[ i ] = nodeObject( array[ i ], altType );
  1114. }
  1115. return array;
  1116. };
  1117. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  1118. const assignNode = ( node ) => nodeObject( settings !== null ? Object.assign( node, settings ) : node );
  1119. if ( scope === null ) {
  1120. return ( ...params ) => {
  1121. return assignNode( new NodeClass( ...nodeArray( params ) ) );
  1122. };
  1123. } else if ( factor !== null ) {
  1124. factor = nodeObject( factor );
  1125. return ( ...params ) => {
  1126. return assignNode( new NodeClass( scope, ...nodeArray( params ), factor ) );
  1127. };
  1128. } else {
  1129. return ( ...params ) => {
  1130. return assignNode( new NodeClass( scope, ...nodeArray( params ) ) );
  1131. };
  1132. }
  1133. };
  1134. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  1135. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  1136. };
  1137. class ShaderCallNodeInternal extends Node {
  1138. constructor( shaderNode, inputNodes ) {
  1139. super();
  1140. this.shaderNode = shaderNode;
  1141. this.inputNodes = inputNodes;
  1142. }
  1143. getNodeType( builder ) {
  1144. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  1145. }
  1146. call( builder ) {
  1147. const { shaderNode, inputNodes } = this;
  1148. const properties = builder.getNodeProperties( shaderNode );
  1149. if ( properties.onceOutput ) return properties.onceOutput;
  1150. //
  1151. let result = null;
  1152. if ( shaderNode.layout ) {
  1153. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  1154. if ( functionNodesCacheMap === undefined ) {
  1155. functionNodesCacheMap = new WeakMap();
  1156. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  1157. }
  1158. let functionNode = functionNodesCacheMap.get( shaderNode );
  1159. if ( functionNode === undefined ) {
  1160. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  1161. functionNodesCacheMap.set( shaderNode, functionNode );
  1162. }
  1163. if ( builder.currentFunctionNode !== null ) {
  1164. builder.currentFunctionNode.includes.push( functionNode );
  1165. }
  1166. result = nodeObject( functionNode.call( inputNodes ) );
  1167. } else {
  1168. const jsFunc = shaderNode.jsFunc;
  1169. const outputNode = inputNodes !== null ? jsFunc( inputNodes, builder ) : jsFunc( builder );
  1170. result = nodeObject( outputNode );
  1171. }
  1172. if ( shaderNode.once ) {
  1173. properties.onceOutput = result;
  1174. }
  1175. return result;
  1176. }
  1177. getOutputNode( builder ) {
  1178. const properties = builder.getNodeProperties( this );
  1179. if ( properties.outputNode === null ) {
  1180. properties.outputNode = this.setupOutput( builder );
  1181. }
  1182. return properties.outputNode;
  1183. }
  1184. setup( builder ) {
  1185. return this.getOutputNode( builder );
  1186. }
  1187. setupOutput( builder ) {
  1188. builder.addStack();
  1189. builder.stack.outputNode = this.call( builder );
  1190. return builder.removeStack();
  1191. }
  1192. generate( builder, output ) {
  1193. const outputNode = this.getOutputNode( builder );
  1194. return outputNode.build( builder, output );
  1195. }
  1196. }
  1197. class ShaderNodeInternal extends Node {
  1198. constructor( jsFunc, nodeType ) {
  1199. super( nodeType );
  1200. this.jsFunc = jsFunc;
  1201. this.layout = null;
  1202. this.global = true;
  1203. this.once = false;
  1204. }
  1205. setLayout( layout ) {
  1206. this.layout = layout;
  1207. return this;
  1208. }
  1209. call( inputs = null ) {
  1210. nodeObjects( inputs );
  1211. return nodeObject( new ShaderCallNodeInternal( this, inputs ) );
  1212. }
  1213. setup() {
  1214. return this.call();
  1215. }
  1216. }
  1217. const bools = [ false, true ];
  1218. const uints = [ 0, 1, 2, 3 ];
  1219. const ints = [ - 1, - 2 ];
  1220. 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 ];
  1221. const boolsCacheMap = new Map();
  1222. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  1223. const uintsCacheMap = new Map();
  1224. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  1225. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  1226. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  1227. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  1228. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  1229. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  1230. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  1231. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  1232. const getConstNode = ( value, type ) => {
  1233. if ( constNodesCacheMap.has( value ) ) {
  1234. return constNodesCacheMap.get( value );
  1235. } else if ( value.isNode === true ) {
  1236. return value;
  1237. } else {
  1238. return new ConstNode( value, type );
  1239. }
  1240. };
  1241. const safeGetNodeType = ( node ) => {
  1242. try {
  1243. return node.getNodeType();
  1244. } catch ( _ ) {
  1245. return undefined;
  1246. }
  1247. };
  1248. const ConvertType = function ( type, cacheMap = null ) {
  1249. return ( ...params ) => {
  1250. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => typeof param !== 'object' ) ) ) {
  1251. params = [ getValueFromType( type, ...params ) ];
  1252. }
  1253. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  1254. return nodeObject( cacheMap.get( params[ 0 ] ) );
  1255. }
  1256. if ( params.length === 1 ) {
  1257. const node = getConstNode( params[ 0 ], type );
  1258. if ( safeGetNodeType( node ) === type ) return nodeObject( node );
  1259. return nodeObject( new ConvertNode( node, type ) );
  1260. }
  1261. const nodes = params.map( param => getConstNode( param ) );
  1262. return nodeObject( new JoinNode( nodes, type ) );
  1263. };
  1264. };
  1265. // exports
  1266. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  1267. // utils
  1268. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  1269. // shader node base
  1270. function ShaderNode( jsFunc, nodeType ) {
  1271. return new Proxy( new ShaderNodeInternal( jsFunc, nodeType ), shaderNodeHandler );
  1272. }
  1273. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  1274. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  1275. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  1276. const nodeProxy = ( ...params ) => new ShaderNodeProxy( ...params );
  1277. const nodeImmutable = ( ...params ) => new ShaderNodeImmutable( ...params );
  1278. const Fn = ( jsFunc, nodeType ) => {
  1279. const shaderNode = new ShaderNode( jsFunc, nodeType );
  1280. const fn = ( ...params ) => {
  1281. let inputs;
  1282. nodeObjects( params );
  1283. if ( params[ 0 ] && params[ 0 ].isNode ) {
  1284. inputs = [ ...params ];
  1285. } else {
  1286. inputs = params[ 0 ];
  1287. }
  1288. return shaderNode.call( inputs );
  1289. };
  1290. fn.shaderNode = shaderNode;
  1291. fn.setLayout = ( layout ) => {
  1292. shaderNode.setLayout( layout );
  1293. return fn;
  1294. };
  1295. fn.once = () => {
  1296. shaderNode.once = true;
  1297. return fn;
  1298. };
  1299. return fn;
  1300. };
  1301. const tslFn = ( ...params ) => { // @deprecated, r168
  1302. console.warn( 'TSL.ShaderNode: tslFn() has been renamed to Fn().' );
  1303. return Fn( ...params );
  1304. };
  1305. //
  1306. addMethodChaining( 'toGlobal', ( node ) => {
  1307. node.global = true;
  1308. return node;
  1309. } );
  1310. //
  1311. const setCurrentStack = ( stack ) => {
  1312. currentStack = stack;
  1313. };
  1314. const getCurrentStack = () => currentStack;
  1315. const If = ( ...params ) => currentStack.If( ...params );
  1316. function append( node ) {
  1317. if ( currentStack ) currentStack.add( node );
  1318. return node;
  1319. }
  1320. addMethodChaining( 'append', append );
  1321. // types
  1322. const color = new ConvertType( 'color' );
  1323. const float = new ConvertType( 'float', cacheMaps.float );
  1324. const int = new ConvertType( 'int', cacheMaps.ints );
  1325. const uint = new ConvertType( 'uint', cacheMaps.uint );
  1326. const bool = new ConvertType( 'bool', cacheMaps.bool );
  1327. const vec2 = new ConvertType( 'vec2' );
  1328. const ivec2 = new ConvertType( 'ivec2' );
  1329. const uvec2 = new ConvertType( 'uvec2' );
  1330. const bvec2 = new ConvertType( 'bvec2' );
  1331. const vec3 = new ConvertType( 'vec3' );
  1332. const ivec3 = new ConvertType( 'ivec3' );
  1333. const uvec3 = new ConvertType( 'uvec3' );
  1334. const bvec3 = new ConvertType( 'bvec3' );
  1335. const vec4 = new ConvertType( 'vec4' );
  1336. const ivec4 = new ConvertType( 'ivec4' );
  1337. const uvec4 = new ConvertType( 'uvec4' );
  1338. const bvec4 = new ConvertType( 'bvec4' );
  1339. const mat2 = new ConvertType( 'mat2' );
  1340. const mat3 = new ConvertType( 'mat3' );
  1341. const mat4 = new ConvertType( 'mat4' );
  1342. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  1343. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  1344. addMethodChaining( 'toColor', color );
  1345. addMethodChaining( 'toFloat', float );
  1346. addMethodChaining( 'toInt', int );
  1347. addMethodChaining( 'toUint', uint );
  1348. addMethodChaining( 'toBool', bool );
  1349. addMethodChaining( 'toVec2', vec2 );
  1350. addMethodChaining( 'toIVec2', ivec2 );
  1351. addMethodChaining( 'toUVec2', uvec2 );
  1352. addMethodChaining( 'toBVec2', bvec2 );
  1353. addMethodChaining( 'toVec3', vec3 );
  1354. addMethodChaining( 'toIVec3', ivec3 );
  1355. addMethodChaining( 'toUVec3', uvec3 );
  1356. addMethodChaining( 'toBVec3', bvec3 );
  1357. addMethodChaining( 'toVec4', vec4 );
  1358. addMethodChaining( 'toIVec4', ivec4 );
  1359. addMethodChaining( 'toUVec4', uvec4 );
  1360. addMethodChaining( 'toBVec4', bvec4 );
  1361. addMethodChaining( 'toMat2', mat2 );
  1362. addMethodChaining( 'toMat3', mat3 );
  1363. addMethodChaining( 'toMat4', mat4 );
  1364. // basic nodes
  1365. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode );
  1366. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  1367. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  1368. addMethodChaining( 'element', element );
  1369. addMethodChaining( 'convert', convert );
  1370. class UniformGroupNode extends Node {
  1371. static get type() {
  1372. return 'UniformGroupNode';
  1373. }
  1374. constructor( name, shared = false, order = 1 ) {
  1375. super( 'string' );
  1376. this.name = name;
  1377. this.version = 0;
  1378. this.shared = shared;
  1379. this.order = order;
  1380. this.isUniformGroup = true;
  1381. }
  1382. set needsUpdate( value ) {
  1383. if ( value === true ) this.version ++;
  1384. }
  1385. serialize( data ) {
  1386. super.serialize( data );
  1387. data.name = this.name;
  1388. data.version = this.version;
  1389. data.shared = this.shared;
  1390. }
  1391. deserialize( data ) {
  1392. super.deserialize( data );
  1393. this.name = data.name;
  1394. this.version = data.version;
  1395. this.shared = data.shared;
  1396. }
  1397. }
  1398. const uniformGroup = ( name ) => new UniformGroupNode( name );
  1399. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  1400. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  1401. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  1402. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  1403. class UniformNode extends InputNode {
  1404. static get type() {
  1405. return 'UniformNode';
  1406. }
  1407. constructor( value, nodeType = null ) {
  1408. super( value, nodeType );
  1409. this.isUniformNode = true;
  1410. this.name = '';
  1411. this.groupNode = objectGroup;
  1412. }
  1413. label( name ) {
  1414. this.name = name;
  1415. return this;
  1416. }
  1417. setGroup( group ) {
  1418. this.groupNode = group;
  1419. return this;
  1420. }
  1421. getGroup() {
  1422. return this.groupNode;
  1423. }
  1424. getUniformHash( builder ) {
  1425. return this.getHash( builder );
  1426. }
  1427. onUpdate( callback, updateType ) {
  1428. const self = this.getSelf();
  1429. callback = callback.bind( self );
  1430. return super.onUpdate( ( frame ) => {
  1431. const value = callback( frame, self );
  1432. if ( value !== undefined ) {
  1433. this.value = value;
  1434. }
  1435. }, updateType );
  1436. }
  1437. generate( builder, output ) {
  1438. const type = this.getNodeType( builder );
  1439. const hash = this.getUniformHash( builder );
  1440. let sharedNode = builder.getNodeFromHash( hash );
  1441. if ( sharedNode === undefined ) {
  1442. builder.setHashNode( this, hash );
  1443. sharedNode = this;
  1444. }
  1445. const sharedNodeType = sharedNode.getInputType( builder );
  1446. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.label );
  1447. const propertyName = builder.getPropertyName( nodeUniform );
  1448. if ( builder.context.label !== undefined ) delete builder.context.label;
  1449. return builder.format( propertyName, type, output );
  1450. }
  1451. }
  1452. const uniform = ( arg1, arg2 ) => {
  1453. const nodeType = getConstNodeType( arg2 || arg1 );
  1454. // @TODO: get ConstNode from .traverse() in the future
  1455. const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1;
  1456. return nodeObject( new UniformNode( value, nodeType ) );
  1457. };
  1458. class PropertyNode extends Node {
  1459. static get type() {
  1460. return 'PropertyNode';
  1461. }
  1462. constructor( nodeType, name = null, varying = false ) {
  1463. super( nodeType );
  1464. this.name = name;
  1465. this.varying = varying;
  1466. this.isPropertyNode = true;
  1467. }
  1468. getHash( builder ) {
  1469. return this.name || super.getHash( builder );
  1470. }
  1471. isGlobal( /*builder*/ ) {
  1472. return true;
  1473. }
  1474. generate( builder ) {
  1475. let nodeVar;
  1476. if ( this.varying === true ) {
  1477. nodeVar = builder.getVaryingFromNode( this, this.name );
  1478. nodeVar.needsInterpolation = true;
  1479. } else {
  1480. nodeVar = builder.getVarFromNode( this, this.name );
  1481. }
  1482. return builder.getPropertyName( nodeVar );
  1483. }
  1484. }
  1485. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  1486. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  1487. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  1488. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  1489. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  1490. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  1491. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  1492. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  1493. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  1494. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  1495. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  1496. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  1497. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  1498. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  1499. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  1500. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  1501. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  1502. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  1503. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  1504. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  1505. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  1506. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  1507. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  1508. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  1509. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  1510. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  1511. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  1512. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  1513. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  1514. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  1515. class AssignNode extends TempNode {
  1516. static get type() {
  1517. return 'AssignNode';
  1518. }
  1519. constructor( targetNode, sourceNode ) {
  1520. super();
  1521. this.targetNode = targetNode;
  1522. this.sourceNode = sourceNode;
  1523. }
  1524. hasDependencies() {
  1525. return false;
  1526. }
  1527. getNodeType( builder, output ) {
  1528. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  1529. }
  1530. needsSplitAssign( builder ) {
  1531. const { targetNode } = this;
  1532. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  1533. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  1534. const assignDiferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  1535. return assignDiferentVector;
  1536. }
  1537. return false;
  1538. }
  1539. generate( builder, output ) {
  1540. const { targetNode, sourceNode } = this;
  1541. const needsSplitAssign = this.needsSplitAssign( builder );
  1542. const targetType = targetNode.getNodeType( builder );
  1543. const target = targetNode.context( { assign: true } ).build( builder );
  1544. const source = sourceNode.build( builder, targetType );
  1545. const sourceType = sourceNode.getNodeType( builder );
  1546. const nodeData = builder.getDataFromNode( this );
  1547. //
  1548. let snippet;
  1549. if ( nodeData.initialized === true ) {
  1550. if ( output !== 'void' ) {
  1551. snippet = target;
  1552. }
  1553. } else if ( needsSplitAssign ) {
  1554. const sourceVar = builder.getVarFromNode( this, null, targetType );
  1555. const sourceProperty = builder.getPropertyName( sourceVar );
  1556. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  1557. const targetRoot = targetNode.node.context( { assign: true } ).build( builder );
  1558. for ( let i = 0; i < targetNode.components.length; i ++ ) {
  1559. const component = targetNode.components[ i ];
  1560. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  1561. }
  1562. if ( output !== 'void' ) {
  1563. snippet = target;
  1564. }
  1565. } else {
  1566. snippet = `${ target } = ${ source }`;
  1567. if ( output === 'void' || sourceType === 'void' ) {
  1568. builder.addLineFlowCode( snippet, this );
  1569. if ( output !== 'void' ) {
  1570. snippet = target;
  1571. }
  1572. }
  1573. }
  1574. nodeData.initialized = true;
  1575. return builder.format( snippet, targetType, output );
  1576. }
  1577. }
  1578. const assign = /*@__PURE__*/ nodeProxy( AssignNode );
  1579. addMethodChaining( 'assign', assign );
  1580. class FunctionCallNode extends TempNode {
  1581. static get type() {
  1582. return 'FunctionCallNode';
  1583. }
  1584. constructor( functionNode = null, parameters = {} ) {
  1585. super();
  1586. this.functionNode = functionNode;
  1587. this.parameters = parameters;
  1588. }
  1589. setParameters( parameters ) {
  1590. this.parameters = parameters;
  1591. return this;
  1592. }
  1593. getParameters() {
  1594. return this.parameters;
  1595. }
  1596. getNodeType( builder ) {
  1597. return this.functionNode.getNodeType( builder );
  1598. }
  1599. generate( builder ) {
  1600. const params = [];
  1601. const functionNode = this.functionNode;
  1602. const inputs = functionNode.getInputs( builder );
  1603. const parameters = this.parameters;
  1604. const generateInput = ( node, inputNode ) => {
  1605. const type = inputNode.type;
  1606. const pointer = type === 'pointer';
  1607. let output;
  1608. if ( pointer ) output = '&' + node.build( builder );
  1609. else output = node.build( builder, type );
  1610. return output;
  1611. };
  1612. if ( Array.isArray( parameters ) ) {
  1613. for ( let i = 0; i < parameters.length; i ++ ) {
  1614. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  1615. }
  1616. } else {
  1617. for ( const inputNode of inputs ) {
  1618. const node = parameters[ inputNode.name ];
  1619. if ( node !== undefined ) {
  1620. params.push( generateInput( node, inputNode ) );
  1621. } else {
  1622. throw new Error( `FunctionCallNode: Input '${inputNode.name}' not found in FunctionNode.` );
  1623. }
  1624. }
  1625. }
  1626. const functionName = functionNode.build( builder, 'property' );
  1627. return `${functionName}( ${params.join( ', ' )} )`;
  1628. }
  1629. }
  1630. const call = ( func, ...params ) => {
  1631. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  1632. return nodeObject( new FunctionCallNode( nodeObject( func ), params ) );
  1633. };
  1634. addMethodChaining( 'call', call );
  1635. class OperatorNode extends TempNode {
  1636. static get type() {
  1637. return 'OperatorNode';
  1638. }
  1639. constructor( op, aNode, bNode, ...params ) {
  1640. super();
  1641. if ( params.length > 0 ) {
  1642. let finalOp = new OperatorNode( op, aNode, bNode );
  1643. for ( let i = 0; i < params.length - 1; i ++ ) {
  1644. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  1645. }
  1646. aNode = finalOp;
  1647. bNode = params[ params.length - 1 ];
  1648. }
  1649. this.op = op;
  1650. this.aNode = aNode;
  1651. this.bNode = bNode;
  1652. }
  1653. getNodeType( builder, output ) {
  1654. const op = this.op;
  1655. const aNode = this.aNode;
  1656. const bNode = this.bNode;
  1657. const typeA = aNode.getNodeType( builder );
  1658. const typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  1659. if ( typeA === 'void' || typeB === 'void' ) {
  1660. return 'void';
  1661. } else if ( op === '%' ) {
  1662. return typeA;
  1663. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  1664. return builder.getIntegerType( typeA );
  1665. } else if ( op === '!' || op === '==' || op === '&&' || op === '||' || op === '^^' ) {
  1666. return 'bool';
  1667. } else if ( op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  1668. const typeLength = output ? builder.getTypeLength( output ) : Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  1669. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  1670. } else {
  1671. if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  1672. return typeB;
  1673. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  1674. // matrix x vector
  1675. return builder.getVectorFromMatrix( typeA );
  1676. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  1677. // vector x matrix
  1678. return builder.getVectorFromMatrix( typeB );
  1679. } else if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  1680. // anytype x anytype: use the greater length vector
  1681. return typeB;
  1682. }
  1683. return typeA;
  1684. }
  1685. }
  1686. generate( builder, output ) {
  1687. const op = this.op;
  1688. const aNode = this.aNode;
  1689. const bNode = this.bNode;
  1690. const type = this.getNodeType( builder, output );
  1691. let typeA = null;
  1692. let typeB = null;
  1693. if ( type !== 'void' ) {
  1694. typeA = aNode.getNodeType( builder );
  1695. typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  1696. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' ) {
  1697. if ( builder.isVector( typeA ) ) {
  1698. typeB = typeA;
  1699. } else if ( typeA !== typeB ) {
  1700. typeA = typeB = 'float';
  1701. }
  1702. } else if ( op === '>>' || op === '<<' ) {
  1703. typeA = type;
  1704. typeB = builder.changeComponentType( typeB, 'uint' );
  1705. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  1706. // matrix x vector
  1707. typeB = builder.getVectorFromMatrix( typeA );
  1708. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  1709. // vector x matrix
  1710. typeA = builder.getVectorFromMatrix( typeB );
  1711. } else {
  1712. // anytype x anytype
  1713. typeA = typeB = type;
  1714. }
  1715. } else {
  1716. typeA = typeB = type;
  1717. }
  1718. const a = aNode.build( builder, typeA );
  1719. const b = typeof bNode !== 'undefined' ? bNode.build( builder, typeB ) : null;
  1720. const outputLength = builder.getTypeLength( output );
  1721. const fnOpSnippet = builder.getFunctionOperator( op );
  1722. if ( output !== 'void' ) {
  1723. if ( op === '<' && outputLength > 1 ) {
  1724. if ( builder.useComparisonMethod ) {
  1725. return builder.format( `${ builder.getMethod( 'lessThan', output ) }( ${ a }, ${ b } )`, type, output );
  1726. } else {
  1727. return builder.format( `( ${ a } < ${ b } )`, type, output );
  1728. }
  1729. } else if ( op === '<=' && outputLength > 1 ) {
  1730. if ( builder.useComparisonMethod ) {
  1731. return builder.format( `${ builder.getMethod( 'lessThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  1732. } else {
  1733. return builder.format( `( ${ a } <= ${ b } )`, type, output );
  1734. }
  1735. } else if ( op === '>' && outputLength > 1 ) {
  1736. if ( builder.useComparisonMethod ) {
  1737. return builder.format( `${ builder.getMethod( 'greaterThan', output ) }( ${ a }, ${ b } )`, type, output );
  1738. } else {
  1739. return builder.format( `( ${ a } > ${ b } )`, type, output );
  1740. }
  1741. } else if ( op === '>=' && outputLength > 1 ) {
  1742. if ( builder.useComparisonMethod ) {
  1743. return builder.format( `${ builder.getMethod( 'greaterThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  1744. } else {
  1745. return builder.format( `( ${ a } >= ${ b } )`, type, output );
  1746. }
  1747. } else if ( op === '!' || op === '~' ) {
  1748. return builder.format( `(${op}${a})`, typeA, output );
  1749. } else if ( fnOpSnippet ) {
  1750. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  1751. } else {
  1752. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  1753. }
  1754. } else if ( typeA !== 'void' ) {
  1755. if ( fnOpSnippet ) {
  1756. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  1757. } else {
  1758. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  1759. }
  1760. }
  1761. }
  1762. serialize( data ) {
  1763. super.serialize( data );
  1764. data.op = this.op;
  1765. }
  1766. deserialize( data ) {
  1767. super.deserialize( data );
  1768. this.op = data.op;
  1769. }
  1770. }
  1771. const add = /*@__PURE__*/ nodeProxy( OperatorNode, '+' );
  1772. const sub = /*@__PURE__*/ nodeProxy( OperatorNode, '-' );
  1773. const mul = /*@__PURE__*/ nodeProxy( OperatorNode, '*' );
  1774. const div = /*@__PURE__*/ nodeProxy( OperatorNode, '/' );
  1775. const modInt = /*@__PURE__*/ nodeProxy( OperatorNode, '%' );
  1776. const equal = /*@__PURE__*/ nodeProxy( OperatorNode, '==' );
  1777. const notEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '!=' );
  1778. const lessThan = /*@__PURE__*/ nodeProxy( OperatorNode, '<' );
  1779. const greaterThan = /*@__PURE__*/ nodeProxy( OperatorNode, '>' );
  1780. const lessThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '<=' );
  1781. const greaterThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '>=' );
  1782. const and = /*@__PURE__*/ nodeProxy( OperatorNode, '&&' );
  1783. const or = /*@__PURE__*/ nodeProxy( OperatorNode, '||' );
  1784. const not = /*@__PURE__*/ nodeProxy( OperatorNode, '!' );
  1785. const xor = /*@__PURE__*/ nodeProxy( OperatorNode, '^^' );
  1786. const bitAnd = /*@__PURE__*/ nodeProxy( OperatorNode, '&' );
  1787. const bitNot = /*@__PURE__*/ nodeProxy( OperatorNode, '~' );
  1788. const bitOr = /*@__PURE__*/ nodeProxy( OperatorNode, '|' );
  1789. const bitXor = /*@__PURE__*/ nodeProxy( OperatorNode, '^' );
  1790. const shiftLeft = /*@__PURE__*/ nodeProxy( OperatorNode, '<<' );
  1791. const shiftRight = /*@__PURE__*/ nodeProxy( OperatorNode, '>>' );
  1792. addMethodChaining( 'add', add );
  1793. addMethodChaining( 'sub', sub );
  1794. addMethodChaining( 'mul', mul );
  1795. addMethodChaining( 'div', div );
  1796. addMethodChaining( 'modInt', modInt );
  1797. addMethodChaining( 'equal', equal );
  1798. addMethodChaining( 'notEqual', notEqual );
  1799. addMethodChaining( 'lessThan', lessThan );
  1800. addMethodChaining( 'greaterThan', greaterThan );
  1801. addMethodChaining( 'lessThanEqual', lessThanEqual );
  1802. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  1803. addMethodChaining( 'and', and );
  1804. addMethodChaining( 'or', or );
  1805. addMethodChaining( 'not', not );
  1806. addMethodChaining( 'xor', xor );
  1807. addMethodChaining( 'bitAnd', bitAnd );
  1808. addMethodChaining( 'bitNot', bitNot );
  1809. addMethodChaining( 'bitOr', bitOr );
  1810. addMethodChaining( 'bitXor', bitXor );
  1811. addMethodChaining( 'shiftLeft', shiftLeft );
  1812. addMethodChaining( 'shiftRight', shiftRight );
  1813. const remainder = ( ...params ) => { // @deprecated, r168
  1814. console.warn( 'TSL.OperatorNode: .remainder() has been renamed to .modInt().' );
  1815. return modInt( ...params );
  1816. };
  1817. addMethodChaining( 'remainder', remainder );
  1818. class MathNode extends TempNode {
  1819. static get type() {
  1820. return 'MathNode';
  1821. }
  1822. constructor( method, aNode, bNode = null, cNode = null ) {
  1823. super();
  1824. this.method = method;
  1825. this.aNode = aNode;
  1826. this.bNode = bNode;
  1827. this.cNode = cNode;
  1828. }
  1829. getInputType( builder ) {
  1830. const aType = this.aNode.getNodeType( builder );
  1831. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  1832. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  1833. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  1834. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  1835. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  1836. if ( aLen > bLen && aLen > cLen ) {
  1837. return aType;
  1838. } else if ( bLen > cLen ) {
  1839. return bType;
  1840. } else if ( cLen > aLen ) {
  1841. return cType;
  1842. }
  1843. return aType;
  1844. }
  1845. getNodeType( builder ) {
  1846. const method = this.method;
  1847. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  1848. return 'float';
  1849. } else if ( method === MathNode.CROSS ) {
  1850. return 'vec3';
  1851. } else if ( method === MathNode.ALL ) {
  1852. return 'bool';
  1853. } else if ( method === MathNode.EQUALS ) {
  1854. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  1855. } else if ( method === MathNode.MOD ) {
  1856. return this.aNode.getNodeType( builder );
  1857. } else {
  1858. return this.getInputType( builder );
  1859. }
  1860. }
  1861. generate( builder, output ) {
  1862. const method = this.method;
  1863. const type = this.getNodeType( builder );
  1864. const inputType = this.getInputType( builder );
  1865. const a = this.aNode;
  1866. const b = this.bNode;
  1867. const c = this.cNode;
  1868. const isWebGL = builder.renderer.isWebGLRenderer === true;
  1869. if ( method === MathNode.TRANSFORM_DIRECTION ) {
  1870. // dir can be either a direction vector or a normal vector
  1871. // upper-left 3x3 of matrix is assumed to be orthogonal
  1872. let tA = a;
  1873. let tB = b;
  1874. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  1875. tB = vec4( vec3( tB ), 0.0 );
  1876. } else {
  1877. tA = vec4( vec3( tA ), 0.0 );
  1878. }
  1879. const mulNode = mul( tA, tB ).xyz;
  1880. return normalize( mulNode ).build( builder, output );
  1881. } else if ( method === MathNode.NEGATE ) {
  1882. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  1883. } else if ( method === MathNode.ONE_MINUS ) {
  1884. return sub( 1.0, a ).build( builder, output );
  1885. } else if ( method === MathNode.RECIPROCAL ) {
  1886. return div( 1.0, a ).build( builder, output );
  1887. } else if ( method === MathNode.DIFFERENCE ) {
  1888. return abs( sub( a, b ) ).build( builder, output );
  1889. } else {
  1890. const params = [];
  1891. if ( method === MathNode.CROSS || method === MathNode.MOD ) {
  1892. params.push(
  1893. a.build( builder, type ),
  1894. b.build( builder, type )
  1895. );
  1896. } else if ( isWebGL && method === MathNode.STEP ) {
  1897. params.push(
  1898. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  1899. b.build( builder, inputType )
  1900. );
  1901. } else if ( ( isWebGL && ( method === MathNode.MIN || method === MathNode.MAX ) ) || method === MathNode.MOD ) {
  1902. params.push(
  1903. a.build( builder, inputType ),
  1904. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  1905. );
  1906. } else if ( method === MathNode.REFRACT ) {
  1907. params.push(
  1908. a.build( builder, inputType ),
  1909. b.build( builder, inputType ),
  1910. c.build( builder, 'float' )
  1911. );
  1912. } else if ( method === MathNode.MIX ) {
  1913. params.push(
  1914. a.build( builder, inputType ),
  1915. b.build( builder, inputType ),
  1916. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  1917. );
  1918. } else {
  1919. params.push( a.build( builder, inputType ) );
  1920. if ( b !== null ) params.push( b.build( builder, inputType ) );
  1921. if ( c !== null ) params.push( c.build( builder, inputType ) );
  1922. }
  1923. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  1924. }
  1925. }
  1926. serialize( data ) {
  1927. super.serialize( data );
  1928. data.method = this.method;
  1929. }
  1930. deserialize( data ) {
  1931. super.deserialize( data );
  1932. this.method = data.method;
  1933. }
  1934. }
  1935. // 1 input
  1936. MathNode.ALL = 'all';
  1937. MathNode.ANY = 'any';
  1938. MathNode.EQUALS = 'equals';
  1939. MathNode.RADIANS = 'radians';
  1940. MathNode.DEGREES = 'degrees';
  1941. MathNode.EXP = 'exp';
  1942. MathNode.EXP2 = 'exp2';
  1943. MathNode.LOG = 'log';
  1944. MathNode.LOG2 = 'log2';
  1945. MathNode.SQRT = 'sqrt';
  1946. MathNode.INVERSE_SQRT = 'inversesqrt';
  1947. MathNode.FLOOR = 'floor';
  1948. MathNode.CEIL = 'ceil';
  1949. MathNode.NORMALIZE = 'normalize';
  1950. MathNode.FRACT = 'fract';
  1951. MathNode.SIN = 'sin';
  1952. MathNode.COS = 'cos';
  1953. MathNode.TAN = 'tan';
  1954. MathNode.ASIN = 'asin';
  1955. MathNode.ACOS = 'acos';
  1956. MathNode.ATAN = 'atan';
  1957. MathNode.ABS = 'abs';
  1958. MathNode.SIGN = 'sign';
  1959. MathNode.LENGTH = 'length';
  1960. MathNode.NEGATE = 'negate';
  1961. MathNode.ONE_MINUS = 'oneMinus';
  1962. MathNode.DFDX = 'dFdx';
  1963. MathNode.DFDY = 'dFdy';
  1964. MathNode.ROUND = 'round';
  1965. MathNode.RECIPROCAL = 'reciprocal';
  1966. MathNode.TRUNC = 'trunc';
  1967. MathNode.FWIDTH = 'fwidth';
  1968. MathNode.BITCAST = 'bitcast';
  1969. MathNode.TRANSPOSE = 'transpose';
  1970. // 2 inputs
  1971. MathNode.ATAN2 = 'atan2';
  1972. MathNode.MIN = 'min';
  1973. MathNode.MAX = 'max';
  1974. MathNode.MOD = 'mod';
  1975. MathNode.STEP = 'step';
  1976. MathNode.REFLECT = 'reflect';
  1977. MathNode.DISTANCE = 'distance';
  1978. MathNode.DIFFERENCE = 'difference';
  1979. MathNode.DOT = 'dot';
  1980. MathNode.CROSS = 'cross';
  1981. MathNode.POW = 'pow';
  1982. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  1983. // 3 inputs
  1984. MathNode.MIX = 'mix';
  1985. MathNode.CLAMP = 'clamp';
  1986. MathNode.REFRACT = 'refract';
  1987. MathNode.SMOOTHSTEP = 'smoothstep';
  1988. MathNode.FACEFORWARD = 'faceforward';
  1989. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  1990. const INFINITY = /*@__PURE__*/ float( 1e6 );
  1991. const PI = /*@__PURE__*/ float( Math.PI );
  1992. const PI2 = /*@__PURE__*/ float( Math.PI * 2 );
  1993. const all = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ALL );
  1994. const any = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ANY );
  1995. const equals = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EQUALS );
  1996. const radians = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RADIANS );
  1997. const degrees = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DEGREES );
  1998. const exp = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP );
  1999. const exp2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP2 );
  2000. const log = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG );
  2001. const log2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG2 );
  2002. const sqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SQRT );
  2003. const inverseSqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.INVERSE_SQRT );
  2004. const floor = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FLOOR );
  2005. const ceil = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CEIL );
  2006. const normalize = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NORMALIZE );
  2007. const fract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FRACT );
  2008. const sin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIN );
  2009. const cos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.COS );
  2010. const tan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TAN );
  2011. const asin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ASIN );
  2012. const acos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ACOS );
  2013. const atan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN );
  2014. const abs = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ABS );
  2015. const sign = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIGN );
  2016. const length = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LENGTH );
  2017. const negate = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NEGATE );
  2018. const oneMinus = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ONE_MINUS );
  2019. const dFdx = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDX );
  2020. const dFdy = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDY );
  2021. const round = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ROUND );
  2022. const reciprocal = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RECIPROCAL );
  2023. const trunc = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRUNC );
  2024. const fwidth = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FWIDTH );
  2025. const bitcast = /*@__PURE__*/ nodeProxy( MathNode, MathNode.BITCAST );
  2026. const transpose = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSPOSE );
  2027. const atan2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN2 );
  2028. const min$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIN );
  2029. const max$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MAX );
  2030. const mod = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MOD );
  2031. const step = /*@__PURE__*/ nodeProxy( MathNode, MathNode.STEP );
  2032. const reflect = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFLECT );
  2033. const distance = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DISTANCE );
  2034. const difference = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DIFFERENCE );
  2035. const dot = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DOT );
  2036. const cross = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CROSS );
  2037. const pow = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW );
  2038. const pow2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 2 );
  2039. const pow3 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 3 );
  2040. const pow4 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 4 );
  2041. const transformDirection = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSFORM_DIRECTION );
  2042. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  2043. const lengthSq = ( a ) => dot( a, a );
  2044. const mix = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIX );
  2045. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  2046. const saturate = ( value ) => clamp( value );
  2047. const refract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFRACT );
  2048. const smoothstep = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SMOOTHSTEP );
  2049. const faceForward = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FACEFORWARD );
  2050. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  2051. const a = 12.9898, b = 78.233, c = 43758.5453;
  2052. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  2053. return fract( sin( sn ).mul( c ) );
  2054. } );
  2055. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  2056. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  2057. addMethodChaining( 'all', all );
  2058. addMethodChaining( 'any', any );
  2059. addMethodChaining( 'equals', equals );
  2060. addMethodChaining( 'radians', radians );
  2061. addMethodChaining( 'degrees', degrees );
  2062. addMethodChaining( 'exp', exp );
  2063. addMethodChaining( 'exp2', exp2 );
  2064. addMethodChaining( 'log', log );
  2065. addMethodChaining( 'log2', log2 );
  2066. addMethodChaining( 'sqrt', sqrt );
  2067. addMethodChaining( 'inverseSqrt', inverseSqrt );
  2068. addMethodChaining( 'floor', floor );
  2069. addMethodChaining( 'ceil', ceil );
  2070. addMethodChaining( 'normalize', normalize );
  2071. addMethodChaining( 'fract', fract );
  2072. addMethodChaining( 'sin', sin );
  2073. addMethodChaining( 'cos', cos );
  2074. addMethodChaining( 'tan', tan );
  2075. addMethodChaining( 'asin', asin );
  2076. addMethodChaining( 'acos', acos );
  2077. addMethodChaining( 'atan', atan );
  2078. addMethodChaining( 'abs', abs );
  2079. addMethodChaining( 'sign', sign );
  2080. addMethodChaining( 'length', length );
  2081. addMethodChaining( 'lengthSq', lengthSq );
  2082. addMethodChaining( 'negate', negate );
  2083. addMethodChaining( 'oneMinus', oneMinus );
  2084. addMethodChaining( 'dFdx', dFdx );
  2085. addMethodChaining( 'dFdy', dFdy );
  2086. addMethodChaining( 'round', round );
  2087. addMethodChaining( 'reciprocal', reciprocal );
  2088. addMethodChaining( 'trunc', trunc );
  2089. addMethodChaining( 'fwidth', fwidth );
  2090. addMethodChaining( 'atan2', atan2 );
  2091. addMethodChaining( 'min', min$1 );
  2092. addMethodChaining( 'max', max$1 );
  2093. addMethodChaining( 'mod', mod );
  2094. addMethodChaining( 'step', step );
  2095. addMethodChaining( 'reflect', reflect );
  2096. addMethodChaining( 'distance', distance );
  2097. addMethodChaining( 'dot', dot );
  2098. addMethodChaining( 'cross', cross );
  2099. addMethodChaining( 'pow', pow );
  2100. addMethodChaining( 'pow2', pow2 );
  2101. addMethodChaining( 'pow3', pow3 );
  2102. addMethodChaining( 'pow4', pow4 );
  2103. addMethodChaining( 'transformDirection', transformDirection );
  2104. addMethodChaining( 'mix', mixElement );
  2105. addMethodChaining( 'clamp', clamp );
  2106. addMethodChaining( 'refract', refract );
  2107. addMethodChaining( 'smoothstep', smoothstepElement );
  2108. addMethodChaining( 'faceForward', faceForward );
  2109. addMethodChaining( 'difference', difference );
  2110. addMethodChaining( 'saturate', saturate );
  2111. addMethodChaining( 'cbrt', cbrt );
  2112. addMethodChaining( 'transpose', transpose );
  2113. addMethodChaining( 'rand', rand );
  2114. class ConditionalNode extends Node {
  2115. static get type() {
  2116. return 'ConditionalNode';
  2117. }
  2118. constructor( condNode, ifNode, elseNode = null ) {
  2119. super();
  2120. this.condNode = condNode;
  2121. this.ifNode = ifNode;
  2122. this.elseNode = elseNode;
  2123. }
  2124. getNodeType( builder ) {
  2125. const ifType = this.ifNode.getNodeType( builder );
  2126. if ( this.elseNode !== null ) {
  2127. const elseType = this.elseNode.getNodeType( builder );
  2128. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  2129. return elseType;
  2130. }
  2131. }
  2132. return ifType;
  2133. }
  2134. setup( builder ) {
  2135. const condNode = this.condNode.cache();
  2136. const ifNode = this.ifNode.cache();
  2137. const elseNode = this.elseNode ? this.elseNode.cache() : null;
  2138. //
  2139. const currentNodeBlock = builder.context.nodeBlock;
  2140. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  2141. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  2142. //
  2143. const properties = builder.getNodeProperties( this );
  2144. properties.condNode = condNode;
  2145. properties.ifNode = ifNode.context( { nodeBlock: ifNode } );
  2146. properties.elseNode = elseNode ? elseNode.context( { nodeBlock: elseNode } ) : null;
  2147. }
  2148. generate( builder, output ) {
  2149. const type = this.getNodeType( builder );
  2150. const nodeData = builder.getDataFromNode( this );
  2151. if ( nodeData.nodeProperty !== undefined ) {
  2152. return nodeData.nodeProperty;
  2153. }
  2154. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  2155. const needsOutput = output !== 'void';
  2156. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  2157. nodeData.nodeProperty = nodeProperty;
  2158. const nodeSnippet = condNode.build( builder, 'bool' );
  2159. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  2160. let ifSnippet = ifNode.build( builder, type );
  2161. if ( ifSnippet ) {
  2162. if ( needsOutput ) {
  2163. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  2164. } else {
  2165. ifSnippet = 'return ' + ifSnippet + ';';
  2166. }
  2167. }
  2168. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  2169. if ( elseNode !== null ) {
  2170. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  2171. let elseSnippet = elseNode.build( builder, type );
  2172. if ( elseSnippet ) {
  2173. if ( needsOutput ) {
  2174. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  2175. } else {
  2176. elseSnippet = 'return ' + elseSnippet + ';';
  2177. }
  2178. }
  2179. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  2180. } else {
  2181. builder.addFlowCode( '\n\n' );
  2182. }
  2183. return builder.format( nodeProperty, type, output );
  2184. }
  2185. }
  2186. const select = /*@__PURE__*/ nodeProxy( ConditionalNode );
  2187. addMethodChaining( 'select', select );
  2188. //
  2189. const cond = ( ...params ) => { // @deprecated, r168
  2190. console.warn( 'TSL.ConditionalNode: cond() has been renamed to select().' );
  2191. return select( ...params );
  2192. };
  2193. addMethodChaining( 'cond', cond );
  2194. class ContextNode extends Node {
  2195. static get type() {
  2196. return 'ContextNode';
  2197. }
  2198. constructor( node, value = {} ) {
  2199. super();
  2200. this.isContextNode = true;
  2201. this.node = node;
  2202. this.value = value;
  2203. }
  2204. getScope() {
  2205. return this.node.getScope();
  2206. }
  2207. getNodeType( builder ) {
  2208. return this.node.getNodeType( builder );
  2209. }
  2210. analyze( builder ) {
  2211. this.node.build( builder );
  2212. }
  2213. setup( builder ) {
  2214. const previousContext = builder.getContext();
  2215. builder.setContext( { ...builder.context, ...this.value } );
  2216. const node = this.node.build( builder );
  2217. builder.setContext( previousContext );
  2218. return node;
  2219. }
  2220. generate( builder, output ) {
  2221. const previousContext = builder.getContext();
  2222. builder.setContext( { ...builder.context, ...this.value } );
  2223. const snippet = this.node.build( builder, output );
  2224. builder.setContext( previousContext );
  2225. return snippet;
  2226. }
  2227. }
  2228. const context = /*@__PURE__*/ nodeProxy( ContextNode );
  2229. const label = ( node, name ) => context( node, { label: name } );
  2230. addMethodChaining( 'context', context );
  2231. addMethodChaining( 'label', label );
  2232. class VarNode extends Node {
  2233. static get type() {
  2234. return 'VarNode';
  2235. }
  2236. constructor( node, name = null ) {
  2237. super();
  2238. this.node = node;
  2239. this.name = name;
  2240. this.global = true;
  2241. this.isVarNode = true;
  2242. }
  2243. getHash( builder ) {
  2244. return this.name || super.getHash( builder );
  2245. }
  2246. getNodeType( builder ) {
  2247. return this.node.getNodeType( builder );
  2248. }
  2249. generate( builder ) {
  2250. const { node, name } = this;
  2251. const nodeVar = builder.getVarFromNode( this, name, builder.getVectorType( this.getNodeType( builder ) ) );
  2252. const propertyName = builder.getPropertyName( nodeVar );
  2253. const snippet = node.build( builder, nodeVar.type );
  2254. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  2255. return propertyName;
  2256. }
  2257. }
  2258. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  2259. addMethodChaining( 'toVar', ( ...params ) => createVar( ...params ).append() );
  2260. // Deprecated
  2261. const temp = ( node ) => { // @deprecated, r170
  2262. console.warn( 'TSL: "temp" is deprecated. Use ".toVar()" instead.' );
  2263. return createVar( node );
  2264. };
  2265. addMethodChaining( 'temp', temp );
  2266. class VaryingNode extends Node {
  2267. static get type() {
  2268. return 'VaryingNode';
  2269. }
  2270. constructor( node, name = null ) {
  2271. super();
  2272. this.node = node;
  2273. this.name = name;
  2274. this.isVaryingNode = true;
  2275. }
  2276. isGlobal() {
  2277. return true;
  2278. }
  2279. getHash( builder ) {
  2280. return this.name || super.getHash( builder );
  2281. }
  2282. getNodeType( builder ) {
  2283. // VaryingNode is auto type
  2284. return this.node.getNodeType( builder );
  2285. }
  2286. setupVarying( builder ) {
  2287. const properties = builder.getNodeProperties( this );
  2288. let varying = properties.varying;
  2289. if ( varying === undefined ) {
  2290. const name = this.name;
  2291. const type = this.getNodeType( builder );
  2292. properties.varying = varying = builder.getVaryingFromNode( this, name, type );
  2293. properties.node = this.node;
  2294. }
  2295. // this property can be used to check if the varying can be optimized for a variable
  2296. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  2297. return varying;
  2298. }
  2299. setup( builder ) {
  2300. this.setupVarying( builder );
  2301. }
  2302. analyze( builder ) {
  2303. this.setupVarying( builder );
  2304. return this.node.analyze( builder );
  2305. }
  2306. generate( builder ) {
  2307. const properties = builder.getNodeProperties( this );
  2308. const varying = this.setupVarying( builder );
  2309. if ( properties.propertyName === undefined ) {
  2310. const type = this.getNodeType( builder );
  2311. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  2312. // force node run in vertex stage
  2313. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node, type, propertyName );
  2314. properties.propertyName = propertyName;
  2315. }
  2316. return builder.getPropertyName( varying );
  2317. }
  2318. }
  2319. const varying = /*@__PURE__*/ nodeProxy( VaryingNode );
  2320. addMethodChaining( 'varying', varying );
  2321. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  2322. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  2323. const b = color.mul( 0.0773993808 );
  2324. const factor = color.lessThanEqual( 0.04045 );
  2325. const rgbResult = mix( a, b, factor );
  2326. return rgbResult;
  2327. } ).setLayout( {
  2328. name: 'sRGBTransferEOTF',
  2329. type: 'vec3',
  2330. inputs: [
  2331. { name: 'color', type: 'vec3' }
  2332. ]
  2333. } );
  2334. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  2335. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  2336. const b = color.mul( 12.92 );
  2337. const factor = color.lessThanEqual( 0.0031308 );
  2338. const rgbResult = mix( a, b, factor );
  2339. return rgbResult;
  2340. } ).setLayout( {
  2341. name: 'sRGBTransferOETF',
  2342. type: 'vec3',
  2343. inputs: [
  2344. { name: 'color', type: 'vec3' }
  2345. ]
  2346. } );
  2347. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  2348. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  2349. class ColorSpaceNode extends TempNode {
  2350. static get type() {
  2351. return 'ColorSpaceNode';
  2352. }
  2353. constructor( colorNode, source, target ) {
  2354. super( 'vec4' );
  2355. this.colorNode = colorNode;
  2356. this.source = source;
  2357. this.target = target;
  2358. }
  2359. resolveColorSpace( builder, colorSpace ) {
  2360. if ( colorSpace === WORKING_COLOR_SPACE ) {
  2361. return ColorManagement.workingColorSpace;
  2362. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  2363. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  2364. }
  2365. return colorSpace;
  2366. }
  2367. setup( builder ) {
  2368. const { colorNode } = this;
  2369. const source = this.resolveColorSpace( builder, this.source );
  2370. const target = this.resolveColorSpace( builder, this.target );
  2371. let outputNode = colorNode;
  2372. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  2373. return outputNode;
  2374. }
  2375. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  2376. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  2377. }
  2378. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  2379. outputNode = vec4(
  2380. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  2381. outputNode.a
  2382. );
  2383. }
  2384. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  2385. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  2386. }
  2387. return outputNode;
  2388. }
  2389. }
  2390. const toOutputColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, OUTPUT_COLOR_SPACE ) );
  2391. const toWorkingColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), OUTPUT_COLOR_SPACE, WORKING_COLOR_SPACE ) );
  2392. const workingToColorSpace = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, colorSpace ) );
  2393. const colorSpaceToWorking = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), colorSpace, WORKING_COLOR_SPACE ) );
  2394. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  2395. addMethodChaining( 'toOutputColorSpace', toOutputColorSpace );
  2396. addMethodChaining( 'toWorkingColorSpace', toWorkingColorSpace );
  2397. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  2398. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  2399. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  2400. static get type() {
  2401. return 'ReferenceElementNode';
  2402. }
  2403. constructor( referenceNode, indexNode ) {
  2404. super( referenceNode, indexNode );
  2405. this.referenceNode = referenceNode;
  2406. this.isReferenceElementNode = true;
  2407. }
  2408. getNodeType() {
  2409. return this.referenceNode.uniformType;
  2410. }
  2411. generate( builder ) {
  2412. const snippet = super.generate( builder );
  2413. const arrayType = this.referenceNode.getNodeType();
  2414. const elementType = this.getNodeType();
  2415. return builder.format( snippet, arrayType, elementType );
  2416. }
  2417. };
  2418. class ReferenceBaseNode extends Node {
  2419. static get type() {
  2420. return 'ReferenceBaseNode';
  2421. }
  2422. constructor( property, uniformType, object = null, count = null ) {
  2423. super();
  2424. this.property = property;
  2425. this.uniformType = uniformType;
  2426. this.object = object;
  2427. this.count = count;
  2428. this.properties = property.split( '.' );
  2429. this.reference = object;
  2430. this.node = null;
  2431. this.group = null;
  2432. this.updateType = NodeUpdateType.OBJECT;
  2433. }
  2434. setGroup( group ) {
  2435. this.group = group;
  2436. return this;
  2437. }
  2438. element( indexNode ) {
  2439. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  2440. }
  2441. setNodeType( uniformType ) {
  2442. const node = uniform( null, uniformType ).getSelf();
  2443. if ( this.group !== null ) {
  2444. node.setGroup( this.group );
  2445. }
  2446. this.node = node;
  2447. }
  2448. getNodeType( builder ) {
  2449. if ( this.node === null ) {
  2450. this.updateReference( builder );
  2451. this.updateValue();
  2452. }
  2453. return this.node.getNodeType( builder );
  2454. }
  2455. getValueFromReference( object = this.reference ) {
  2456. const { properties } = this;
  2457. let value = object[ properties[ 0 ] ];
  2458. for ( let i = 1; i < properties.length; i ++ ) {
  2459. value = value[ properties[ i ] ];
  2460. }
  2461. return value;
  2462. }
  2463. updateReference( state ) {
  2464. this.reference = this.object !== null ? this.object : state.object;
  2465. return this.reference;
  2466. }
  2467. setup() {
  2468. this.updateValue();
  2469. return this.node;
  2470. }
  2471. update( /*frame*/ ) {
  2472. this.updateValue();
  2473. }
  2474. updateValue() {
  2475. if ( this.node === null ) this.setNodeType( this.uniformType );
  2476. const value = this.getValueFromReference();
  2477. if ( Array.isArray( value ) ) {
  2478. this.node.array = value;
  2479. } else {
  2480. this.node.value = value;
  2481. }
  2482. }
  2483. }
  2484. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  2485. class RendererReferenceNode extends ReferenceBaseNode {
  2486. static get type() {
  2487. return 'RendererReferenceNode';
  2488. }
  2489. constructor( property, inputType, renderer = null ) {
  2490. super( property, inputType, renderer );
  2491. this.renderer = renderer;
  2492. this.setGroup( renderGroup );
  2493. }
  2494. updateReference( state ) {
  2495. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  2496. return this.reference;
  2497. }
  2498. }
  2499. const rendererReference = ( name, type, renderer ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  2500. class ToneMappingNode extends TempNode {
  2501. static get type() {
  2502. return 'ToneMappingNode';
  2503. }
  2504. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  2505. super( 'vec3' );
  2506. this.toneMapping = toneMapping;
  2507. this.exposureNode = exposureNode;
  2508. this.colorNode = colorNode;
  2509. }
  2510. getCacheKey() {
  2511. return hash$1( super.getCacheKey(), this.toneMapping );
  2512. }
  2513. setup( builder ) {
  2514. const colorNode = this.colorNode || builder.context.color;
  2515. const toneMapping = this.toneMapping;
  2516. if ( toneMapping === NoToneMapping ) return colorNode;
  2517. let outputNode = null;
  2518. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  2519. if ( toneMappingFn !== null ) {
  2520. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  2521. } else {
  2522. console.error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  2523. outputNode = colorNode;
  2524. }
  2525. return outputNode;
  2526. }
  2527. }
  2528. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  2529. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  2530. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  2531. class BufferAttributeNode extends InputNode {
  2532. static get type() {
  2533. return 'BufferAttributeNode';
  2534. }
  2535. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  2536. super( value, bufferType );
  2537. this.isBufferNode = true;
  2538. this.bufferType = bufferType;
  2539. this.bufferStride = bufferStride;
  2540. this.bufferOffset = bufferOffset;
  2541. this.usage = StaticDrawUsage;
  2542. this.instanced = false;
  2543. this.attribute = null;
  2544. this.global = true;
  2545. if ( value && value.isBufferAttribute === true ) {
  2546. this.attribute = value;
  2547. this.usage = value.usage;
  2548. this.instanced = value.isInstancedBufferAttribute;
  2549. }
  2550. }
  2551. getHash( builder ) {
  2552. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  2553. let bufferData = builder.globalCache.getData( this.value );
  2554. if ( bufferData === undefined ) {
  2555. bufferData = {
  2556. node: this
  2557. };
  2558. builder.globalCache.setData( this.value, bufferData );
  2559. }
  2560. return bufferData.node.uuid;
  2561. }
  2562. return this.uuid;
  2563. }
  2564. getNodeType( builder ) {
  2565. if ( this.bufferType === null ) {
  2566. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  2567. }
  2568. return this.bufferType;
  2569. }
  2570. setup( builder ) {
  2571. if ( this.attribute !== null ) return;
  2572. const type = this.getNodeType( builder );
  2573. const array = this.value;
  2574. const itemSize = builder.getTypeLength( type );
  2575. const stride = this.bufferStride || itemSize;
  2576. const offset = this.bufferOffset;
  2577. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  2578. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  2579. buffer.setUsage( this.usage );
  2580. this.attribute = bufferAttribute;
  2581. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  2582. }
  2583. generate( builder ) {
  2584. const nodeType = this.getNodeType( builder );
  2585. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  2586. const propertyName = builder.getPropertyName( nodeAttribute );
  2587. let output = null;
  2588. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  2589. this.name = propertyName;
  2590. output = propertyName;
  2591. } else {
  2592. const nodeVarying = varying( this );
  2593. output = nodeVarying.build( builder, nodeType );
  2594. }
  2595. return output;
  2596. }
  2597. getInputType( /*builder*/ ) {
  2598. return 'bufferAttribute';
  2599. }
  2600. setUsage( value ) {
  2601. this.usage = value;
  2602. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  2603. this.attribute.usage = value;
  2604. }
  2605. return this;
  2606. }
  2607. setInstanced( value ) {
  2608. this.instanced = value;
  2609. return this;
  2610. }
  2611. }
  2612. const bufferAttribute = ( array, type, stride, offset ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  2613. const dynamicBufferAttribute = ( array, type, stride, offset ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  2614. const instancedBufferAttribute = ( array, type, stride, offset ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  2615. const instancedDynamicBufferAttribute = ( array, type, stride, offset ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  2616. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  2617. class ComputeNode extends Node {
  2618. static get type() {
  2619. return 'ComputeNode';
  2620. }
  2621. constructor( computeNode, count, workgroupSize = [ 64 ] ) {
  2622. super( 'void' );
  2623. this.isComputeNode = true;
  2624. this.computeNode = computeNode;
  2625. this.count = count;
  2626. this.workgroupSize = workgroupSize;
  2627. this.dispatchCount = 0;
  2628. this.version = 1;
  2629. this.updateBeforeType = NodeUpdateType.OBJECT;
  2630. this.onInitFunction = null;
  2631. this.updateDispatchCount();
  2632. }
  2633. dispose() {
  2634. this.dispatchEvent( { type: 'dispose' } );
  2635. }
  2636. set needsUpdate( value ) {
  2637. if ( value === true ) this.version ++;
  2638. }
  2639. updateDispatchCount() {
  2640. const { count, workgroupSize } = this;
  2641. let size = workgroupSize[ 0 ];
  2642. for ( let i = 1; i < workgroupSize.length; i ++ )
  2643. size *= workgroupSize[ i ];
  2644. this.dispatchCount = Math.ceil( count / size );
  2645. }
  2646. onInit( callback ) {
  2647. this.onInitFunction = callback;
  2648. return this;
  2649. }
  2650. updateBefore( { renderer } ) {
  2651. renderer.compute( this );
  2652. }
  2653. generate( builder ) {
  2654. const { shaderStage } = builder;
  2655. if ( shaderStage === 'compute' ) {
  2656. const snippet = this.computeNode.build( builder, 'void' );
  2657. if ( snippet !== '' ) {
  2658. builder.addLineFlowCode( snippet, this );
  2659. }
  2660. }
  2661. }
  2662. }
  2663. const compute = ( node, count, workgroupSize ) => nodeObject( new ComputeNode( nodeObject( node ), count, workgroupSize ) );
  2664. addMethodChaining( 'compute', compute );
  2665. class CacheNode extends Node {
  2666. static get type() {
  2667. return 'CacheNode';
  2668. }
  2669. constructor( node, parent = true ) {
  2670. super();
  2671. this.node = node;
  2672. this.parent = parent;
  2673. this.isCacheNode = true;
  2674. }
  2675. getNodeType( builder ) {
  2676. return this.node.getNodeType( builder );
  2677. }
  2678. build( builder, ...params ) {
  2679. const previousCache = builder.getCache();
  2680. const cache = builder.getCacheFromNode( this, this.parent );
  2681. builder.setCache( cache );
  2682. const data = this.node.build( builder, ...params );
  2683. builder.setCache( previousCache );
  2684. return data;
  2685. }
  2686. }
  2687. const cache = ( node, ...params ) => nodeObject( new CacheNode( nodeObject( node ), ...params ) );
  2688. addMethodChaining( 'cache', cache );
  2689. class BypassNode extends Node {
  2690. static get type() {
  2691. return 'BypassNode';
  2692. }
  2693. constructor( returnNode, callNode ) {
  2694. super();
  2695. this.isBypassNode = true;
  2696. this.outputNode = returnNode;
  2697. this.callNode = callNode;
  2698. }
  2699. getNodeType( builder ) {
  2700. return this.outputNode.getNodeType( builder );
  2701. }
  2702. generate( builder ) {
  2703. const snippet = this.callNode.build( builder, 'void' );
  2704. if ( snippet !== '' ) {
  2705. builder.addLineFlowCode( snippet, this );
  2706. }
  2707. return this.outputNode.build( builder );
  2708. }
  2709. }
  2710. const bypass = /*@__PURE__*/ nodeProxy( BypassNode );
  2711. addMethodChaining( 'bypass', bypass );
  2712. class RemapNode extends Node {
  2713. static get type() {
  2714. return 'RemapNode';
  2715. }
  2716. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  2717. super();
  2718. this.node = node;
  2719. this.inLowNode = inLowNode;
  2720. this.inHighNode = inHighNode;
  2721. this.outLowNode = outLowNode;
  2722. this.outHighNode = outHighNode;
  2723. this.doClamp = true;
  2724. }
  2725. setup() {
  2726. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  2727. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  2728. if ( doClamp === true ) t = t.clamp();
  2729. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  2730. }
  2731. }
  2732. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } );
  2733. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode );
  2734. addMethodChaining( 'remap', remap );
  2735. addMethodChaining( 'remapClamp', remapClamp );
  2736. class ExpressionNode extends Node {
  2737. static get type() {
  2738. return 'ExpressionNode';
  2739. }
  2740. constructor( snippet = '', nodeType = 'void' ) {
  2741. super( nodeType );
  2742. this.snippet = snippet;
  2743. }
  2744. generate( builder, output ) {
  2745. const type = this.getNodeType( builder );
  2746. const snippet = this.snippet;
  2747. if ( type === 'void' ) {
  2748. builder.addLineFlowCode( snippet, this );
  2749. } else {
  2750. return builder.format( `( ${ snippet } )`, type, output );
  2751. }
  2752. }
  2753. }
  2754. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode );
  2755. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).append();
  2756. const Return = () => expression( 'return' ).append();
  2757. addMethodChaining( 'discard', Discard );
  2758. class RenderOutputNode extends TempNode {
  2759. static get type() {
  2760. return 'RenderOutputNode';
  2761. }
  2762. constructor( colorNode, toneMapping, outputColorSpace ) {
  2763. super( 'vec4' );
  2764. this.colorNode = colorNode;
  2765. this.toneMapping = toneMapping;
  2766. this.outputColorSpace = outputColorSpace;
  2767. this.isRenderOutput = true;
  2768. }
  2769. setup( { context } ) {
  2770. let outputNode = this.colorNode || context.color;
  2771. // tone mapping
  2772. const toneMapping = ( this.toneMapping !== null ? this.toneMapping : context.toneMapping ) || NoToneMapping;
  2773. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  2774. if ( toneMapping !== NoToneMapping ) {
  2775. outputNode = outputNode.toneMapping( toneMapping );
  2776. }
  2777. // working to output color space
  2778. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  2779. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  2780. }
  2781. return outputNode;
  2782. }
  2783. }
  2784. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  2785. addMethodChaining( 'renderOutput', renderOutput );
  2786. // Non-PURE exports list, side-effects are required here.
  2787. // TSL Base Syntax
  2788. function addNodeElement( name/*, nodeElement*/ ) {
  2789. console.warn( 'THREE.TSLBase: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  2790. }
  2791. class AttributeNode extends Node {
  2792. static get type() {
  2793. return 'AttributeNode';
  2794. }
  2795. constructor( attributeName, nodeType = null ) {
  2796. super( nodeType );
  2797. this.global = true;
  2798. this._attributeName = attributeName;
  2799. }
  2800. getHash( builder ) {
  2801. return this.getAttributeName( builder );
  2802. }
  2803. getNodeType( builder ) {
  2804. let nodeType = this.nodeType;
  2805. if ( nodeType === null ) {
  2806. const attributeName = this.getAttributeName( builder );
  2807. if ( builder.hasGeometryAttribute( attributeName ) ) {
  2808. const attribute = builder.geometry.getAttribute( attributeName );
  2809. nodeType = builder.getTypeFromAttribute( attribute );
  2810. } else {
  2811. nodeType = 'float';
  2812. }
  2813. }
  2814. return nodeType;
  2815. }
  2816. setAttributeName( attributeName ) {
  2817. this._attributeName = attributeName;
  2818. return this;
  2819. }
  2820. getAttributeName( /*builder*/ ) {
  2821. return this._attributeName;
  2822. }
  2823. generate( builder ) {
  2824. const attributeName = this.getAttributeName( builder );
  2825. const nodeType = this.getNodeType( builder );
  2826. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  2827. if ( geometryAttribute === true ) {
  2828. const attribute = builder.geometry.getAttribute( attributeName );
  2829. const attributeType = builder.getTypeFromAttribute( attribute );
  2830. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  2831. if ( builder.shaderStage === 'vertex' ) {
  2832. return builder.format( nodeAttribute.name, attributeType, nodeType );
  2833. } else {
  2834. const nodeVarying = varying( this );
  2835. return nodeVarying.build( builder, nodeType );
  2836. }
  2837. } else {
  2838. console.warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  2839. return builder.generateConst( nodeType );
  2840. }
  2841. }
  2842. serialize( data ) {
  2843. super.serialize( data );
  2844. data.global = this.global;
  2845. data._attributeName = this._attributeName;
  2846. }
  2847. deserialize( data ) {
  2848. super.deserialize( data );
  2849. this.global = data.global;
  2850. this._attributeName = data._attributeName;
  2851. }
  2852. }
  2853. const attribute = ( name, nodeType ) => nodeObject( new AttributeNode( name, nodeType ) );
  2854. const uv = ( index ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  2855. class TextureSizeNode extends Node {
  2856. static get type() {
  2857. return 'TextureSizeNode';
  2858. }
  2859. constructor( textureNode, levelNode = null ) {
  2860. super( 'uvec2' );
  2861. this.isTextureSizeNode = true;
  2862. this.textureNode = textureNode;
  2863. this.levelNode = levelNode;
  2864. }
  2865. generate( builder, output ) {
  2866. const textureProperty = this.textureNode.build( builder, 'property' );
  2867. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  2868. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  2869. }
  2870. }
  2871. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode );
  2872. class MaxMipLevelNode extends UniformNode {
  2873. static get type() {
  2874. return 'MaxMipLevelNode';
  2875. }
  2876. constructor( textureNode ) {
  2877. super( 0 );
  2878. this._textureNode = textureNode;
  2879. this.updateType = NodeUpdateType.FRAME;
  2880. }
  2881. get textureNode() {
  2882. return this._textureNode;
  2883. }
  2884. get texture() {
  2885. return this._textureNode.value;
  2886. }
  2887. update() {
  2888. const texture = this.texture;
  2889. const images = texture.images;
  2890. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  2891. if ( image && image.width !== undefined ) {
  2892. const { width, height } = image;
  2893. this.value = Math.log2( Math.max( width, height ) );
  2894. }
  2895. }
  2896. }
  2897. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode );
  2898. class TextureNode extends UniformNode {
  2899. static get type() {
  2900. return 'TextureNode';
  2901. }
  2902. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  2903. super( value );
  2904. this.isTextureNode = true;
  2905. this.uvNode = uvNode;
  2906. this.levelNode = levelNode;
  2907. this.biasNode = biasNode;
  2908. this.compareNode = null;
  2909. this.depthNode = null;
  2910. this.gradNode = null;
  2911. this.sampler = true;
  2912. this.updateMatrix = false;
  2913. this.updateType = NodeUpdateType.NONE;
  2914. this.referenceNode = null;
  2915. this._value = value;
  2916. this._matrixUniform = null;
  2917. this.setUpdateMatrix( uvNode === null );
  2918. }
  2919. set value( value ) {
  2920. if ( this.referenceNode ) {
  2921. this.referenceNode.value = value;
  2922. } else {
  2923. this._value = value;
  2924. }
  2925. }
  2926. get value() {
  2927. return this.referenceNode ? this.referenceNode.value : this._value;
  2928. }
  2929. getUniformHash( /*builder*/ ) {
  2930. return this.value.uuid;
  2931. }
  2932. getNodeType( /*builder*/ ) {
  2933. if ( this.value.isDepthTexture === true ) return 'float';
  2934. if ( this.value.type === UnsignedIntType ) {
  2935. return 'uvec4';
  2936. } else if ( this.value.type === IntType ) {
  2937. return 'ivec4';
  2938. }
  2939. return 'vec4';
  2940. }
  2941. getInputType( /*builder*/ ) {
  2942. return 'texture';
  2943. }
  2944. getDefaultUV() {
  2945. return uv( this.value.channel );
  2946. }
  2947. updateReference( /*state*/ ) {
  2948. return this.value;
  2949. }
  2950. getTransformedUV( uvNode ) {
  2951. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  2952. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  2953. }
  2954. setUpdateMatrix( value ) {
  2955. this.updateMatrix = value;
  2956. this.updateType = value ? NodeUpdateType.FRAME : NodeUpdateType.NONE;
  2957. return this;
  2958. }
  2959. setupUV( builder, uvNode ) {
  2960. const texture = this.value;
  2961. if ( builder.isFlipY() && ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true ) ) {
  2962. if ( this.sampler ) {
  2963. uvNode = uvNode.flipY();
  2964. } else {
  2965. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  2966. }
  2967. }
  2968. return uvNode;
  2969. }
  2970. setup( builder ) {
  2971. const properties = builder.getNodeProperties( this );
  2972. properties.referenceNode = this.referenceNode;
  2973. //
  2974. let uvNode = this.uvNode;
  2975. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  2976. uvNode = builder.context.getUV( this );
  2977. }
  2978. if ( ! uvNode ) uvNode = this.getDefaultUV();
  2979. if ( this.updateMatrix === true ) {
  2980. uvNode = this.getTransformedUV( uvNode );
  2981. }
  2982. uvNode = this.setupUV( builder, uvNode );
  2983. //
  2984. let levelNode = this.levelNode;
  2985. if ( levelNode === null && builder.context.getTextureLevel ) {
  2986. levelNode = builder.context.getTextureLevel( this );
  2987. }
  2988. //
  2989. properties.uvNode = uvNode;
  2990. properties.levelNode = levelNode;
  2991. properties.biasNode = this.biasNode;
  2992. properties.compareNode = this.compareNode;
  2993. properties.gradNode = this.gradNode;
  2994. properties.depthNode = this.depthNode;
  2995. }
  2996. generateUV( builder, uvNode ) {
  2997. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  2998. }
  2999. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet ) {
  3000. const texture = this.value;
  3001. let snippet;
  3002. if ( levelSnippet ) {
  3003. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  3004. } else if ( biasSnippet ) {
  3005. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet );
  3006. } else if ( gradSnippet ) {
  3007. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet );
  3008. } else if ( compareSnippet ) {
  3009. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet );
  3010. } else if ( this.sampler === false ) {
  3011. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, depthSnippet );
  3012. } else {
  3013. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet );
  3014. }
  3015. return snippet;
  3016. }
  3017. generate( builder, output ) {
  3018. const properties = builder.getNodeProperties( this );
  3019. const texture = this.value;
  3020. if ( ! texture || texture.isTexture !== true ) {
  3021. throw new Error( 'TextureNode: Need a three.js texture.' );
  3022. }
  3023. const textureProperty = super.generate( builder, 'property' );
  3024. if ( output === 'sampler' ) {
  3025. return textureProperty + '_sampler';
  3026. } else if ( builder.isReference( output ) ) {
  3027. return textureProperty;
  3028. } else {
  3029. const nodeData = builder.getDataFromNode( this );
  3030. let propertyName = nodeData.propertyName;
  3031. if ( propertyName === undefined ) {
  3032. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode } = properties;
  3033. const uvSnippet = this.generateUV( builder, uvNode );
  3034. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  3035. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  3036. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  3037. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  3038. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  3039. const nodeVar = builder.getVarFromNode( this );
  3040. propertyName = builder.getPropertyName( nodeVar );
  3041. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet );
  3042. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  3043. nodeData.snippet = snippet;
  3044. nodeData.propertyName = propertyName;
  3045. }
  3046. let snippet = propertyName;
  3047. const nodeType = this.getNodeType( builder );
  3048. if ( builder.needsToWorkingColorSpace( texture ) ) {
  3049. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  3050. }
  3051. return builder.format( snippet, nodeType, output );
  3052. }
  3053. }
  3054. setSampler( value ) {
  3055. this.sampler = value;
  3056. return this;
  3057. }
  3058. getSampler() {
  3059. return this.sampler;
  3060. }
  3061. // @TODO: Move to TSL
  3062. uv( uvNode ) {
  3063. const textureNode = this.clone();
  3064. textureNode.uvNode = nodeObject( uvNode );
  3065. textureNode.referenceNode = this.getSelf();
  3066. return nodeObject( textureNode );
  3067. }
  3068. blur( amountNode ) {
  3069. const textureNode = this.clone();
  3070. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  3071. textureNode.referenceNode = this.getSelf();
  3072. return nodeObject( textureNode );
  3073. }
  3074. level( levelNode ) {
  3075. const textureNode = this.clone();
  3076. textureNode.levelNode = nodeObject( levelNode );
  3077. textureNode.referenceNode = this.getSelf();
  3078. return nodeObject( textureNode );
  3079. }
  3080. size( levelNode ) {
  3081. return textureSize( this, levelNode );
  3082. }
  3083. bias( biasNode ) {
  3084. const textureNode = this.clone();
  3085. textureNode.biasNode = nodeObject( biasNode );
  3086. textureNode.referenceNode = this.getSelf();
  3087. return nodeObject( textureNode );
  3088. }
  3089. compare( compareNode ) {
  3090. const textureNode = this.clone();
  3091. textureNode.compareNode = nodeObject( compareNode );
  3092. textureNode.referenceNode = this.getSelf();
  3093. return nodeObject( textureNode );
  3094. }
  3095. grad( gradNodeX, gradNodeY ) {
  3096. const textureNode = this.clone();
  3097. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  3098. textureNode.referenceNode = this.getSelf();
  3099. return nodeObject( textureNode );
  3100. }
  3101. depth( depthNode ) {
  3102. const textureNode = this.clone();
  3103. textureNode.depthNode = nodeObject( depthNode );
  3104. textureNode.referenceNode = this.getSelf();
  3105. return nodeObject( textureNode );
  3106. }
  3107. // --
  3108. serialize( data ) {
  3109. super.serialize( data );
  3110. data.value = this.value.toJSON( data.meta ).uuid;
  3111. data.sampler = this.sampler;
  3112. data.updateMatrix = this.updateMatrix;
  3113. data.updateType = this.updateType;
  3114. }
  3115. deserialize( data ) {
  3116. super.deserialize( data );
  3117. this.value = data.meta.textures[ data.value ];
  3118. this.sampler = data.sampler;
  3119. this.updateMatrix = data.updateMatrix;
  3120. this.updateType = data.updateType;
  3121. }
  3122. update() {
  3123. const texture = this.value;
  3124. const matrixUniform = this._matrixUniform;
  3125. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  3126. if ( texture.matrixAutoUpdate === true ) {
  3127. texture.updateMatrix();
  3128. }
  3129. }
  3130. clone() {
  3131. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  3132. newNode.sampler = this.sampler;
  3133. return newNode;
  3134. }
  3135. }
  3136. const texture = /*@__PURE__*/ nodeProxy( TextureNode );
  3137. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  3138. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  3139. const sampler = ( aTexture ) => ( aTexture.isNode === true ? aTexture : texture( aTexture ) ).convert( 'sampler' );
  3140. const cameraNear = /*@__PURE__*/ uniform( 'float' ).label( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  3141. const cameraFar = /*@__PURE__*/ uniform( 'float' ).label( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  3142. const cameraProjectionMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  3143. const cameraProjectionMatrixInverse = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  3144. const cameraViewMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  3145. const cameraWorldMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  3146. const cameraNormalMatrix = /*@__PURE__*/ uniform( 'mat3' ).label( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  3147. const cameraPosition = /*@__PURE__*/ uniform( new Vector3() ).label( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  3148. class Object3DNode extends Node {
  3149. static get type() {
  3150. return 'Object3DNode';
  3151. }
  3152. constructor( scope, object3d = null ) {
  3153. super();
  3154. this.scope = scope;
  3155. this.object3d = object3d;
  3156. this.updateType = NodeUpdateType.OBJECT;
  3157. this._uniformNode = new UniformNode( null );
  3158. }
  3159. getNodeType() {
  3160. const scope = this.scope;
  3161. if ( scope === Object3DNode.WORLD_MATRIX ) {
  3162. return 'mat4';
  3163. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  3164. return 'vec3';
  3165. }
  3166. }
  3167. update( frame ) {
  3168. const object = this.object3d;
  3169. const uniformNode = this._uniformNode;
  3170. const scope = this.scope;
  3171. if ( scope === Object3DNode.WORLD_MATRIX ) {
  3172. uniformNode.value = object.matrixWorld;
  3173. } else if ( scope === Object3DNode.POSITION ) {
  3174. uniformNode.value = uniformNode.value || new Vector3();
  3175. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  3176. } else if ( scope === Object3DNode.SCALE ) {
  3177. uniformNode.value = uniformNode.value || new Vector3();
  3178. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  3179. } else if ( scope === Object3DNode.DIRECTION ) {
  3180. uniformNode.value = uniformNode.value || new Vector3();
  3181. object.getWorldDirection( uniformNode.value );
  3182. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  3183. const camera = frame.camera;
  3184. uniformNode.value = uniformNode.value || new Vector3();
  3185. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  3186. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  3187. }
  3188. }
  3189. generate( builder ) {
  3190. const scope = this.scope;
  3191. if ( scope === Object3DNode.WORLD_MATRIX ) {
  3192. this._uniformNode.nodeType = 'mat4';
  3193. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  3194. this._uniformNode.nodeType = 'vec3';
  3195. }
  3196. return this._uniformNode.build( builder );
  3197. }
  3198. serialize( data ) {
  3199. super.serialize( data );
  3200. data.scope = this.scope;
  3201. }
  3202. deserialize( data ) {
  3203. super.deserialize( data );
  3204. this.scope = data.scope;
  3205. }
  3206. }
  3207. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  3208. Object3DNode.POSITION = 'position';
  3209. Object3DNode.SCALE = 'scale';
  3210. Object3DNode.VIEW_POSITION = 'viewPosition';
  3211. Object3DNode.DIRECTION = 'direction';
  3212. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION );
  3213. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX );
  3214. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION );
  3215. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE );
  3216. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION );
  3217. class ModelNode extends Object3DNode {
  3218. static get type() {
  3219. return 'ModelNode';
  3220. }
  3221. constructor( scope ) {
  3222. super( scope );
  3223. }
  3224. update( frame ) {
  3225. this.object3d = frame.object;
  3226. super.update( frame );
  3227. }
  3228. }
  3229. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  3230. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  3231. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  3232. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  3233. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  3234. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  3235. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  3236. const modelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix ).toVar( 'modelViewMatrix' );
  3237. const highPrecisionModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  3238. builder.context.isHighPrecisionModelViewMatrix = true;
  3239. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  3240. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  3241. } );
  3242. } ).once() )().toVar( 'highPrecisionModelViewMatrix' );
  3243. const highPrecisionModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  3244. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  3245. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  3246. if ( isHighPrecisionModelViewMatrix !== true ) {
  3247. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  3248. }
  3249. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  3250. } );
  3251. } ).once() )().toVar( 'highPrecisionModelNormalMatrix' );
  3252. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  3253. const positionLocal = /*@__PURE__*/ positionGeometry.varying( 'positionLocal' );
  3254. const positionPrevious = /*@__PURE__*/ positionGeometry.varying( 'positionPrevious' );
  3255. const positionWorld = /*@__PURE__*/ modelWorldMatrix.mul( positionLocal ).xyz.varying( 'v_positionWorld' );
  3256. const positionWorldDirection = /*@__PURE__*/ positionLocal.transformDirection( modelWorldMatrix ).varying( 'v_positionWorldDirection' ).normalize().toVar( 'positionWorldDirection' );
  3257. const positionView = /*@__PURE__*/ modelViewMatrix.mul( positionLocal ).xyz.varying( 'v_positionView' );
  3258. const positionViewDirection = /*@__PURE__*/ positionView.negate().varying( 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  3259. class FrontFacingNode extends Node {
  3260. static get type() {
  3261. return 'FrontFacingNode';
  3262. }
  3263. constructor() {
  3264. super( 'bool' );
  3265. this.isFrontFacingNode = true;
  3266. }
  3267. generate( builder ) {
  3268. const { renderer, material } = builder;
  3269. if ( renderer.coordinateSystem === WebGLCoordinateSystem ) {
  3270. if ( material.side === BackSide ) {
  3271. return 'false';
  3272. }
  3273. }
  3274. return builder.getFrontFacing();
  3275. }
  3276. }
  3277. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  3278. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  3279. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  3280. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  3281. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  3282. console.warn( 'TSL.NormalNode: Vertex attribute "normal" not found on geometry.' );
  3283. return vec3( 0, 1, 0 );
  3284. }
  3285. return normalGeometry;
  3286. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  3287. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  3288. const normalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  3289. let node;
  3290. if ( builder.material.flatShading === true ) {
  3291. node = normalFlat;
  3292. } else {
  3293. node = varying( transformNormalToView( normalLocal ), 'v_normalView' ).normalize();
  3294. }
  3295. return node;
  3296. }, 'vec3' ).once() )().toVar( 'normalView' );
  3297. const normalWorld = /*@__PURE__*/ varying( normalView.transformDirection( cameraViewMatrix ), 'v_normalWorld' ).normalize().toVar( 'normalWorld' );
  3298. const transformedNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  3299. return builder.context.setupNormal();
  3300. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedNormalView' );
  3301. const transformedNormalWorld = /*@__PURE__*/ transformedNormalView.transformDirection( cameraViewMatrix ).toVar( 'transformedNormalWorld' );
  3302. const transformedClearcoatNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  3303. return builder.context.setupClearcoatNormal();
  3304. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedClearcoatNormalView' );
  3305. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  3306. const m = mat3( matrix );
  3307. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  3308. return m.mul( transformedNormal ).xyz;
  3309. } );
  3310. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  3311. const modelNormalViewMatrix = builder.renderer.nodes.modelNormalViewMatrix;
  3312. if ( modelNormalViewMatrix !== null ) {
  3313. return modelNormalViewMatrix.transformDirection( normal );
  3314. }
  3315. //
  3316. const transformedNormal = modelNormalMatrix.mul( normal );
  3317. return cameraViewMatrix.transformDirection( transformedNormal );
  3318. } );
  3319. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onRenderUpdate( ( { material } ) => material.refractionRatio );
  3320. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( transformedNormalView );
  3321. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( transformedNormalView, materialRefractionRatio );
  3322. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  3323. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  3324. class CubeTextureNode extends TextureNode {
  3325. static get type() {
  3326. return 'CubeTextureNode';
  3327. }
  3328. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  3329. super( value, uvNode, levelNode, biasNode );
  3330. this.isCubeTextureNode = true;
  3331. }
  3332. getInputType( /*builder*/ ) {
  3333. return 'cubeTexture';
  3334. }
  3335. getDefaultUV() {
  3336. const texture = this.value;
  3337. if ( texture.mapping === CubeReflectionMapping ) {
  3338. return reflectVector;
  3339. } else if ( texture.mapping === CubeRefractionMapping ) {
  3340. return refractVector;
  3341. } else {
  3342. console.error( 'THREE.CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  3343. return vec3( 0, 0, 0 );
  3344. }
  3345. }
  3346. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  3347. setupUV( builder, uvNode ) {
  3348. const texture = this.value;
  3349. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  3350. return vec3( uvNode.x.negate(), uvNode.yz );
  3351. } else {
  3352. return uvNode;
  3353. }
  3354. }
  3355. generateUV( builder, cubeUV ) {
  3356. return cubeUV.build( builder, 'vec3' );
  3357. }
  3358. }
  3359. const cubeTexture = /*@__PURE__*/ nodeProxy( CubeTextureNode );
  3360. class BufferNode extends UniformNode {
  3361. static get type() {
  3362. return 'BufferNode';
  3363. }
  3364. constructor( value, bufferType, bufferCount = 0 ) {
  3365. super( value, bufferType );
  3366. this.isBufferNode = true;
  3367. this.bufferType = bufferType;
  3368. this.bufferCount = bufferCount;
  3369. }
  3370. getElementType( builder ) {
  3371. return this.getNodeType( builder );
  3372. }
  3373. getInputType( /*builder*/ ) {
  3374. return 'buffer';
  3375. }
  3376. }
  3377. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  3378. class UniformArrayElementNode extends ArrayElementNode {
  3379. static get type() {
  3380. return 'UniformArrayElementNode';
  3381. }
  3382. constructor( arrayBuffer, indexNode ) {
  3383. super( arrayBuffer, indexNode );
  3384. this.isArrayBufferElementNode = true;
  3385. }
  3386. generate( builder ) {
  3387. const snippet = super.generate( builder );
  3388. const type = this.getNodeType();
  3389. return builder.format( snippet, 'vec4', type );
  3390. }
  3391. }
  3392. class UniformArrayNode extends BufferNode {
  3393. static get type() {
  3394. return 'UniformArrayNode';
  3395. }
  3396. constructor( value, elementType = null ) {
  3397. super( null, 'vec4' );
  3398. this.array = value;
  3399. this.elementType = elementType;
  3400. this._elementType = null;
  3401. this._elementLength = 0;
  3402. this.updateType = NodeUpdateType.RENDER;
  3403. this.isArrayBufferNode = true;
  3404. }
  3405. getElementType() {
  3406. return this.elementType || this._elementType;
  3407. }
  3408. getElementLength() {
  3409. return this._elementLength;
  3410. }
  3411. update( /*frame*/ ) {
  3412. const { array, value } = this;
  3413. const elementLength = this.getElementLength();
  3414. const elementType = this.getElementType();
  3415. if ( elementLength === 1 ) {
  3416. for ( let i = 0; i < array.length; i ++ ) {
  3417. const index = i * 4;
  3418. value[ index ] = array[ i ];
  3419. }
  3420. } else if ( elementType === 'color' ) {
  3421. for ( let i = 0; i < array.length; i ++ ) {
  3422. const index = i * 4;
  3423. const vector = array[ i ];
  3424. value[ index ] = vector.r;
  3425. value[ index + 1 ] = vector.g;
  3426. value[ index + 2 ] = vector.b || 0;
  3427. //value[ index + 3 ] = vector.a || 0;
  3428. }
  3429. } else {
  3430. for ( let i = 0; i < array.length; i ++ ) {
  3431. const index = i * 4;
  3432. const vector = array[ i ];
  3433. value[ index ] = vector.x;
  3434. value[ index + 1 ] = vector.y;
  3435. value[ index + 2 ] = vector.z || 0;
  3436. value[ index + 3 ] = vector.w || 0;
  3437. }
  3438. }
  3439. }
  3440. setup( builder ) {
  3441. const length = this.array.length;
  3442. this._elementType = this.elementType === null ? getValueType( this.array[ 0 ] ) : this.elementType;
  3443. this._elementLength = builder.getTypeLength( this._elementType );
  3444. let arrayType = Float32Array;
  3445. if ( this._elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  3446. else if ( this._elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  3447. this.value = new arrayType( length * 4 );
  3448. this.bufferCount = length;
  3449. this.bufferType = builder.changeComponentType( 'vec4', builder.getComponentType( this._elementType ) );
  3450. return super.setup( builder );
  3451. }
  3452. element( indexNode ) {
  3453. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  3454. }
  3455. }
  3456. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  3457. //
  3458. const uniforms = ( values, nodeType ) => { // @deprecated, r168
  3459. console.warn( 'TSL.UniformArrayNode: uniforms() has been renamed to uniformArray().' );
  3460. return nodeObject( new UniformArrayNode( values, nodeType ) );
  3461. };
  3462. class ReferenceElementNode extends ArrayElementNode {
  3463. static get type() {
  3464. return 'ReferenceElementNode';
  3465. }
  3466. constructor( referenceNode, indexNode ) {
  3467. super( referenceNode, indexNode );
  3468. this.referenceNode = referenceNode;
  3469. this.isReferenceElementNode = true;
  3470. }
  3471. getNodeType() {
  3472. return this.referenceNode.uniformType;
  3473. }
  3474. generate( builder ) {
  3475. const snippet = super.generate( builder );
  3476. const arrayType = this.referenceNode.getNodeType();
  3477. const elementType = this.getNodeType();
  3478. return builder.format( snippet, arrayType, elementType );
  3479. }
  3480. }
  3481. // TODO: Extends this from ReferenceBaseNode
  3482. class ReferenceNode extends Node {
  3483. static get type() {
  3484. return 'ReferenceNode';
  3485. }
  3486. constructor( property, uniformType, object = null, count = null ) {
  3487. super();
  3488. this.property = property;
  3489. this.uniformType = uniformType;
  3490. this.object = object;
  3491. this.count = count;
  3492. this.properties = property.split( '.' );
  3493. this.reference = object;
  3494. this.node = null;
  3495. this.group = null;
  3496. this.name = null;
  3497. this.updateType = NodeUpdateType.OBJECT;
  3498. }
  3499. element( indexNode ) {
  3500. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  3501. }
  3502. setGroup( group ) {
  3503. this.group = group;
  3504. return this;
  3505. }
  3506. label( name ) {
  3507. this.name = name;
  3508. return this;
  3509. }
  3510. setNodeType( uniformType ) {
  3511. let node = null;
  3512. if ( this.count !== null ) {
  3513. node = buffer( null, uniformType, this.count );
  3514. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  3515. node = uniformArray( null, uniformType );
  3516. } else if ( uniformType === 'texture' ) {
  3517. node = texture( null );
  3518. } else if ( uniformType === 'cubeTexture' ) {
  3519. node = cubeTexture( null );
  3520. } else {
  3521. node = uniform( null, uniformType );
  3522. }
  3523. if ( this.group !== null ) {
  3524. node.setGroup( this.group );
  3525. }
  3526. if ( this.name !== null ) node.label( this.name );
  3527. this.node = node.getSelf();
  3528. }
  3529. getNodeType( builder ) {
  3530. if ( this.node === null ) {
  3531. this.updateReference( builder );
  3532. this.updateValue();
  3533. }
  3534. return this.node.getNodeType( builder );
  3535. }
  3536. getValueFromReference( object = this.reference ) {
  3537. const { properties } = this;
  3538. let value = object[ properties[ 0 ] ];
  3539. for ( let i = 1; i < properties.length; i ++ ) {
  3540. value = value[ properties[ i ] ];
  3541. }
  3542. return value;
  3543. }
  3544. updateReference( state ) {
  3545. this.reference = this.object !== null ? this.object : state.object;
  3546. return this.reference;
  3547. }
  3548. setup() {
  3549. this.updateValue();
  3550. return this.node;
  3551. }
  3552. update( /*frame*/ ) {
  3553. this.updateValue();
  3554. }
  3555. updateValue() {
  3556. if ( this.node === null ) this.setNodeType( this.uniformType );
  3557. const value = this.getValueFromReference();
  3558. if ( Array.isArray( value ) ) {
  3559. this.node.array = value;
  3560. } else {
  3561. this.node.value = value;
  3562. }
  3563. }
  3564. }
  3565. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  3566. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  3567. class MaterialReferenceNode extends ReferenceNode {
  3568. static get type() {
  3569. return 'MaterialReferenceNode';
  3570. }
  3571. constructor( property, inputType, material = null ) {
  3572. super( property, inputType, material );
  3573. this.material = material;
  3574. //this.updateType = NodeUpdateType.RENDER;
  3575. this.isMaterialReferenceNode = true;
  3576. }
  3577. /*setNodeType( node ) {
  3578. super.setNodeType( node );
  3579. this.node.groupNode = renderGroup;
  3580. }*/
  3581. updateReference( state ) {
  3582. this.reference = this.material !== null ? this.material : state.material;
  3583. return this.reference;
  3584. }
  3585. }
  3586. const materialReference = ( name, type, material ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  3587. const tangentGeometry = /*@__PURE__*/ Fn( ( builder ) => {
  3588. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  3589. builder.geometry.computeTangents();
  3590. }
  3591. return attribute( 'tangent', 'vec4' );
  3592. } )();
  3593. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  3594. const tangentView = /*@__PURE__*/ modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.varying( 'v_tangentView' ).normalize().toVar( 'tangentView' );
  3595. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).varying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  3596. const transformedTangentView = /*@__PURE__*/ tangentView.toVar( 'transformedTangentView' );
  3597. const transformedTangentWorld = /*@__PURE__*/ transformedTangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedTangentWorld' );
  3598. const getBitangent = ( crossNormalTangent ) => crossNormalTangent.mul( tangentGeometry.w ).xyz;
  3599. const bitangentGeometry = /*@__PURE__*/ varying( getBitangent( normalGeometry.cross( tangentGeometry ) ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  3600. const bitangentLocal = /*@__PURE__*/ varying( getBitangent( normalLocal.cross( tangentLocal ) ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  3601. const bitangentView = /*@__PURE__*/ varying( getBitangent( normalView.cross( tangentView ) ), 'v_bitangentView' ).normalize().toVar( 'bitangentView' );
  3602. const bitangentWorld = /*@__PURE__*/ varying( getBitangent( normalWorld.cross( tangentWorld ) ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  3603. const transformedBitangentView = /*@__PURE__*/ getBitangent( transformedNormalView.cross( transformedTangentView ) ).normalize().toVar( 'transformedBitangentView' );
  3604. const transformedBitangentWorld = /*@__PURE__*/ transformedBitangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedBitangentWorld' );
  3605. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView );
  3606. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  3607. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  3608. const transformedBentNormalView = /*@__PURE__*/ ( () => {
  3609. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  3610. let bentNormal = anisotropyB.cross( positionViewDirection );
  3611. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  3612. bentNormal = mix( bentNormal, transformedNormalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  3613. return bentNormal;
  3614. } )();
  3615. // Normal Mapping Without Precomputed Tangents
  3616. // http://www.thetenthplanet.de/archives/1180
  3617. const perturbNormal2Arb = /*@__PURE__*/ Fn( ( inputs ) => {
  3618. const { eye_pos, surf_norm, mapN, uv } = inputs;
  3619. const q0 = eye_pos.dFdx();
  3620. const q1 = eye_pos.dFdy();
  3621. const st0 = uv.dFdx();
  3622. const st1 = uv.dFdy();
  3623. const N = surf_norm; // normalized
  3624. const q1perp = q1.cross( N );
  3625. const q0perp = N.cross( q0 );
  3626. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  3627. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  3628. const det = T.dot( T ).max( B.dot( B ) );
  3629. const scale = faceDirection.mul( det.inverseSqrt() );
  3630. return add( T.mul( mapN.x, scale ), B.mul( mapN.y, scale ), N.mul( mapN.z ) ).normalize();
  3631. } );
  3632. class NormalMapNode extends TempNode {
  3633. static get type() {
  3634. return 'NormalMapNode';
  3635. }
  3636. constructor( node, scaleNode = null ) {
  3637. super( 'vec3' );
  3638. this.node = node;
  3639. this.scaleNode = scaleNode;
  3640. this.normalMapType = TangentSpaceNormalMap;
  3641. }
  3642. setup( builder ) {
  3643. const { normalMapType, scaleNode } = this;
  3644. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  3645. if ( scaleNode !== null ) {
  3646. normalMap = vec3( normalMap.xy.mul( scaleNode ), normalMap.z );
  3647. }
  3648. let outputNode = null;
  3649. if ( normalMapType === ObjectSpaceNormalMap ) {
  3650. outputNode = transformNormalToView( normalMap );
  3651. } else if ( normalMapType === TangentSpaceNormalMap ) {
  3652. const tangent = builder.hasGeometryAttribute( 'tangent' );
  3653. if ( tangent === true ) {
  3654. outputNode = TBNViewMatrix.mul( normalMap ).normalize();
  3655. } else {
  3656. outputNode = perturbNormal2Arb( {
  3657. eye_pos: positionView,
  3658. surf_norm: normalView,
  3659. mapN: normalMap,
  3660. uv: uv()
  3661. } );
  3662. }
  3663. }
  3664. return outputNode;
  3665. }
  3666. }
  3667. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode );
  3668. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  3669. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  3670. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  3671. // It's used to preserve the same TextureNode instance
  3672. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv() ), forceUVContext: true } );
  3673. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  3674. return vec2(
  3675. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  3676. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  3677. ).mul( bumpScale );
  3678. } );
  3679. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  3680. const perturbNormalArb = Fn( ( inputs ) => {
  3681. const { surf_pos, surf_norm, dHdxy } = inputs;
  3682. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  3683. const vSigmaX = surf_pos.dFdx().normalize();
  3684. const vSigmaY = surf_pos.dFdy().normalize();
  3685. const vN = surf_norm; // normalized
  3686. const R1 = vSigmaY.cross( vN );
  3687. const R2 = vN.cross( vSigmaX );
  3688. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  3689. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  3690. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  3691. } );
  3692. class BumpMapNode extends TempNode {
  3693. static get type() {
  3694. return 'BumpMapNode';
  3695. }
  3696. constructor( textureNode, scaleNode = null ) {
  3697. super( 'vec3' );
  3698. this.textureNode = textureNode;
  3699. this.scaleNode = scaleNode;
  3700. }
  3701. setup() {
  3702. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  3703. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  3704. return perturbNormalArb( {
  3705. surf_pos: positionView,
  3706. surf_norm: normalView,
  3707. dHdxy
  3708. } );
  3709. }
  3710. }
  3711. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode );
  3712. const _propertyCache = new Map();
  3713. class MaterialNode extends Node {
  3714. static get type() {
  3715. return 'MaterialNode';
  3716. }
  3717. constructor( scope ) {
  3718. super();
  3719. this.scope = scope;
  3720. }
  3721. getCache( property, type ) {
  3722. let node = _propertyCache.get( property );
  3723. if ( node === undefined ) {
  3724. node = materialReference( property, type );
  3725. _propertyCache.set( property, node );
  3726. }
  3727. return node;
  3728. }
  3729. getFloat( property ) {
  3730. return this.getCache( property, 'float' );
  3731. }
  3732. getColor( property ) {
  3733. return this.getCache( property, 'color' );
  3734. }
  3735. getTexture( property ) {
  3736. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  3737. }
  3738. setup( builder ) {
  3739. const material = builder.context.material;
  3740. const scope = this.scope;
  3741. let node = null;
  3742. if ( scope === MaterialNode.COLOR ) {
  3743. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  3744. if ( material.map && material.map.isTexture === true ) {
  3745. node = colorNode.mul( this.getTexture( 'map' ) );
  3746. } else {
  3747. node = colorNode;
  3748. }
  3749. } else if ( scope === MaterialNode.OPACITY ) {
  3750. const opacityNode = this.getFloat( scope );
  3751. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  3752. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  3753. } else {
  3754. node = opacityNode;
  3755. }
  3756. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  3757. if ( material.specularMap && material.specularMap.isTexture === true ) {
  3758. node = this.getTexture( 'specular' ).r;
  3759. } else {
  3760. node = float( 1 );
  3761. }
  3762. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  3763. const specularIntensity = this.getFloat( scope );
  3764. if ( material.specularMap ) {
  3765. node = specularIntensity.mul( this.getTexture( scope ).a );
  3766. } else {
  3767. node = specularIntensity;
  3768. }
  3769. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  3770. const specularColorNode = this.getColor( scope );
  3771. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  3772. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  3773. } else {
  3774. node = specularColorNode;
  3775. }
  3776. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  3777. const roughnessNode = this.getFloat( scope );
  3778. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  3779. node = roughnessNode.mul( this.getTexture( scope ).g );
  3780. } else {
  3781. node = roughnessNode;
  3782. }
  3783. } else if ( scope === MaterialNode.METALNESS ) {
  3784. const metalnessNode = this.getFloat( scope );
  3785. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  3786. node = metalnessNode.mul( this.getTexture( scope ).b );
  3787. } else {
  3788. node = metalnessNode;
  3789. }
  3790. } else if ( scope === MaterialNode.EMISSIVE ) {
  3791. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  3792. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  3793. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  3794. node = emissiveNode.mul( this.getTexture( scope ) );
  3795. } else {
  3796. node = emissiveNode;
  3797. }
  3798. } else if ( scope === MaterialNode.NORMAL ) {
  3799. if ( material.normalMap ) {
  3800. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  3801. node.normalMapType = material.normalMapType;
  3802. } else if ( material.bumpMap ) {
  3803. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  3804. } else {
  3805. node = normalView;
  3806. }
  3807. } else if ( scope === MaterialNode.CLEARCOAT ) {
  3808. const clearcoatNode = this.getFloat( scope );
  3809. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  3810. node = clearcoatNode.mul( this.getTexture( scope ).r );
  3811. } else {
  3812. node = clearcoatNode;
  3813. }
  3814. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  3815. const clearcoatRoughnessNode = this.getFloat( scope );
  3816. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  3817. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  3818. } else {
  3819. node = clearcoatRoughnessNode;
  3820. }
  3821. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  3822. if ( material.clearcoatNormalMap ) {
  3823. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  3824. } else {
  3825. node = normalView;
  3826. }
  3827. } else if ( scope === MaterialNode.SHEEN ) {
  3828. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  3829. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  3830. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  3831. } else {
  3832. node = sheenNode;
  3833. }
  3834. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  3835. const sheenRoughnessNode = this.getFloat( scope );
  3836. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  3837. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  3838. } else {
  3839. node = sheenRoughnessNode;
  3840. }
  3841. node = node.clamp( 0.07, 1.0 );
  3842. } else if ( scope === MaterialNode.ANISOTROPY ) {
  3843. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  3844. const anisotropyPolar = this.getTexture( scope );
  3845. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  3846. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  3847. } else {
  3848. node = materialAnisotropyVector;
  3849. }
  3850. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  3851. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  3852. if ( material.iridescenceThicknessMap ) {
  3853. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  3854. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  3855. } else {
  3856. node = iridescenceThicknessMaximum;
  3857. }
  3858. } else if ( scope === MaterialNode.TRANSMISSION ) {
  3859. const transmissionNode = this.getFloat( scope );
  3860. if ( material.transmissionMap ) {
  3861. node = transmissionNode.mul( this.getTexture( scope ).r );
  3862. } else {
  3863. node = transmissionNode;
  3864. }
  3865. } else if ( scope === MaterialNode.THICKNESS ) {
  3866. const thicknessNode = this.getFloat( scope );
  3867. if ( material.thicknessMap ) {
  3868. node = thicknessNode.mul( this.getTexture( scope ).g );
  3869. } else {
  3870. node = thicknessNode;
  3871. }
  3872. } else if ( scope === MaterialNode.IOR ) {
  3873. node = this.getFloat( scope );
  3874. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  3875. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  3876. } else if ( scope === MaterialNode.AO_MAP ) {
  3877. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  3878. } else {
  3879. const outputType = this.getNodeType( builder );
  3880. node = this.getCache( scope, outputType );
  3881. }
  3882. return node;
  3883. }
  3884. }
  3885. MaterialNode.ALPHA_TEST = 'alphaTest';
  3886. MaterialNode.COLOR = 'color';
  3887. MaterialNode.OPACITY = 'opacity';
  3888. MaterialNode.SHININESS = 'shininess';
  3889. MaterialNode.SPECULAR = 'specular';
  3890. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  3891. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  3892. MaterialNode.SPECULAR_COLOR = 'specularColor';
  3893. MaterialNode.REFLECTIVITY = 'reflectivity';
  3894. MaterialNode.ROUGHNESS = 'roughness';
  3895. MaterialNode.METALNESS = 'metalness';
  3896. MaterialNode.NORMAL = 'normal';
  3897. MaterialNode.CLEARCOAT = 'clearcoat';
  3898. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  3899. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  3900. MaterialNode.EMISSIVE = 'emissive';
  3901. MaterialNode.ROTATION = 'rotation';
  3902. MaterialNode.SHEEN = 'sheen';
  3903. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  3904. MaterialNode.ANISOTROPY = 'anisotropy';
  3905. MaterialNode.IRIDESCENCE = 'iridescence';
  3906. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  3907. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  3908. MaterialNode.IOR = 'ior';
  3909. MaterialNode.TRANSMISSION = 'transmission';
  3910. MaterialNode.THICKNESS = 'thickness';
  3911. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  3912. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  3913. MaterialNode.LINE_SCALE = 'scale';
  3914. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  3915. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  3916. MaterialNode.LINE_WIDTH = 'linewidth';
  3917. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  3918. MaterialNode.POINT_WIDTH = 'pointWidth';
  3919. MaterialNode.DISPERSION = 'dispersion';
  3920. MaterialNode.LIGHT_MAP = 'light';
  3921. MaterialNode.AO_MAP = 'ao';
  3922. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  3923. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  3924. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  3925. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  3926. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  3927. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  3928. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  3929. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  3930. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  3931. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  3932. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  3933. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  3934. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL ).context( { getUV: null } );
  3935. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  3936. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  3937. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL ).context( { getUV: null } );
  3938. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  3939. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  3940. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  3941. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  3942. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  3943. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  3944. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  3945. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  3946. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  3947. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  3948. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  3949. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  3950. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  3951. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  3952. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  3953. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  3954. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  3955. const materialPointWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_WIDTH );
  3956. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  3957. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  3958. const materialAOMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO_MAP );
  3959. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  3960. return frame.material;
  3961. } ).onRenderUpdate( function ( { material } ) {
  3962. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  3963. } );
  3964. class ModelViewProjectionNode extends TempNode {
  3965. static get type() {
  3966. return 'ModelViewProjectionNode';
  3967. }
  3968. constructor( positionNode = null ) {
  3969. super( 'vec4' );
  3970. this.positionNode = positionNode;
  3971. }
  3972. setup( builder ) {
  3973. if ( builder.shaderStage === 'fragment' ) {
  3974. return varying( builder.context.mvp );
  3975. }
  3976. const position = this.positionNode || positionLocal;
  3977. const viewMatrix = builder.renderer.nodes.modelViewMatrix || modelViewMatrix;
  3978. return cameraProjectionMatrix.mul( viewMatrix ).mul( position );
  3979. }
  3980. }
  3981. const modelViewProjection = /*@__PURE__*/ nodeProxy( ModelViewProjectionNode );
  3982. class IndexNode extends Node {
  3983. static get type() {
  3984. return 'IndexNode';
  3985. }
  3986. constructor( scope ) {
  3987. super( 'uint' );
  3988. this.scope = scope;
  3989. this.isInstanceIndexNode = true;
  3990. }
  3991. generate( builder ) {
  3992. const nodeType = this.getNodeType( builder );
  3993. const scope = this.scope;
  3994. let propertyName;
  3995. if ( scope === IndexNode.VERTEX ) {
  3996. // The index of a vertex within a mesh.
  3997. propertyName = builder.getVertexIndex();
  3998. } else if ( scope === IndexNode.INSTANCE ) {
  3999. // The index of either a mesh instance or an invocation of a compute shader.
  4000. propertyName = builder.getInstanceIndex();
  4001. } else if ( scope === IndexNode.DRAW ) {
  4002. // The index of a draw call.
  4003. propertyName = builder.getDrawIndex();
  4004. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  4005. // The index of a compute invocation within the scope of a workgroup load.
  4006. propertyName = builder.getInvocationLocalIndex();
  4007. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  4008. // The index of a compute invocation within the scope of a subgroup.
  4009. propertyName = builder.getInvocationSubgroupIndex();
  4010. } else if ( scope === IndexNode.SUBGROUP ) {
  4011. // The index of the subgroup the current compute invocation belongs to.
  4012. propertyName = builder.getSubgroupIndex();
  4013. } else {
  4014. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  4015. }
  4016. let output;
  4017. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  4018. output = propertyName;
  4019. } else {
  4020. const nodeVarying = varying( this );
  4021. output = nodeVarying.build( builder, nodeType );
  4022. }
  4023. return output;
  4024. }
  4025. }
  4026. IndexNode.VERTEX = 'vertex';
  4027. IndexNode.INSTANCE = 'instance';
  4028. IndexNode.SUBGROUP = 'subgroup';
  4029. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  4030. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  4031. IndexNode.DRAW = 'draw';
  4032. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  4033. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  4034. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  4035. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  4036. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  4037. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  4038. class InstanceNode extends Node {
  4039. static get type() {
  4040. return 'InstanceNode';
  4041. }
  4042. constructor( count, instanceMatrix, instanceColor ) {
  4043. super( 'void' );
  4044. this.count = count;
  4045. this.instanceMatrix = instanceMatrix;
  4046. this.instanceColor = instanceColor;
  4047. this.instanceMatrixNode = null;
  4048. this.instanceColorNode = null;
  4049. this.updateType = NodeUpdateType.FRAME;
  4050. this.buffer = null;
  4051. this.bufferColor = null;
  4052. }
  4053. setup( builder ) {
  4054. const { count, instanceMatrix, instanceColor } = this;
  4055. let { instanceMatrixNode, instanceColorNode } = this;
  4056. if ( instanceMatrixNode === null ) {
  4057. // 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.
  4058. if ( count <= 1000 ) {
  4059. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  4060. } else {
  4061. const buffer = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  4062. this.buffer = buffer;
  4063. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  4064. const instanceBuffers = [
  4065. // F.Signature -> bufferAttribute( array, type, stride, offset )
  4066. bufferFn( buffer, 'vec4', 16, 0 ),
  4067. bufferFn( buffer, 'vec4', 16, 4 ),
  4068. bufferFn( buffer, 'vec4', 16, 8 ),
  4069. bufferFn( buffer, 'vec4', 16, 12 )
  4070. ];
  4071. instanceMatrixNode = mat4( ...instanceBuffers );
  4072. }
  4073. this.instanceMatrixNode = instanceMatrixNode;
  4074. }
  4075. if ( instanceColor && instanceColorNode === null ) {
  4076. const buffer = new InstancedBufferAttribute( instanceColor.array, 3 );
  4077. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  4078. this.bufferColor = buffer;
  4079. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  4080. this.instanceColorNode = instanceColorNode;
  4081. }
  4082. // POSITION
  4083. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  4084. positionLocal.assign( instancePosition );
  4085. // NORMAL
  4086. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  4087. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  4088. // ASSIGNS
  4089. normalLocal.assign( instanceNormal );
  4090. }
  4091. // COLOR
  4092. if ( this.instanceColorNode !== null ) {
  4093. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  4094. }
  4095. }
  4096. update( /*frame*/ ) {
  4097. if ( this.instanceMatrix.usage !== DynamicDrawUsage && this.buffer != null && this.instanceMatrix.version !== this.buffer.version ) {
  4098. this.buffer.version = this.instanceMatrix.version;
  4099. }
  4100. if ( this.instanceColor && this.instanceColor.usage !== DynamicDrawUsage && this.bufferColor != null && this.instanceColor.version !== this.bufferColor.version ) {
  4101. this.bufferColor.version = this.instanceColor.version;
  4102. }
  4103. }
  4104. }
  4105. const instance = /*@__PURE__*/ nodeProxy( InstanceNode );
  4106. class InstancedMeshNode extends InstanceNode {
  4107. static get type() {
  4108. return 'InstancedMeshNode';
  4109. }
  4110. constructor( instanceMesh ) {
  4111. const { count, instanceMatrix, instanceColor } = instanceMesh;
  4112. super( count, instanceMatrix, instanceColor );
  4113. this.instanceMesh = instanceMesh;
  4114. }
  4115. }
  4116. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode );
  4117. class BatchNode extends Node {
  4118. static get type() {
  4119. return 'BatchNode';
  4120. }
  4121. constructor( batchMesh ) {
  4122. super( 'void' );
  4123. this.batchMesh = batchMesh;
  4124. this.batchingIdNode = null;
  4125. }
  4126. setup( builder ) {
  4127. // POSITION
  4128. if ( this.batchingIdNode === null ) {
  4129. if ( builder.getDrawIndex() === null ) {
  4130. this.batchingIdNode = instanceIndex;
  4131. } else {
  4132. this.batchingIdNode = drawIndex;
  4133. }
  4134. }
  4135. const getIndirectIndex = Fn( ( [ id ] ) => {
  4136. const size = textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 );
  4137. const x = int( id ).modInt( int( size ) );
  4138. const y = int( id ).div( int( size ) );
  4139. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  4140. } ).setLayout( {
  4141. name: 'getIndirectIndex',
  4142. type: 'uint',
  4143. inputs: [
  4144. { name: 'id', type: 'int' }
  4145. ]
  4146. } );
  4147. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  4148. const matricesTexture = this.batchMesh._matricesTexture;
  4149. const size = textureSize( textureLoad( matricesTexture ), 0 );
  4150. const j = float( indirectId ).mul( 4 ).toInt().toVar();
  4151. const x = j.modInt( size );
  4152. const y = j.div( int( size ) );
  4153. const batchingMatrix = mat4(
  4154. textureLoad( matricesTexture, ivec2( x, y ) ),
  4155. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  4156. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  4157. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  4158. );
  4159. const colorsTexture = this.batchMesh._colorsTexture;
  4160. if ( colorsTexture !== null ) {
  4161. const getBatchingColor = Fn( ( [ id ] ) => {
  4162. const size = textureSize( textureLoad( colorsTexture ), 0 ).x;
  4163. const j = id;
  4164. const x = j.modInt( size );
  4165. const y = j.div( size );
  4166. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  4167. } ).setLayout( {
  4168. name: 'getBatchingColor',
  4169. type: 'vec3',
  4170. inputs: [
  4171. { name: 'id', type: 'int' }
  4172. ]
  4173. } );
  4174. const color = getBatchingColor( indirectId );
  4175. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  4176. }
  4177. const bm = mat3( batchingMatrix );
  4178. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  4179. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  4180. const batchingNormal = bm.mul( transformedNormal ).xyz;
  4181. normalLocal.assign( batchingNormal );
  4182. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  4183. tangentLocal.mulAssign( bm );
  4184. }
  4185. }
  4186. }
  4187. const batch = /*@__PURE__*/ nodeProxy( BatchNode );
  4188. const _frameId = new WeakMap();
  4189. class SkinningNode extends Node {
  4190. static get type() {
  4191. return 'SkinningNode';
  4192. }
  4193. constructor( skinnedMesh, useReference = false ) {
  4194. super( 'void' );
  4195. this.skinnedMesh = skinnedMesh;
  4196. this.useReference = useReference;
  4197. this.updateType = NodeUpdateType.OBJECT;
  4198. //
  4199. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  4200. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  4201. let bindMatrixNode, bindMatrixInverseNode, boneMatricesNode;
  4202. if ( useReference ) {
  4203. bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  4204. bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  4205. boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  4206. } else {
  4207. bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  4208. bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  4209. boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  4210. }
  4211. this.bindMatrixNode = bindMatrixNode;
  4212. this.bindMatrixInverseNode = bindMatrixInverseNode;
  4213. this.boneMatricesNode = boneMatricesNode;
  4214. this.previousBoneMatricesNode = null;
  4215. }
  4216. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = positionLocal ) {
  4217. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  4218. const boneMatX = boneMatrices.element( skinIndexNode.x );
  4219. const boneMatY = boneMatrices.element( skinIndexNode.y );
  4220. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  4221. const boneMatW = boneMatrices.element( skinIndexNode.w );
  4222. // POSITION
  4223. const skinVertex = bindMatrixNode.mul( position );
  4224. const skinned = add(
  4225. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  4226. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  4227. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  4228. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  4229. );
  4230. return bindMatrixInverseNode.mul( skinned ).xyz;
  4231. }
  4232. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  4233. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  4234. const boneMatX = boneMatrices.element( skinIndexNode.x );
  4235. const boneMatY = boneMatrices.element( skinIndexNode.y );
  4236. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  4237. const boneMatW = boneMatrices.element( skinIndexNode.w );
  4238. // NORMAL
  4239. let skinMatrix = add(
  4240. skinWeightNode.x.mul( boneMatX ),
  4241. skinWeightNode.y.mul( boneMatY ),
  4242. skinWeightNode.z.mul( boneMatZ ),
  4243. skinWeightNode.w.mul( boneMatW )
  4244. );
  4245. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  4246. return skinMatrix.transformDirection( normal ).xyz;
  4247. }
  4248. getPreviousSkinnedPosition( builder ) {
  4249. const skinnedMesh = builder.object;
  4250. if ( this.previousBoneMatricesNode === null ) {
  4251. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  4252. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  4253. }
  4254. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  4255. }
  4256. needsPreviousBoneMatrices( builder ) {
  4257. const mrt = builder.renderer.getMRT();
  4258. return mrt && mrt.has( 'velocity' );
  4259. }
  4260. setup( builder ) {
  4261. if ( this.needsPreviousBoneMatrices( builder ) ) {
  4262. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  4263. }
  4264. const skinPosition = this.getSkinnedPosition();
  4265. positionLocal.assign( skinPosition );
  4266. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  4267. const skinNormal = this.getSkinnedNormal();
  4268. normalLocal.assign( skinNormal );
  4269. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  4270. tangentLocal.assign( skinNormal );
  4271. }
  4272. }
  4273. }
  4274. generate( builder, output ) {
  4275. if ( output !== 'void' ) {
  4276. return positionLocal.build( builder, output );
  4277. }
  4278. }
  4279. update( frame ) {
  4280. const object = this.useReference ? frame.object : this.skinnedMesh;
  4281. const skeleton = object.skeleton;
  4282. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  4283. _frameId.set( skeleton, frame.frameId );
  4284. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  4285. skeleton.update();
  4286. }
  4287. }
  4288. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  4289. const skinningReference = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh, true ) );
  4290. class LoopNode extends Node {
  4291. static get type() {
  4292. return 'LoopNode';
  4293. }
  4294. constructor( params = [] ) {
  4295. super();
  4296. this.params = params;
  4297. }
  4298. getVarName( index ) {
  4299. return String.fromCharCode( 'i'.charCodeAt() + index );
  4300. }
  4301. getProperties( builder ) {
  4302. const properties = builder.getNodeProperties( this );
  4303. if ( properties.stackNode !== undefined ) return properties;
  4304. //
  4305. const inputs = {};
  4306. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  4307. const param = this.params[ i ];
  4308. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  4309. const type = ( param.isNode !== true && param.type ) || 'int';
  4310. inputs[ name ] = expression( name, type );
  4311. }
  4312. const stack = builder.addStack(); // TODO: cache() it
  4313. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, stack, builder );
  4314. properties.stackNode = stack;
  4315. builder.removeStack();
  4316. return properties;
  4317. }
  4318. getNodeType( builder ) {
  4319. const { returnsNode } = this.getProperties( builder );
  4320. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  4321. }
  4322. setup( builder ) {
  4323. // setup properties
  4324. this.getProperties( builder );
  4325. }
  4326. generate( builder ) {
  4327. const properties = this.getProperties( builder );
  4328. const params = this.params;
  4329. const stackNode = properties.stackNode;
  4330. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  4331. const param = params[ i ];
  4332. let start = null, end = null, name = null, type = null, condition = null, update = null;
  4333. if ( param.isNode ) {
  4334. type = 'int';
  4335. name = this.getVarName( i );
  4336. start = '0';
  4337. end = param.build( builder, type );
  4338. condition = '<';
  4339. } else {
  4340. type = param.type || 'int';
  4341. name = param.name || this.getVarName( i );
  4342. start = param.start;
  4343. end = param.end;
  4344. condition = param.condition;
  4345. update = param.update;
  4346. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  4347. else if ( start && start.isNode ) start = start.build( builder, type );
  4348. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  4349. else if ( end && end.isNode ) end = end.build( builder, type );
  4350. if ( start !== undefined && end === undefined ) {
  4351. start = start + ' - 1';
  4352. end = '0';
  4353. condition = '>=';
  4354. } else if ( end !== undefined && start === undefined ) {
  4355. start = '0';
  4356. condition = '<';
  4357. }
  4358. if ( condition === undefined ) {
  4359. if ( Number( start ) > Number( end ) ) {
  4360. condition = '>=';
  4361. } else {
  4362. condition = '<';
  4363. }
  4364. }
  4365. }
  4366. const internalParam = { start, end, condition };
  4367. //
  4368. const startSnippet = internalParam.start;
  4369. const endSnippet = internalParam.end;
  4370. let declarationSnippet = '';
  4371. let conditionalSnippet = '';
  4372. let updateSnippet = '';
  4373. if ( ! update ) {
  4374. if ( type === 'int' || type === 'uint' ) {
  4375. if ( condition.includes( '<' ) ) update = '++';
  4376. else update = '--';
  4377. } else {
  4378. if ( condition.includes( '<' ) ) update = '+= 1.';
  4379. else update = '-= 1.';
  4380. }
  4381. }
  4382. declarationSnippet += builder.getVar( type, name ) + ' = ' + startSnippet;
  4383. conditionalSnippet += name + ' ' + condition + ' ' + endSnippet;
  4384. updateSnippet += name + ' ' + update;
  4385. const forSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  4386. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + forSnippet + ' {\n\n' ).addFlowTab();
  4387. }
  4388. const stackSnippet = stackNode.build( builder, 'void' );
  4389. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  4390. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  4391. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  4392. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  4393. }
  4394. builder.addFlowTab();
  4395. return returnsSnippet;
  4396. }
  4397. }
  4398. const Loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).append();
  4399. const Continue = () => expression( 'continue' ).append();
  4400. const Break = () => expression( 'break' ).append();
  4401. //
  4402. const loop = ( ...params ) => { // @deprecated, r168
  4403. console.warn( 'TSL.LoopNode: loop() has been renamed to Loop().' );
  4404. return Loop( ...params );
  4405. };
  4406. const _morphTextures = /*@__PURE__*/ new WeakMap();
  4407. const _morphVec4 = /*@__PURE__*/ new Vector4();
  4408. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  4409. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  4410. const y = texelIndex.div( width );
  4411. const x = texelIndex.sub( y.mul( width ) );
  4412. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth );
  4413. return bufferAttrib.mul( influence );
  4414. } );
  4415. function getEntry( geometry ) {
  4416. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  4417. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  4418. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  4419. // instead of using attributes, the WebGL 2 code path encodes morph targets
  4420. // into an array of data textures. Each layer represents a single morph target.
  4421. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  4422. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  4423. let entry = _morphTextures.get( geometry );
  4424. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  4425. if ( entry !== undefined ) entry.texture.dispose();
  4426. const morphTargets = geometry.morphAttributes.position || [];
  4427. const morphNormals = geometry.morphAttributes.normal || [];
  4428. const morphColors = geometry.morphAttributes.color || [];
  4429. let vertexDataCount = 0;
  4430. if ( hasMorphPosition === true ) vertexDataCount = 1;
  4431. if ( hasMorphNormals === true ) vertexDataCount = 2;
  4432. if ( hasMorphColors === true ) vertexDataCount = 3;
  4433. let width = geometry.attributes.position.count * vertexDataCount;
  4434. let height = 1;
  4435. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  4436. if ( width > maxTextureSize ) {
  4437. height = Math.ceil( width / maxTextureSize );
  4438. width = maxTextureSize;
  4439. }
  4440. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  4441. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  4442. bufferTexture.type = FloatType;
  4443. bufferTexture.needsUpdate = true;
  4444. // fill buffer
  4445. const vertexDataStride = vertexDataCount * 4;
  4446. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  4447. const morphTarget = morphTargets[ i ];
  4448. const morphNormal = morphNormals[ i ];
  4449. const morphColor = morphColors[ i ];
  4450. const offset = width * height * 4 * i;
  4451. for ( let j = 0; j < morphTarget.count; j ++ ) {
  4452. const stride = j * vertexDataStride;
  4453. if ( hasMorphPosition === true ) {
  4454. _morphVec4.fromBufferAttribute( morphTarget, j );
  4455. buffer[ offset + stride + 0 ] = _morphVec4.x;
  4456. buffer[ offset + stride + 1 ] = _morphVec4.y;
  4457. buffer[ offset + stride + 2 ] = _morphVec4.z;
  4458. buffer[ offset + stride + 3 ] = 0;
  4459. }
  4460. if ( hasMorphNormals === true ) {
  4461. _morphVec4.fromBufferAttribute( morphNormal, j );
  4462. buffer[ offset + stride + 4 ] = _morphVec4.x;
  4463. buffer[ offset + stride + 5 ] = _morphVec4.y;
  4464. buffer[ offset + stride + 6 ] = _morphVec4.z;
  4465. buffer[ offset + stride + 7 ] = 0;
  4466. }
  4467. if ( hasMorphColors === true ) {
  4468. _morphVec4.fromBufferAttribute( morphColor, j );
  4469. buffer[ offset + stride + 8 ] = _morphVec4.x;
  4470. buffer[ offset + stride + 9 ] = _morphVec4.y;
  4471. buffer[ offset + stride + 10 ] = _morphVec4.z;
  4472. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  4473. }
  4474. }
  4475. }
  4476. entry = {
  4477. count: morphTargetsCount,
  4478. texture: bufferTexture,
  4479. stride: vertexDataCount,
  4480. size: new Vector2( width, height )
  4481. };
  4482. _morphTextures.set( geometry, entry );
  4483. function disposeTexture() {
  4484. bufferTexture.dispose();
  4485. _morphTextures.delete( geometry );
  4486. geometry.removeEventListener( 'dispose', disposeTexture );
  4487. }
  4488. geometry.addEventListener( 'dispose', disposeTexture );
  4489. }
  4490. return entry;
  4491. }
  4492. class MorphNode extends Node {
  4493. static get type() {
  4494. return 'MorphNode';
  4495. }
  4496. constructor( mesh ) {
  4497. super( 'void' );
  4498. this.mesh = mesh;
  4499. this.morphBaseInfluence = uniform( 1 );
  4500. this.updateType = NodeUpdateType.OBJECT;
  4501. }
  4502. setup( builder ) {
  4503. const { geometry } = builder;
  4504. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  4505. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  4506. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  4507. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  4508. // nodes
  4509. const { texture: bufferMap, stride, size } = getEntry( geometry );
  4510. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  4511. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  4512. const width = int( size.width );
  4513. Loop( morphTargetsCount, ( { i } ) => {
  4514. const influence = float( 0 ).toVar();
  4515. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  4516. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  4517. } else {
  4518. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  4519. }
  4520. if ( hasMorphPosition === true ) {
  4521. positionLocal.addAssign( getMorph( {
  4522. bufferMap,
  4523. influence,
  4524. stride,
  4525. width,
  4526. depth: i,
  4527. offset: int( 0 )
  4528. } ) );
  4529. }
  4530. if ( hasMorphNormals === true ) {
  4531. normalLocal.addAssign( getMorph( {
  4532. bufferMap,
  4533. influence,
  4534. stride,
  4535. width,
  4536. depth: i,
  4537. offset: int( 1 )
  4538. } ) );
  4539. }
  4540. } );
  4541. }
  4542. update() {
  4543. const morphBaseInfluence = this.morphBaseInfluence;
  4544. if ( this.mesh.geometry.morphTargetsRelative ) {
  4545. morphBaseInfluence.value = 1;
  4546. } else {
  4547. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  4548. }
  4549. }
  4550. }
  4551. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode );
  4552. class LightingNode extends Node {
  4553. static get type() {
  4554. return 'LightingNode';
  4555. }
  4556. constructor() {
  4557. super( 'vec3' );
  4558. this.isLightingNode = true;
  4559. }
  4560. generate( /*builder*/ ) {
  4561. console.warn( 'Abstract function.' );
  4562. }
  4563. }
  4564. class AONode extends LightingNode {
  4565. static get type() {
  4566. return 'AONode';
  4567. }
  4568. constructor( aoNode = null ) {
  4569. super();
  4570. this.aoNode = aoNode;
  4571. }
  4572. setup( builder ) {
  4573. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  4574. }
  4575. }
  4576. class LightingContextNode extends ContextNode {
  4577. static get type() {
  4578. return 'LightingContextNode';
  4579. }
  4580. constructor( node, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  4581. super( node );
  4582. this.lightingModel = lightingModel;
  4583. this.backdropNode = backdropNode;
  4584. this.backdropAlphaNode = backdropAlphaNode;
  4585. this._value = null;
  4586. }
  4587. getContext() {
  4588. const { backdropNode, backdropAlphaNode } = this;
  4589. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  4590. directSpecular = vec3().toVar( 'directSpecular' ),
  4591. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  4592. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  4593. const reflectedLight = {
  4594. directDiffuse,
  4595. directSpecular,
  4596. indirectDiffuse,
  4597. indirectSpecular
  4598. };
  4599. const context = {
  4600. radiance: vec3().toVar( 'radiance' ),
  4601. irradiance: vec3().toVar( 'irradiance' ),
  4602. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  4603. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  4604. reflectedLight,
  4605. backdrop: backdropNode,
  4606. backdropAlpha: backdropAlphaNode
  4607. };
  4608. return context;
  4609. }
  4610. setup( builder ) {
  4611. this.value = this._value || ( this._value = this.getContext() );
  4612. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  4613. return super.setup( builder );
  4614. }
  4615. }
  4616. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  4617. class IrradianceNode extends LightingNode {
  4618. static get type() {
  4619. return 'IrradianceNode';
  4620. }
  4621. constructor( node ) {
  4622. super();
  4623. this.node = node;
  4624. }
  4625. setup( builder ) {
  4626. builder.context.irradiance.addAssign( this.node );
  4627. }
  4628. }
  4629. let screenSizeVec, viewportVec;
  4630. class ScreenNode extends Node {
  4631. static get type() {
  4632. return 'ScreenNode';
  4633. }
  4634. constructor( scope ) {
  4635. super();
  4636. this.scope = scope;
  4637. this.isViewportNode = true;
  4638. }
  4639. getNodeType() {
  4640. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  4641. else return 'vec2';
  4642. }
  4643. getUpdateType() {
  4644. let updateType = NodeUpdateType.NONE;
  4645. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT ) {
  4646. updateType = NodeUpdateType.RENDER;
  4647. }
  4648. this.updateType = updateType;
  4649. return updateType;
  4650. }
  4651. update( { renderer } ) {
  4652. const renderTarget = renderer.getRenderTarget();
  4653. if ( this.scope === ScreenNode.VIEWPORT ) {
  4654. if ( renderTarget !== null ) {
  4655. viewportVec.copy( renderTarget.viewport );
  4656. } else {
  4657. renderer.getViewport( viewportVec );
  4658. viewportVec.multiplyScalar( renderer.getPixelRatio() );
  4659. }
  4660. } else {
  4661. if ( renderTarget !== null ) {
  4662. screenSizeVec.width = renderTarget.width;
  4663. screenSizeVec.height = renderTarget.height;
  4664. } else {
  4665. renderer.getDrawingBufferSize( screenSizeVec );
  4666. }
  4667. }
  4668. }
  4669. setup( /*builder*/ ) {
  4670. const scope = this.scope;
  4671. let output = null;
  4672. if ( scope === ScreenNode.SIZE ) {
  4673. output = uniform( screenSizeVec || ( screenSizeVec = new Vector2() ) );
  4674. } else if ( scope === ScreenNode.VIEWPORT ) {
  4675. output = uniform( viewportVec || ( viewportVec = new Vector4() ) );
  4676. } else {
  4677. output = vec2( screenCoordinate.div( screenSize ) );
  4678. }
  4679. return output;
  4680. }
  4681. generate( builder ) {
  4682. if ( this.scope === ScreenNode.COORDINATE ) {
  4683. let coord = builder.getFragCoord();
  4684. if ( builder.isFlipY() ) {
  4685. // follow webgpu standards
  4686. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  4687. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  4688. }
  4689. return coord;
  4690. }
  4691. return super.generate( builder );
  4692. }
  4693. }
  4694. ScreenNode.COORDINATE = 'coordinate';
  4695. ScreenNode.VIEWPORT = 'viewport';
  4696. ScreenNode.SIZE = 'size';
  4697. ScreenNode.UV = 'uv';
  4698. // Screen
  4699. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  4700. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  4701. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  4702. // Viewport
  4703. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  4704. const viewportSize = viewport.zw;
  4705. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  4706. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  4707. // Deprecated
  4708. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  4709. console.warn( 'TSL.ViewportNode: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  4710. return screenSize;
  4711. }, 'vec2' ).once() )();
  4712. const viewportTopLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  4713. console.warn( 'TSL.ViewportNode: "viewportTopLeft" is deprecated. Use "screenUV" instead.' );
  4714. return screenUV;
  4715. }, 'vec2' ).once() )();
  4716. const viewportBottomLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  4717. console.warn( 'TSL.ViewportNode: "viewportBottomLeft" is deprecated. Use "screenUV.flipY()" instead.' );
  4718. return screenUV.flipY();
  4719. }, 'vec2' ).once() )();
  4720. const _size$4 = /*@__PURE__*/ new Vector2();
  4721. class ViewportTextureNode extends TextureNode {
  4722. static get type() {
  4723. return 'ViewportTextureNode';
  4724. }
  4725. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  4726. if ( framebufferTexture === null ) {
  4727. framebufferTexture = new FramebufferTexture();
  4728. framebufferTexture.minFilter = LinearMipmapLinearFilter;
  4729. }
  4730. super( framebufferTexture, uvNode, levelNode );
  4731. this.generateMipmaps = false;
  4732. this.isOutputTextureNode = true;
  4733. this.updateBeforeType = NodeUpdateType.FRAME;
  4734. }
  4735. updateBefore( frame ) {
  4736. const renderer = frame.renderer;
  4737. renderer.getDrawingBufferSize( _size$4 );
  4738. //
  4739. const framebufferTexture = this.value;
  4740. if ( framebufferTexture.image.width !== _size$4.width || framebufferTexture.image.height !== _size$4.height ) {
  4741. framebufferTexture.image.width = _size$4.width;
  4742. framebufferTexture.image.height = _size$4.height;
  4743. framebufferTexture.needsUpdate = true;
  4744. }
  4745. //
  4746. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  4747. framebufferTexture.generateMipmaps = this.generateMipmaps;
  4748. renderer.copyFramebufferToTexture( framebufferTexture );
  4749. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  4750. }
  4751. clone() {
  4752. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  4753. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  4754. return viewportTextureNode;
  4755. }
  4756. }
  4757. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode );
  4758. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } );
  4759. let sharedDepthbuffer = null;
  4760. class ViewportDepthTextureNode extends ViewportTextureNode {
  4761. static get type() {
  4762. return 'ViewportDepthTextureNode';
  4763. }
  4764. constructor( uvNode = screenUV, levelNode = null ) {
  4765. if ( sharedDepthbuffer === null ) {
  4766. sharedDepthbuffer = new DepthTexture();
  4767. }
  4768. super( uvNode, levelNode, sharedDepthbuffer );
  4769. }
  4770. }
  4771. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode );
  4772. class ViewportDepthNode extends Node {
  4773. static get type() {
  4774. return 'ViewportDepthNode';
  4775. }
  4776. constructor( scope, valueNode = null ) {
  4777. super( 'float' );
  4778. this.scope = scope;
  4779. this.valueNode = valueNode;
  4780. this.isViewportDepthNode = true;
  4781. }
  4782. generate( builder ) {
  4783. const { scope } = this;
  4784. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  4785. return builder.getFragDepth();
  4786. }
  4787. return super.generate( builder );
  4788. }
  4789. setup( { camera } ) {
  4790. const { scope } = this;
  4791. const value = this.valueNode;
  4792. let node = null;
  4793. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  4794. if ( value !== null ) {
  4795. node = depthBase().assign( value );
  4796. }
  4797. } else if ( scope === ViewportDepthNode.DEPTH ) {
  4798. if ( camera.isPerspectiveCamera ) {
  4799. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  4800. } else {
  4801. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  4802. }
  4803. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  4804. if ( value !== null ) {
  4805. if ( camera.isPerspectiveCamera ) {
  4806. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  4807. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  4808. } else {
  4809. node = value;
  4810. }
  4811. } else {
  4812. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  4813. }
  4814. }
  4815. return node;
  4816. }
  4817. }
  4818. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  4819. ViewportDepthNode.DEPTH = 'depth';
  4820. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  4821. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  4822. // -near maps to 0; -far maps to 1
  4823. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  4824. // maps orthographic depth in [ 0, 1 ] to viewZ
  4825. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  4826. // NOTE: https://twitter.com/gonnavis/status/1377183786949959682
  4827. // -near maps to 0; -far maps to 1
  4828. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  4829. // maps perspective depth in [ 0, 1 ] to viewZ
  4830. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  4831. // -near maps to 0; -far maps to 1
  4832. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  4833. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  4834. // The final logarithmic depth formula used here is adapted from one described in an
  4835. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  4836. // which was an improvement upon an earlier formula one described in an
  4837. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  4838. // Ulrich's formula is the following:
  4839. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  4840. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  4841. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  4842. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  4843. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  4844. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  4845. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  4846. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  4847. // be used, and ultimately Ulrich's "near plane" version was chosen.
  4848. // Outerra eventually made another improvement to their original "C-constant" variant,
  4849. // but it still does not incorporate the camera near plane (for this version,
  4850. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  4851. // Here we make 4 changes to Ulrich's formula:
  4852. // 1. Clamp the camera near plane so we don't divide by 0.
  4853. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  4854. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  4855. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  4856. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  4857. // so we do the same here, hence the 'viewZ.negate()' call.
  4858. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  4859. near = near.max( 1e-6 ).toVar();
  4860. const numerator = log2( viewZ.negate().div( near ) );
  4861. const denominator = log2( far.div( near ) );
  4862. return numerator.div( denominator );
  4863. };
  4864. // maps logarithmic depth in [ 0, 1 ] to viewZ
  4865. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  4866. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  4867. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  4868. // a negative viewZ).
  4869. const exponent = depth.mul( log( far.div( near ) ) );
  4870. return float( Math.E ).pow( exponent ).mul( near ).negate();
  4871. };
  4872. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  4873. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  4874. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH );
  4875. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  4876. depth.assign = ( value ) => depthBase( value );
  4877. class BuiltinNode extends Node {
  4878. constructor( name ) {
  4879. super( 'float' );
  4880. this.name = name;
  4881. this.isBuiltinNode = true;
  4882. }
  4883. generate( /* builder */ ) {
  4884. return this.name;
  4885. }
  4886. }
  4887. const builtin = nodeProxy( BuiltinNode );
  4888. class ClippingNode extends Node {
  4889. static get type() {
  4890. return 'ClippingNode';
  4891. }
  4892. constructor( scope = ClippingNode.DEFAULT ) {
  4893. super();
  4894. this.scope = scope;
  4895. }
  4896. setup( builder ) {
  4897. super.setup( builder );
  4898. const clippingContext = builder.clippingContext;
  4899. const { intersectionPlanes, unionPlanes } = clippingContext;
  4900. this.hardwareClipping = builder.material.hardwareClipping;
  4901. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  4902. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  4903. } else if ( this.scope === ClippingNode.HARDWARE ) {
  4904. return this.setupHardwareClipping( unionPlanes, builder );
  4905. } else {
  4906. return this.setupDefault( intersectionPlanes, unionPlanes );
  4907. }
  4908. }
  4909. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  4910. return Fn( () => {
  4911. const distanceToPlane = float().toVar( 'distanceToPlane' );
  4912. const distanceGradient = float().toVar( 'distanceToGradient' );
  4913. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  4914. const numUnionPlanes = unionPlanes.length;
  4915. if ( ! this.hardwareClipping && numUnionPlanes > 0 ) {
  4916. const clippingPlanes = uniformArray( unionPlanes );
  4917. Loop( numUnionPlanes, ( { i } ) => {
  4918. const plane = clippingPlanes.element( i );
  4919. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  4920. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  4921. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  4922. } );
  4923. }
  4924. const numIntersectionPlanes = intersectionPlanes.length;
  4925. if ( numIntersectionPlanes > 0 ) {
  4926. const clippingPlanes = uniformArray( intersectionPlanes );
  4927. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  4928. Loop( numIntersectionPlanes, ( { i } ) => {
  4929. const plane = clippingPlanes.element( i );
  4930. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  4931. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  4932. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  4933. } );
  4934. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  4935. }
  4936. diffuseColor.a.mulAssign( clipOpacity );
  4937. diffuseColor.a.equal( 0.0 ).discard();
  4938. } )();
  4939. }
  4940. setupDefault( intersectionPlanes, unionPlanes ) {
  4941. return Fn( () => {
  4942. const numUnionPlanes = unionPlanes.length;
  4943. if ( ! this.hardwareClipping && numUnionPlanes > 0 ) {
  4944. const clippingPlanes = uniformArray( unionPlanes );
  4945. Loop( numUnionPlanes, ( { i } ) => {
  4946. const plane = clippingPlanes.element( i );
  4947. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  4948. } );
  4949. }
  4950. const numIntersectionPlanes = intersectionPlanes.length;
  4951. if ( numIntersectionPlanes > 0 ) {
  4952. const clippingPlanes = uniformArray( intersectionPlanes );
  4953. const clipped = bool( true ).toVar( 'clipped' );
  4954. Loop( numIntersectionPlanes, ( { i } ) => {
  4955. const plane = clippingPlanes.element( i );
  4956. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  4957. } );
  4958. clipped.discard();
  4959. }
  4960. } )();
  4961. }
  4962. setupHardwareClipping( unionPlanes, builder ) {
  4963. const numUnionPlanes = unionPlanes.length;
  4964. builder.enableHardwareClipping( numUnionPlanes );
  4965. return Fn( () => {
  4966. const clippingPlanes = uniformArray( unionPlanes );
  4967. const hw_clip_distances = builtin( builder.getClipDistance() );
  4968. Loop( numUnionPlanes, ( { i } ) => {
  4969. const plane = clippingPlanes.element( i );
  4970. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  4971. hw_clip_distances.element( i ).assign( distance );
  4972. } );
  4973. } )();
  4974. }
  4975. }
  4976. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  4977. ClippingNode.DEFAULT = 'default';
  4978. ClippingNode.HARDWARE = 'hardware';
  4979. const clipping = () => nodeObject( new ClippingNode() );
  4980. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  4981. const hardwareClipping = () => nodeObject( new ClippingNode( ClippingNode.HARDWARE ) );
  4982. /**
  4983. * See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  4984. */
  4985. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  4986. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  4987. 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 ) ) ) ) ) );
  4988. } );
  4989. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  4990. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  4991. } );
  4992. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  4993. // Find the discretized derivatives of our coordinates
  4994. const maxDeriv = max$1(
  4995. length( dFdx( position.xyz ) ),
  4996. length( dFdy( position.xyz ) )
  4997. ).toVar( 'maxDeriv' );
  4998. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  4999. // Find two nearest log-discretized noise scales
  5000. const pixScales = vec2(
  5001. exp2( floor( log2( pixScale ) ) ),
  5002. exp2( ceil( log2( pixScale ) ) )
  5003. ).toVar( 'pixScales' );
  5004. // Compute alpha thresholds at our two noise scales
  5005. const alpha = vec2(
  5006. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  5007. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  5008. ).toVar( 'alpha' );
  5009. // Factor to interpolate lerp with
  5010. const lerpFactor = fract( log2( pixScale ) ).toVar( 'lerpFactor' );
  5011. // Interpolate alpha threshold from noise at two scales
  5012. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) ).toVar( 'x' );
  5013. // Pass into CDF to compute uniformly distrib threshold
  5014. const a = min$1( lerpFactor, lerpFactor.oneMinus() ).toVar( 'a' );
  5015. const cases = vec3(
  5016. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  5017. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  5018. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) ).toVar( 'cases' );
  5019. // Find our final, uniformly distributed alpha threshold (ατ)
  5020. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  5021. // Avoids ατ == 0. Could also do ατ =1-ατ
  5022. return clamp( threshold, 1.0e-6, 1.0 );
  5023. } );
  5024. class NodeMaterial extends Material {
  5025. static get type() {
  5026. return 'NodeMaterial';
  5027. }
  5028. get type() {
  5029. return this.constructor.type;
  5030. }
  5031. set type( _value ) { /* */ }
  5032. constructor() {
  5033. super();
  5034. this.isNodeMaterial = true;
  5035. this.forceSinglePass = false;
  5036. this.fog = true;
  5037. this.lights = false;
  5038. this.hardwareClipping = false;
  5039. this.lightsNode = null;
  5040. this.envNode = null;
  5041. this.aoNode = null;
  5042. this.colorNode = null;
  5043. this.normalNode = null;
  5044. this.opacityNode = null;
  5045. this.backdropNode = null;
  5046. this.backdropAlphaNode = null;
  5047. this.alphaTestNode = null;
  5048. this.positionNode = null;
  5049. this.geometryNode = null;
  5050. this.depthNode = null;
  5051. this.shadowPositionNode = null;
  5052. this.receivedShadowNode = null;
  5053. this.castShadowNode = null;
  5054. this.outputNode = null;
  5055. this.mrtNode = null;
  5056. this.fragmentNode = null;
  5057. this.vertexNode = null;
  5058. }
  5059. customProgramCacheKey() {
  5060. return this.type + getCacheKey$1( this );
  5061. }
  5062. build( builder ) {
  5063. this.setup( builder );
  5064. }
  5065. setupObserver( builder ) {
  5066. return new NodeMaterialObserver( builder );
  5067. }
  5068. setup( builder ) {
  5069. builder.context.setupNormal = () => this.setupNormal( builder );
  5070. const renderer = builder.renderer;
  5071. const renderTarget = renderer.getRenderTarget();
  5072. // < VERTEX STAGE >
  5073. builder.addStack();
  5074. builder.stack.outputNode = this.vertexNode || this.setupPosition( builder );
  5075. if ( this.geometryNode !== null ) {
  5076. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  5077. }
  5078. builder.addFlow( 'vertex', builder.removeStack() );
  5079. // < FRAGMENT STAGE >
  5080. builder.addStack();
  5081. let resultNode;
  5082. const clippingNode = this.setupClipping( builder );
  5083. if ( this.depthWrite === true ) {
  5084. // only write depth if depth buffer is configured
  5085. if ( renderTarget !== null ) {
  5086. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  5087. } else {
  5088. if ( renderer.depth === true ) this.setupDepth( builder );
  5089. }
  5090. }
  5091. if ( this.fragmentNode === null ) {
  5092. this.setupDiffuseColor( builder );
  5093. this.setupVariants( builder );
  5094. const outgoingLightNode = this.setupLighting( builder );
  5095. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  5096. // force unsigned floats - useful for RenderTargets
  5097. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  5098. resultNode = this.setupOutput( builder, basicOutput );
  5099. // OUTPUT NODE
  5100. output.assign( resultNode );
  5101. //
  5102. if ( this.outputNode !== null ) resultNode = this.outputNode;
  5103. // MRT
  5104. if ( renderTarget !== null ) {
  5105. const mrt = renderer.getMRT();
  5106. const materialMRT = this.mrtNode;
  5107. if ( mrt !== null ) {
  5108. resultNode = mrt;
  5109. if ( materialMRT !== null ) {
  5110. resultNode = mrt.merge( materialMRT );
  5111. }
  5112. } else if ( materialMRT !== null ) {
  5113. resultNode = materialMRT;
  5114. }
  5115. }
  5116. } else {
  5117. let fragmentNode = this.fragmentNode;
  5118. if ( fragmentNode.isOutputStructNode !== true ) {
  5119. fragmentNode = vec4( fragmentNode );
  5120. }
  5121. resultNode = this.setupOutput( builder, fragmentNode );
  5122. }
  5123. builder.stack.outputNode = resultNode;
  5124. builder.addFlow( 'fragment', builder.removeStack() );
  5125. // < MONITOR >
  5126. builder.monitor = this.setupObserver( builder );
  5127. }
  5128. setupClipping( builder ) {
  5129. if ( builder.clippingContext === null ) return null;
  5130. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  5131. let result = null;
  5132. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  5133. const samples = builder.renderer.samples;
  5134. if ( this.alphaToCoverage && samples > 1 ) {
  5135. // to be added to flow when the color/alpha value has been determined
  5136. result = clippingAlpha();
  5137. } else {
  5138. builder.stack.add( clipping() );
  5139. }
  5140. }
  5141. return result;
  5142. }
  5143. setupHardwareClipping( builder ) {
  5144. this.hardwareClipping = false;
  5145. if ( builder.clippingContext === null ) return;
  5146. const candidateCount = builder.clippingContext.unionPlanes.length;
  5147. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  5148. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  5149. builder.stack.add( hardwareClipping() );
  5150. this.hardwareClipping = true;
  5151. }
  5152. return;
  5153. }
  5154. setupDepth( builder ) {
  5155. const { renderer, camera } = builder;
  5156. // Depth
  5157. let depthNode = this.depthNode;
  5158. if ( depthNode === null ) {
  5159. const mrt = renderer.getMRT();
  5160. if ( mrt && mrt.has( 'depth' ) ) {
  5161. depthNode = mrt.get( 'depth' );
  5162. } else if ( renderer.logarithmicDepthBuffer === true ) {
  5163. if ( camera.isPerspectiveCamera ) {
  5164. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  5165. } else {
  5166. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  5167. }
  5168. }
  5169. }
  5170. if ( depthNode !== null ) {
  5171. depth.assign( depthNode ).append();
  5172. }
  5173. }
  5174. setupPosition( builder ) {
  5175. const { object } = builder;
  5176. const geometry = object.geometry;
  5177. builder.addStack();
  5178. // Vertex
  5179. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  5180. morphReference( object ).append();
  5181. }
  5182. if ( object.isSkinnedMesh === true ) {
  5183. skinningReference( object ).append();
  5184. }
  5185. if ( this.displacementMap ) {
  5186. const displacementMap = materialReference( 'displacementMap', 'texture' );
  5187. const displacementScale = materialReference( 'displacementScale', 'float' );
  5188. const displacementBias = materialReference( 'displacementBias', 'float' );
  5189. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  5190. }
  5191. if ( object.isBatchedMesh ) {
  5192. batch( object ).append();
  5193. }
  5194. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  5195. instancedMesh( object ).append();
  5196. }
  5197. if ( this.positionNode !== null ) {
  5198. positionLocal.assign( this.positionNode );
  5199. }
  5200. this.setupHardwareClipping( builder );
  5201. const mvp = modelViewProjection();
  5202. builder.context.vertex = builder.removeStack();
  5203. builder.context.mvp = mvp;
  5204. return mvp;
  5205. }
  5206. setupDiffuseColor( { object, geometry } ) {
  5207. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  5208. // VERTEX COLORS
  5209. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  5210. colorNode = vec4( colorNode.xyz.mul( attribute( 'color', 'vec3' ) ), colorNode.a );
  5211. }
  5212. // Instanced colors
  5213. if ( object.instanceColor ) {
  5214. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  5215. colorNode = instanceColor.mul( colorNode );
  5216. }
  5217. if ( object.isBatchedMesh && object._colorsTexture ) {
  5218. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  5219. colorNode = batchColor.mul( colorNode );
  5220. }
  5221. // COLOR
  5222. diffuseColor.assign( colorNode );
  5223. // OPACITY
  5224. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  5225. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  5226. // ALPHA TEST
  5227. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  5228. const alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  5229. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  5230. }
  5231. // ALPHA HASH
  5232. if ( this.alphaHash === true ) {
  5233. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  5234. }
  5235. if ( this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false ) {
  5236. diffuseColor.a.assign( 1.0 );
  5237. }
  5238. }
  5239. setupVariants( /*builder*/ ) {
  5240. // Interface function.
  5241. }
  5242. setupOutgoingLight() {
  5243. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  5244. }
  5245. setupNormal() {
  5246. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  5247. }
  5248. setupEnvironment( /*builder*/ ) {
  5249. let node = null;
  5250. if ( this.envNode ) {
  5251. node = this.envNode;
  5252. } else if ( this.envMap ) {
  5253. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  5254. }
  5255. return node;
  5256. }
  5257. setupLightMap( builder ) {
  5258. let node = null;
  5259. if ( builder.material.lightMap ) {
  5260. node = new IrradianceNode( materialLightMap );
  5261. }
  5262. return node;
  5263. }
  5264. setupLights( builder ) {
  5265. const materialLightsNode = [];
  5266. //
  5267. const envNode = this.setupEnvironment( builder );
  5268. if ( envNode && envNode.isLightingNode ) {
  5269. materialLightsNode.push( envNode );
  5270. }
  5271. const lightMapNode = this.setupLightMap( builder );
  5272. if ( lightMapNode && lightMapNode.isLightingNode ) {
  5273. materialLightsNode.push( lightMapNode );
  5274. }
  5275. if ( this.aoNode !== null || builder.material.aoMap ) {
  5276. const aoNode = this.aoNode !== null ? this.aoNode : materialAOMap;
  5277. materialLightsNode.push( new AONode( aoNode ) );
  5278. }
  5279. let lightsN = this.lightsNode || builder.lightsNode;
  5280. if ( materialLightsNode.length > 0 ) {
  5281. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  5282. }
  5283. return lightsN;
  5284. }
  5285. setupLightingModel( /*builder*/ ) {
  5286. // Interface function.
  5287. }
  5288. setupLighting( builder ) {
  5289. const { material } = builder;
  5290. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  5291. // OUTGOING LIGHT
  5292. const lights = this.lights === true || this.lightsNode !== null;
  5293. const lightsNode = lights ? this.setupLights( builder ) : null;
  5294. let outgoingLightNode = this.setupOutgoingLight( builder );
  5295. if ( lightsNode && lightsNode.getScope().hasLights ) {
  5296. const lightingModel = this.setupLightingModel( builder );
  5297. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  5298. } else if ( backdropNode !== null ) {
  5299. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  5300. }
  5301. // EMISSIVE
  5302. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  5303. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  5304. outgoingLightNode = outgoingLightNode.add( emissive );
  5305. }
  5306. return outgoingLightNode;
  5307. }
  5308. setupOutput( builder, outputNode ) {
  5309. // FOG
  5310. if ( this.fog === true ) {
  5311. const fogNode = builder.fogNode;
  5312. if ( fogNode ) outputNode = vec4( fogNode.mix( outputNode.rgb, fogNode.colorNode ), outputNode.a );
  5313. }
  5314. return outputNode;
  5315. }
  5316. setDefaultValues( material ) {
  5317. // This approach is to reuse the native refreshUniforms*
  5318. // and turn available the use of features like transmission and environment in core
  5319. for ( const property in material ) {
  5320. const value = material[ property ];
  5321. if ( this[ property ] === undefined ) {
  5322. this[ property ] = value;
  5323. if ( value && value.clone ) this[ property ] = value.clone();
  5324. }
  5325. }
  5326. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  5327. for ( const key in descriptors ) {
  5328. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  5329. descriptors[ key ].get !== undefined ) {
  5330. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  5331. }
  5332. }
  5333. }
  5334. toJSON( meta ) {
  5335. const isRoot = ( meta === undefined || typeof meta === 'string' );
  5336. if ( isRoot ) {
  5337. meta = {
  5338. textures: {},
  5339. images: {},
  5340. nodes: {}
  5341. };
  5342. }
  5343. const data = Material.prototype.toJSON.call( this, meta );
  5344. const nodeChildren = getNodeChildren( this );
  5345. data.inputNodes = {};
  5346. for ( const { property, childNode } of nodeChildren ) {
  5347. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  5348. }
  5349. // TODO: Copied from Object3D.toJSON
  5350. function extractFromCache( cache ) {
  5351. const values = [];
  5352. for ( const key in cache ) {
  5353. const data = cache[ key ];
  5354. delete data.metadata;
  5355. values.push( data );
  5356. }
  5357. return values;
  5358. }
  5359. if ( isRoot ) {
  5360. const textures = extractFromCache( meta.textures );
  5361. const images = extractFromCache( meta.images );
  5362. const nodes = extractFromCache( meta.nodes );
  5363. if ( textures.length > 0 ) data.textures = textures;
  5364. if ( images.length > 0 ) data.images = images;
  5365. if ( nodes.length > 0 ) data.nodes = nodes;
  5366. }
  5367. return data;
  5368. }
  5369. copy( source ) {
  5370. this.lightsNode = source.lightsNode;
  5371. this.envNode = source.envNode;
  5372. this.colorNode = source.colorNode;
  5373. this.normalNode = source.normalNode;
  5374. this.opacityNode = source.opacityNode;
  5375. this.backdropNode = source.backdropNode;
  5376. this.backdropAlphaNode = source.backdropAlphaNode;
  5377. this.alphaTestNode = source.alphaTestNode;
  5378. this.positionNode = source.positionNode;
  5379. this.geometryNode = source.geometryNode;
  5380. this.depthNode = source.depthNode;
  5381. this.shadowPositionNode = source.shadowPositionNode;
  5382. this.receivedShadowNode = source.receivedShadowNode;
  5383. this.castShadowNode = source.castShadowNode;
  5384. this.outputNode = source.outputNode;
  5385. this.mrtNode = source.mrtNode;
  5386. this.fragmentNode = source.fragmentNode;
  5387. this.vertexNode = source.vertexNode;
  5388. return super.copy( source );
  5389. }
  5390. }
  5391. const _defaultValues$e = /*@__PURE__*/ new PointsMaterial();
  5392. class InstancedPointsNodeMaterial extends NodeMaterial {
  5393. static get type() {
  5394. return 'InstancedPointsNodeMaterial';
  5395. }
  5396. constructor( params = {} ) {
  5397. super();
  5398. this.lights = false;
  5399. this.useAlphaToCoverage = true;
  5400. this.useColor = params.vertexColors;
  5401. this.pointWidth = 1;
  5402. this.pointColorNode = null;
  5403. this.pointWidthNode = null;
  5404. this.setDefaultValues( _defaultValues$e );
  5405. this.setValues( params );
  5406. }
  5407. setup( builder ) {
  5408. this.setupShaders( builder );
  5409. super.setup( builder );
  5410. }
  5411. setupShaders( { renderer } ) {
  5412. const useAlphaToCoverage = this.alphaToCoverage;
  5413. const useColor = this.useColor;
  5414. this.vertexNode = Fn( () => {
  5415. const instancePosition = attribute( 'instancePosition' ).xyz;
  5416. // camera space
  5417. const mvPos = vec4( modelViewMatrix.mul( vec4( instancePosition, 1.0 ) ) );
  5418. const aspect = viewport.z.div( viewport.w );
  5419. // clip space
  5420. const clipPos = cameraProjectionMatrix.mul( mvPos );
  5421. // offset in ndc space
  5422. const offset = positionGeometry.xy.toVar();
  5423. offset.mulAssign( this.pointWidthNode ? this.pointWidthNode : materialPointWidth );
  5424. offset.assign( offset.div( viewport.z ) );
  5425. offset.y.assign( offset.y.mul( aspect ) );
  5426. // back to clip space
  5427. offset.assign( offset.mul( clipPos.w ) );
  5428. //clipPos.xy += offset;
  5429. clipPos.addAssign( vec4( offset, 0, 0 ) );
  5430. return clipPos;
  5431. } )();
  5432. this.fragmentNode = Fn( () => {
  5433. const alpha = float( 1 ).toVar();
  5434. const len2 = lengthSq( uv().mul( 2 ).sub( 1 ) );
  5435. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  5436. const dlen = float( len2.fwidth() ).toVar();
  5437. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  5438. } else {
  5439. len2.greaterThan( 1.0 ).discard();
  5440. }
  5441. let pointColorNode;
  5442. if ( this.pointColorNode ) {
  5443. pointColorNode = this.pointColorNode;
  5444. } else {
  5445. if ( useColor ) {
  5446. const instanceColor = attribute( 'instanceColor' );
  5447. pointColorNode = instanceColor.mul( materialColor );
  5448. } else {
  5449. pointColorNode = materialColor;
  5450. }
  5451. }
  5452. alpha.mulAssign( materialOpacity );
  5453. return vec4( pointColorNode, alpha );
  5454. } )();
  5455. }
  5456. get alphaToCoverage() {
  5457. return this.useAlphaToCoverage;
  5458. }
  5459. set alphaToCoverage( value ) {
  5460. if ( this.useAlphaToCoverage !== value ) {
  5461. this.useAlphaToCoverage = value;
  5462. this.needsUpdate = true;
  5463. }
  5464. }
  5465. }
  5466. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  5467. class LineBasicNodeMaterial extends NodeMaterial {
  5468. static get type() {
  5469. return 'LineBasicNodeMaterial';
  5470. }
  5471. constructor( parameters ) {
  5472. super();
  5473. this.isLineBasicNodeMaterial = true;
  5474. this.lights = false;
  5475. this.setDefaultValues( _defaultValues$d );
  5476. this.setValues( parameters );
  5477. }
  5478. }
  5479. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  5480. class LineDashedNodeMaterial extends NodeMaterial {
  5481. static get type() {
  5482. return 'LineDashedNodeMaterial';
  5483. }
  5484. constructor( parameters ) {
  5485. super();
  5486. this.isLineDashedNodeMaterial = true;
  5487. this.lights = false;
  5488. this.setDefaultValues( _defaultValues$c );
  5489. this.dashOffset = 0;
  5490. this.offsetNode = null;
  5491. this.dashScaleNode = null;
  5492. this.dashSizeNode = null;
  5493. this.gapSizeNode = null;
  5494. this.setValues( parameters );
  5495. }
  5496. setupVariants() {
  5497. const offsetNode = this.offsetNode ? float( this.offsetNodeNode ) : materialLineDashOffset;
  5498. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  5499. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  5500. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  5501. dashSize.assign( dashSizeNode );
  5502. gapSize.assign( gapSizeNode );
  5503. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  5504. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  5505. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  5506. }
  5507. }
  5508. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  5509. class Line2NodeMaterial extends NodeMaterial {
  5510. static get type() {
  5511. return 'Line2NodeMaterial';
  5512. }
  5513. constructor( params = {} ) {
  5514. super();
  5515. this.lights = false;
  5516. this.setDefaultValues( _defaultValues$b );
  5517. this.useAlphaToCoverage = true;
  5518. this.useColor = params.vertexColors;
  5519. this.useDash = params.dashed;
  5520. this.useWorldUnits = false;
  5521. this.dashOffset = 0;
  5522. this.lineWidth = 1;
  5523. this.lineColorNode = null;
  5524. this.offsetNode = null;
  5525. this.dashScaleNode = null;
  5526. this.dashSizeNode = null;
  5527. this.gapSizeNode = null;
  5528. this.setValues( params );
  5529. }
  5530. setup( builder ) {
  5531. this.setupShaders( builder );
  5532. super.setup( builder );
  5533. }
  5534. setupShaders( { renderer } ) {
  5535. const useAlphaToCoverage = this.alphaToCoverage;
  5536. const useColor = this.useColor;
  5537. const useDash = this.dashed;
  5538. const useWorldUnits = this.worldUnits;
  5539. const trimSegment = Fn( ( { start, end } ) => {
  5540. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  5541. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  5542. const nearEstimate = b.mul( - 0.5 ).div( a );
  5543. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  5544. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  5545. } ).setLayout( {
  5546. name: 'trimSegment',
  5547. type: 'vec4',
  5548. inputs: [
  5549. { name: 'start', type: 'vec4' },
  5550. { name: 'end', type: 'vec4' }
  5551. ]
  5552. } );
  5553. this.vertexNode = Fn( () => {
  5554. const instanceStart = attribute( 'instanceStart' );
  5555. const instanceEnd = attribute( 'instanceEnd' );
  5556. // camera space
  5557. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  5558. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  5559. if ( useDash ) {
  5560. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  5561. const offsetNode = this.offsetNode ? float( this.offsetNodeNode ) : materialLineDashOffset;
  5562. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  5563. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  5564. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  5565. lineDistance = lineDistance.add( offsetNode );
  5566. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  5567. }
  5568. if ( useWorldUnits ) {
  5569. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  5570. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  5571. }
  5572. const aspect = viewport.z.div( viewport.w );
  5573. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  5574. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  5575. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  5576. // perhaps there is a more elegant solution -- WestLangley
  5577. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( - 1.0 ); // 4th entry in the 3rd column
  5578. If( perspective, () => {
  5579. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  5580. end.assign( trimSegment( { start: start, end: end } ) );
  5581. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  5582. start.assign( trimSegment( { start: end, end: start } ) );
  5583. } );
  5584. } );
  5585. // clip space
  5586. const clipStart = cameraProjectionMatrix.mul( start );
  5587. const clipEnd = cameraProjectionMatrix.mul( end );
  5588. // ndc space
  5589. const ndcStart = clipStart.xyz.div( clipStart.w );
  5590. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  5591. // direction
  5592. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  5593. // account for clip-space aspect ratio
  5594. dir.x.assign( dir.x.mul( aspect ) );
  5595. dir.assign( dir.normalize() );
  5596. const clip = vec4().toVar();
  5597. if ( useWorldUnits ) {
  5598. // get the offset direction as perpendicular to the view vector
  5599. const worldDir = end.xyz.sub( start.xyz ).normalize();
  5600. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  5601. const worldUp = worldDir.cross( tmpFwd ).normalize();
  5602. const worldFwd = worldDir.cross( worldUp );
  5603. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  5604. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  5605. // height offset
  5606. const hw = materialLineWidth.mul( 0.5 );
  5607. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  5608. // don't extend the line if we're rendering dashes because we
  5609. // won't be rendering the endcaps
  5610. if ( ! useDash ) {
  5611. // cap extension
  5612. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  5613. // add width to the box
  5614. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  5615. // endcaps
  5616. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  5617. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  5618. } );
  5619. }
  5620. // project the worldpos
  5621. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  5622. // shift the depth of the projected points so the line
  5623. // segments overlap neatly
  5624. const clipPose = vec3().toVar();
  5625. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  5626. clip.z.assign( clipPose.z.mul( clip.w ) );
  5627. } else {
  5628. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  5629. // undo aspect ratio adjustment
  5630. dir.x.assign( dir.x.div( aspect ) );
  5631. offset.x.assign( offset.x.div( aspect ) );
  5632. // sign flip
  5633. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  5634. // endcaps
  5635. If( positionGeometry.y.lessThan( 0.0 ), () => {
  5636. offset.assign( offset.sub( dir ) );
  5637. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  5638. offset.assign( offset.add( dir ) );
  5639. } );
  5640. // adjust for linewidth
  5641. offset.assign( offset.mul( materialLineWidth ) );
  5642. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  5643. offset.assign( offset.div( viewport.w ) );
  5644. // select end
  5645. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  5646. // back to clip space
  5647. offset.assign( offset.mul( clip.w ) );
  5648. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  5649. }
  5650. return clip;
  5651. } )();
  5652. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  5653. const p13 = p1.sub( p3 );
  5654. const p43 = p4.sub( p3 );
  5655. const p21 = p2.sub( p1 );
  5656. const d1343 = p13.dot( p43 );
  5657. const d4321 = p43.dot( p21 );
  5658. const d1321 = p13.dot( p21 );
  5659. const d4343 = p43.dot( p43 );
  5660. const d2121 = p21.dot( p21 );
  5661. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  5662. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  5663. const mua = numer.div( denom ).clamp();
  5664. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  5665. return vec2( mua, mub );
  5666. } );
  5667. this.fragmentNode = Fn( () => {
  5668. const vUv = uv();
  5669. if ( useDash ) {
  5670. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  5671. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  5672. dashSize.assign( dashSizeNode );
  5673. gapSize.assign( gapSizeNode );
  5674. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  5675. vUv.y.lessThan( - 1.0 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  5676. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  5677. }
  5678. const alpha = float( 1 ).toVar( 'alpha' );
  5679. if ( useWorldUnits ) {
  5680. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  5681. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  5682. // Find the closest points on the view ray and the line segment
  5683. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  5684. const lineDir = worldEnd.sub( worldStart );
  5685. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  5686. const p1 = worldStart.add( lineDir.mul( params.x ) );
  5687. const p2 = rayEnd.mul( params.y );
  5688. const delta = p1.sub( p2 );
  5689. const len = delta.length();
  5690. const norm = len.div( materialLineWidth );
  5691. if ( ! useDash ) {
  5692. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  5693. const dnorm = norm.fwidth();
  5694. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  5695. } else {
  5696. norm.greaterThan( 0.5 ).discard();
  5697. }
  5698. }
  5699. } else {
  5700. // round endcaps
  5701. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  5702. const a = vUv.x;
  5703. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  5704. const len2 = a.mul( a ).add( b.mul( b ) );
  5705. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  5706. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  5707. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  5708. } );
  5709. } else {
  5710. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  5711. const a = vUv.x;
  5712. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  5713. const len2 = a.mul( a ).add( b.mul( b ) );
  5714. len2.greaterThan( 1.0 ).discard();
  5715. } );
  5716. }
  5717. }
  5718. let lineColorNode;
  5719. if ( this.lineColorNode ) {
  5720. lineColorNode = this.lineColorNode;
  5721. } else {
  5722. if ( useColor ) {
  5723. const instanceColorStart = attribute( 'instanceColorStart' );
  5724. const instanceColorEnd = attribute( 'instanceColorEnd' );
  5725. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  5726. lineColorNode = instanceColor.mul( materialColor );
  5727. } else {
  5728. lineColorNode = materialColor;
  5729. }
  5730. }
  5731. return vec4( lineColorNode, alpha );
  5732. } )();
  5733. }
  5734. get worldUnits() {
  5735. return this.useWorldUnits;
  5736. }
  5737. set worldUnits( value ) {
  5738. if ( this.useWorldUnits !== value ) {
  5739. this.useWorldUnits = value;
  5740. this.needsUpdate = true;
  5741. }
  5742. }
  5743. get dashed() {
  5744. return this.useDash;
  5745. }
  5746. set dashed( value ) {
  5747. if ( this.useDash !== value ) {
  5748. this.useDash = value;
  5749. this.needsUpdate = true;
  5750. }
  5751. }
  5752. get alphaToCoverage() {
  5753. return this.useAlphaToCoverage;
  5754. }
  5755. set alphaToCoverage( value ) {
  5756. if ( this.useAlphaToCoverage !== value ) {
  5757. this.useAlphaToCoverage = value;
  5758. this.needsUpdate = true;
  5759. }
  5760. }
  5761. }
  5762. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  5763. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  5764. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  5765. class MeshNormalNodeMaterial extends NodeMaterial {
  5766. static get type() {
  5767. return 'MeshNormalNodeMaterial';
  5768. }
  5769. constructor( parameters ) {
  5770. super();
  5771. this.lights = false;
  5772. this.isMeshNormalNodeMaterial = true;
  5773. this.setDefaultValues( _defaultValues$a );
  5774. this.setValues( parameters );
  5775. }
  5776. setupDiffuseColor() {
  5777. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  5778. diffuseColor.assign( vec4( directionToColor( transformedNormalView ), opacityNode ) );
  5779. }
  5780. }
  5781. class EquirectUVNode extends TempNode {
  5782. static get type() {
  5783. return 'EquirectUVNode';
  5784. }
  5785. constructor( dirNode = positionWorldDirection ) {
  5786. super( 'vec2' );
  5787. this.dirNode = dirNode;
  5788. }
  5789. setup() {
  5790. const dir = this.dirNode;
  5791. const u = dir.z.atan2( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  5792. const v = dir.y.clamp( - 1.0, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  5793. return vec2( u, v );
  5794. }
  5795. }
  5796. const equirectUV = /*@__PURE__*/ nodeProxy( EquirectUVNode );
  5797. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  5798. class CubeRenderTarget extends WebGLCubeRenderTarget {
  5799. constructor( size = 1, options = {} ) {
  5800. super( size, options );
  5801. this.isCubeRenderTarget = true;
  5802. }
  5803. fromEquirectangularTexture( renderer, texture$1 ) {
  5804. const currentMinFilter = texture$1.minFilter;
  5805. const currentGenerateMipmaps = texture$1.generateMipmaps;
  5806. texture$1.generateMipmaps = true;
  5807. this.texture.type = texture$1.type;
  5808. this.texture.colorSpace = texture$1.colorSpace;
  5809. this.texture.generateMipmaps = texture$1.generateMipmaps;
  5810. this.texture.minFilter = texture$1.minFilter;
  5811. this.texture.magFilter = texture$1.magFilter;
  5812. const geometry = new BoxGeometry( 5, 5, 5 );
  5813. const uvNode = equirectUV( positionWorldDirection );
  5814. const material = new NodeMaterial();
  5815. material.colorNode = texture( texture$1, uvNode, 0 );
  5816. material.side = BackSide;
  5817. material.blending = NoBlending;
  5818. const mesh = new Mesh( geometry, material );
  5819. const scene = new Scene();
  5820. scene.add( mesh );
  5821. // Avoid blurred poles
  5822. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  5823. const camera = new CubeCamera( 1, 10, this );
  5824. const currentMRT = renderer.getMRT();
  5825. renderer.setMRT( null );
  5826. camera.update( renderer, scene );
  5827. renderer.setMRT( currentMRT );
  5828. texture$1.minFilter = currentMinFilter;
  5829. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  5830. mesh.geometry.dispose();
  5831. mesh.material.dispose();
  5832. return this;
  5833. }
  5834. }
  5835. const _cache$1 = new WeakMap();
  5836. class CubeMapNode extends TempNode {
  5837. static get type() {
  5838. return 'CubeMapNode';
  5839. }
  5840. constructor( envNode ) {
  5841. super( 'vec3' );
  5842. this.envNode = envNode;
  5843. this._cubeTexture = null;
  5844. this._cubeTextureNode = cubeTexture();
  5845. const defaultTexture = new CubeTexture();
  5846. defaultTexture.isRenderTargetTexture = true;
  5847. this._defaultTexture = defaultTexture;
  5848. this.updateBeforeType = NodeUpdateType.RENDER;
  5849. }
  5850. updateBefore( frame ) {
  5851. const { renderer, material } = frame;
  5852. const envNode = this.envNode;
  5853. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  5854. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  5855. if ( texture && texture.isTexture ) {
  5856. const mapping = texture.mapping;
  5857. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  5858. // check for converted cubemap map
  5859. if ( _cache$1.has( texture ) ) {
  5860. const cubeMap = _cache$1.get( texture );
  5861. mapTextureMapping( cubeMap, texture.mapping );
  5862. this._cubeTexture = cubeMap;
  5863. } else {
  5864. // create cube map from equirectangular map
  5865. const image = texture.image;
  5866. if ( isEquirectangularMapReady$1( image ) ) {
  5867. const renderTarget = new CubeRenderTarget( image.height );
  5868. renderTarget.fromEquirectangularTexture( renderer, texture );
  5869. mapTextureMapping( renderTarget.texture, texture.mapping );
  5870. this._cubeTexture = renderTarget.texture;
  5871. _cache$1.set( texture, renderTarget.texture );
  5872. texture.addEventListener( 'dispose', onTextureDispose );
  5873. } else {
  5874. // default cube texture as fallback when equirectangular texture is not yet loaded
  5875. this._cubeTexture = this._defaultTexture;
  5876. }
  5877. }
  5878. //
  5879. this._cubeTextureNode.value = this._cubeTexture;
  5880. } else {
  5881. // envNode already refers to a cube map
  5882. this._cubeTextureNode = this.envNode;
  5883. }
  5884. }
  5885. }
  5886. }
  5887. setup( builder ) {
  5888. this.updateBefore( builder );
  5889. return this._cubeTextureNode;
  5890. }
  5891. }
  5892. function isEquirectangularMapReady$1( image ) {
  5893. if ( image === null || image === undefined ) return false;
  5894. return image.height > 0;
  5895. }
  5896. function onTextureDispose( event ) {
  5897. const texture = event.target;
  5898. texture.removeEventListener( 'dispose', onTextureDispose );
  5899. const renderTarget = _cache$1.get( texture );
  5900. if ( renderTarget !== undefined ) {
  5901. _cache$1.delete( texture );
  5902. renderTarget.dispose();
  5903. }
  5904. }
  5905. function mapTextureMapping( texture, mapping ) {
  5906. if ( mapping === EquirectangularReflectionMapping ) {
  5907. texture.mapping = CubeReflectionMapping;
  5908. } else if ( mapping === EquirectangularRefractionMapping ) {
  5909. texture.mapping = CubeRefractionMapping;
  5910. }
  5911. }
  5912. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode );
  5913. class BasicEnvironmentNode extends LightingNode {
  5914. static get type() {
  5915. return 'BasicEnvironmentNode';
  5916. }
  5917. constructor( envNode = null ) {
  5918. super();
  5919. this.envNode = envNode;
  5920. }
  5921. setup( builder ) {
  5922. // environment property is used in the finish() method of BasicLightingModel
  5923. builder.context.environment = cubeMapNode( this.envNode );
  5924. }
  5925. }
  5926. class BasicLightMapNode extends LightingNode {
  5927. static get type() {
  5928. return 'BasicLightMapNode';
  5929. }
  5930. constructor( lightMapNode = null ) {
  5931. super();
  5932. this.lightMapNode = lightMapNode;
  5933. }
  5934. setup( builder ) {
  5935. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  5936. const RECIPROCAL_PI = float( 1 / Math.PI );
  5937. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  5938. }
  5939. }
  5940. class LightingModel {
  5941. start( /*input, stack, builder*/ ) { }
  5942. finish( /*input, stack, builder*/ ) { }
  5943. direct( /*input, stack, builder*/ ) { }
  5944. directRectArea( /*input, stack, builder*/ ) {}
  5945. indirect( /*input, stack, builder*/ ) { }
  5946. ambientOcclusion( /*input, stack, builder*/ ) { }
  5947. }
  5948. class BasicLightingModel extends LightingModel {
  5949. constructor() {
  5950. super();
  5951. }
  5952. indirect( context, stack, builder ) {
  5953. const ambientOcclusion = context.ambientOcclusion;
  5954. const reflectedLight = context.reflectedLight;
  5955. const irradianceLightMap = builder.context.irradianceLightMap;
  5956. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  5957. // accumulation (baked indirect lighting only)
  5958. if ( irradianceLightMap ) {
  5959. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  5960. } else {
  5961. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  5962. }
  5963. // modulation
  5964. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  5965. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  5966. }
  5967. finish( context, stack, builder ) {
  5968. const material = builder.material;
  5969. const outgoingLight = context.outgoingLight;
  5970. const envNode = builder.context.environment;
  5971. if ( envNode ) {
  5972. switch ( material.combine ) {
  5973. case MultiplyOperation:
  5974. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  5975. break;
  5976. case MixOperation:
  5977. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  5978. break;
  5979. case AddOperation:
  5980. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  5981. break;
  5982. default:
  5983. console.warn( 'THREE.BasicLightingModel: Unsupported .combine value:', material.combine );
  5984. break;
  5985. }
  5986. }
  5987. }
  5988. }
  5989. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  5990. class MeshBasicNodeMaterial extends NodeMaterial {
  5991. static get type() {
  5992. return 'MeshBasicNodeMaterial';
  5993. }
  5994. constructor( parameters ) {
  5995. super();
  5996. this.isMeshBasicNodeMaterial = true;
  5997. this.lights = true;
  5998. this.setDefaultValues( _defaultValues$9 );
  5999. this.setValues( parameters );
  6000. }
  6001. setupNormal() {
  6002. return normalView; // see #28839
  6003. }
  6004. setupEnvironment( builder ) {
  6005. const envNode = super.setupEnvironment( builder );
  6006. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  6007. }
  6008. setupLightMap( builder ) {
  6009. let node = null;
  6010. if ( builder.material.lightMap ) {
  6011. node = new BasicLightMapNode( materialLightMap );
  6012. }
  6013. return node;
  6014. }
  6015. setupOutgoingLight() {
  6016. return diffuseColor.rgb;
  6017. }
  6018. setupLightingModel() {
  6019. return new BasicLightingModel();
  6020. }
  6021. }
  6022. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  6023. // Original approximation by Christophe Schlick '94
  6024. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  6025. // Optimized variant (presented by Epic at SIGGRAPH '13)
  6026. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  6027. const fresnel = dotVH.mul( - 5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  6028. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  6029. } ); // validated
  6030. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  6031. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  6032. } ); // validated
  6033. const G_BlinnPhong_Implicit = () => float( 0.25 );
  6034. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  6035. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  6036. } );
  6037. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  6038. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  6039. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  6040. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  6041. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  6042. const G = G_BlinnPhong_Implicit();
  6043. const D = D_BlinnPhong( { dotNH } );
  6044. return F.mul( G ).mul( D );
  6045. } );
  6046. class PhongLightingModel extends BasicLightingModel {
  6047. constructor( specular = true ) {
  6048. super();
  6049. this.specular = specular;
  6050. }
  6051. direct( { lightDirection, lightColor, reflectedLight } ) {
  6052. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  6053. const irradiance = dotNL.mul( lightColor );
  6054. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  6055. if ( this.specular === true ) {
  6056. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  6057. }
  6058. }
  6059. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  6060. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  6061. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  6062. }
  6063. }
  6064. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  6065. class MeshLambertNodeMaterial extends NodeMaterial {
  6066. static get type() {
  6067. return 'MeshLambertNodeMaterial';
  6068. }
  6069. constructor( parameters ) {
  6070. super();
  6071. this.isMeshLambertNodeMaterial = true;
  6072. this.lights = true;
  6073. this.setDefaultValues( _defaultValues$8 );
  6074. this.setValues( parameters );
  6075. }
  6076. setupEnvironment( builder ) {
  6077. const envNode = super.setupEnvironment( builder );
  6078. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  6079. }
  6080. setupLightingModel( /*builder*/ ) {
  6081. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  6082. }
  6083. }
  6084. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  6085. class MeshPhongNodeMaterial extends NodeMaterial {
  6086. static get type() {
  6087. return 'MeshPhongNodeMaterial';
  6088. }
  6089. constructor( parameters ) {
  6090. super();
  6091. this.isMeshPhongNodeMaterial = true;
  6092. this.lights = true;
  6093. this.shininessNode = null;
  6094. this.specularNode = null;
  6095. this.setDefaultValues( _defaultValues$7 );
  6096. this.setValues( parameters );
  6097. }
  6098. setupEnvironment( builder ) {
  6099. const envNode = super.setupEnvironment( builder );
  6100. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  6101. }
  6102. setupLightingModel( /*builder*/ ) {
  6103. return new PhongLightingModel();
  6104. }
  6105. setupVariants() {
  6106. // SHININESS
  6107. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  6108. shininess.assign( shininessNode );
  6109. // SPECULAR COLOR
  6110. const specularNode = this.specularNode || materialSpecular;
  6111. specularColor.assign( specularNode );
  6112. }
  6113. copy( source ) {
  6114. this.shininessNode = source.shininessNode;
  6115. this.specularNode = source.specularNode;
  6116. return super.copy( source );
  6117. }
  6118. }
  6119. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  6120. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  6121. return float( 0 );
  6122. }
  6123. const dxy = normalView.dFdx().abs().max( normalView.dFdy().abs() );
  6124. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  6125. return geometryRoughness;
  6126. } );
  6127. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  6128. const { roughness } = inputs;
  6129. const geometryRoughness = getGeometryRoughness();
  6130. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  6131. roughnessFactor = roughnessFactor.add( geometryRoughness );
  6132. roughnessFactor = roughnessFactor.min( 1.0 );
  6133. return roughnessFactor;
  6134. } );
  6135. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  6136. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  6137. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  6138. const a2 = alpha.pow2();
  6139. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  6140. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  6141. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  6142. } ).setLayout( {
  6143. name: 'V_GGX_SmithCorrelated',
  6144. type: 'float',
  6145. inputs: [
  6146. { name: 'alpha', type: 'float' },
  6147. { name: 'dotNL', type: 'float' },
  6148. { name: 'dotNV', type: 'float' }
  6149. ]
  6150. } ); // validated
  6151. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  6152. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  6153. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  6154. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  6155. const v = div( 0.5, gv.add( gl ) );
  6156. return v.saturate();
  6157. } ).setLayout( {
  6158. name: 'V_GGX_SmithCorrelated_Anisotropic',
  6159. type: 'float',
  6160. inputs: [
  6161. { name: 'alphaT', type: 'float', qualifier: 'in' },
  6162. { name: 'alphaB', type: 'float', qualifier: 'in' },
  6163. { name: 'dotTV', type: 'float', qualifier: 'in' },
  6164. { name: 'dotBV', type: 'float', qualifier: 'in' },
  6165. { name: 'dotTL', type: 'float', qualifier: 'in' },
  6166. { name: 'dotBL', type: 'float', qualifier: 'in' },
  6167. { name: 'dotNV', type: 'float', qualifier: 'in' },
  6168. { name: 'dotNL', type: 'float', qualifier: 'in' }
  6169. ]
  6170. } );
  6171. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  6172. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  6173. // alpha is "roughness squared" in Disney’s reparameterization
  6174. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  6175. const a2 = alpha.pow2();
  6176. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  6177. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  6178. } ).setLayout( {
  6179. name: 'D_GGX',
  6180. type: 'float',
  6181. inputs: [
  6182. { name: 'alpha', type: 'float' },
  6183. { name: 'dotNH', type: 'float' }
  6184. ]
  6185. } ); // validated
  6186. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  6187. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  6188. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  6189. const a2 = alphaT.mul( alphaB );
  6190. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  6191. const v2 = v.dot( v );
  6192. const w2 = a2.div( v2 );
  6193. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  6194. } ).setLayout( {
  6195. name: 'D_GGX_Anisotropic',
  6196. type: 'float',
  6197. inputs: [
  6198. { name: 'alphaT', type: 'float', qualifier: 'in' },
  6199. { name: 'alphaB', type: 'float', qualifier: 'in' },
  6200. { name: 'dotNH', type: 'float', qualifier: 'in' },
  6201. { name: 'dotTH', type: 'float', qualifier: 'in' },
  6202. { name: 'dotBH', type: 'float', qualifier: 'in' }
  6203. ]
  6204. } );
  6205. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  6206. const BRDF_GGX = /*@__PURE__*/ Fn( ( inputs ) => {
  6207. const { lightDirection, f0, f90, roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } = inputs;
  6208. const normalView = inputs.normalView || transformedNormalView;
  6209. const alpha = roughness.pow2(); // UE4's roughness
  6210. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  6211. const dotNL = normalView.dot( lightDirection ).clamp();
  6212. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  6213. const dotNH = normalView.dot( halfDir ).clamp();
  6214. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  6215. let F = F_Schlick( { f0, f90, dotVH } );
  6216. let V, D;
  6217. if ( defined( USE_IRIDESCENCE ) ) {
  6218. F = iridescence.mix( F, f );
  6219. }
  6220. if ( defined( USE_ANISOTROPY ) ) {
  6221. const dotTL = anisotropyT.dot( lightDirection );
  6222. const dotTV = anisotropyT.dot( positionViewDirection );
  6223. const dotTH = anisotropyT.dot( halfDir );
  6224. const dotBL = anisotropyB.dot( lightDirection );
  6225. const dotBV = anisotropyB.dot( positionViewDirection );
  6226. const dotBH = anisotropyB.dot( halfDir );
  6227. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  6228. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  6229. } else {
  6230. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  6231. D = D_GGX( { alpha, dotNH } );
  6232. }
  6233. return F.mul( V ).mul( D );
  6234. } ); // validated
  6235. // Analytical approximation of the DFG LUT, one half of the
  6236. // split-sum approximation used in indirect specular lighting.
  6237. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  6238. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  6239. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  6240. const c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );
  6241. const c1 = vec4( 1, 0.0425, 1.04, - 0.04 );
  6242. const r = roughness.mul( c0 ).add( c1 );
  6243. const a004 = r.x.mul( r.x ).min( dotNV.mul( - 9.28 ).exp2() ).mul( r.x ).add( r.y );
  6244. const fab = vec2( - 1.04, 1.04 ).mul( a004 ).add( r.zw );
  6245. return fab;
  6246. } ).setLayout( {
  6247. name: 'DFGApprox',
  6248. type: 'vec2',
  6249. inputs: [
  6250. { name: 'roughness', type: 'float' },
  6251. { name: 'dotNV', type: 'vec3' }
  6252. ]
  6253. } );
  6254. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  6255. const { dotNV, specularColor, specularF90, roughness } = inputs;
  6256. const fab = DFGApprox( { dotNV, roughness } );
  6257. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  6258. } );
  6259. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  6260. const x = dotVH.oneMinus().saturate();
  6261. const x2 = x.mul( x );
  6262. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  6263. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  6264. } ).setLayout( {
  6265. name: 'Schlick_to_F0',
  6266. type: 'vec3',
  6267. inputs: [
  6268. { name: 'f', type: 'vec3' },
  6269. { name: 'f90', type: 'float' },
  6270. { name: 'dotVH', type: 'float' }
  6271. ]
  6272. } );
  6273. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  6274. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  6275. const alpha = roughness.pow2();
  6276. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  6277. const invAlpha = float( 1.0 ).div( alpha );
  6278. const cos2h = dotNH.pow2();
  6279. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  6280. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  6281. } ).setLayout( {
  6282. name: 'D_Charlie',
  6283. type: 'float',
  6284. inputs: [
  6285. { name: 'roughness', type: 'float' },
  6286. { name: 'dotNH', type: 'float' }
  6287. ]
  6288. } );
  6289. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  6290. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  6291. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  6292. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  6293. } ).setLayout( {
  6294. name: 'V_Neubelt',
  6295. type: 'float',
  6296. inputs: [
  6297. { name: 'dotNV', type: 'float' },
  6298. { name: 'dotNL', type: 'float' }
  6299. ]
  6300. } );
  6301. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  6302. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  6303. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  6304. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp();
  6305. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  6306. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  6307. const V = V_Neubelt( { dotNV, dotNL } );
  6308. return sheen.mul( D ).mul( V );
  6309. } );
  6310. // Rect Area Light
  6311. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  6312. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  6313. // code: https://github.com/selfshadow/ltc_code/
  6314. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  6315. const LUT_SIZE = 64.0;
  6316. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  6317. const LUT_BIAS = 0.5 / LUT_SIZE;
  6318. const dotNV = N.dot( V ).saturate();
  6319. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  6320. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  6321. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  6322. return uv;
  6323. } ).setLayout( {
  6324. name: 'LTC_Uv',
  6325. type: 'vec2',
  6326. inputs: [
  6327. { name: 'N', type: 'vec3' },
  6328. { name: 'V', type: 'vec3' },
  6329. { name: 'roughness', type: 'float' }
  6330. ]
  6331. } );
  6332. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  6333. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  6334. // An approximation of the form factor of a horizon-clipped rectangle.
  6335. const l = f.length();
  6336. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  6337. } ).setLayout( {
  6338. name: 'LTC_ClippedSphereFormFactor',
  6339. type: 'float',
  6340. inputs: [
  6341. { name: 'f', type: 'vec3' }
  6342. ]
  6343. } );
  6344. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  6345. const x = v1.dot( v2 );
  6346. const y = x.abs().toVar();
  6347. // rational polynomial approximation to theta / sin( theta ) / 2PI
  6348. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  6349. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  6350. const v = a.div( b );
  6351. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  6352. return v1.cross( v2 ).mul( theta_sintheta );
  6353. } ).setLayout( {
  6354. name: 'LTC_EdgeVectorFormFactor',
  6355. type: 'vec3',
  6356. inputs: [
  6357. { name: 'v1', type: 'vec3' },
  6358. { name: 'v2', type: 'vec3' }
  6359. ]
  6360. } );
  6361. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  6362. // bail if point is on back side of plane of light
  6363. // assumes ccw winding order of light vertices
  6364. const v1 = p1.sub( p0 ).toVar();
  6365. const v2 = p3.sub( p0 ).toVar();
  6366. const lightNormal = v1.cross( v2 );
  6367. const result = vec3().toVar();
  6368. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  6369. // construct orthonormal basis around N
  6370. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  6371. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  6372. // compute transform
  6373. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  6374. // transform rect
  6375. // & project rect onto sphere
  6376. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  6377. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  6378. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  6379. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  6380. // calculate vector form factor
  6381. const vectorFormFactor = vec3( 0 ).toVar();
  6382. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  6383. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  6384. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  6385. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  6386. // adjust for horizon clipping
  6387. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  6388. } );
  6389. return result;
  6390. } ).setLayout( {
  6391. name: 'LTC_Evaluate',
  6392. type: 'vec3',
  6393. inputs: [
  6394. { name: 'N', type: 'vec3' },
  6395. { name: 'V', type: 'vec3' },
  6396. { name: 'P', type: 'vec3' },
  6397. { name: 'mInv', type: 'mat3' },
  6398. { name: 'p0', type: 'vec3' },
  6399. { name: 'p1', type: 'vec3' },
  6400. { name: 'p2', type: 'vec3' },
  6401. { name: 'p3', type: 'vec3' }
  6402. ]
  6403. } );
  6404. // Mipped Bicubic Texture Filtering by N8
  6405. // https://www.shadertoy.com/view/Dl2SDW
  6406. const bC = 1.0 / 6.0;
  6407. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  6408. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  6409. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( - 3.0, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  6410. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  6411. const g0 = ( a ) => w0( a ).add( w1( a ) );
  6412. const g1 = ( a ) => w2( a ).add( w3( a ) );
  6413. // h0 and h1 are the two offset functions
  6414. const h0 = ( a ) => add( - 1.0, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  6415. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  6416. const bicubic = ( textureNode, texelSize, lod ) => {
  6417. const uv = textureNode.uvNode;
  6418. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  6419. const iuv = floor( uvScaled );
  6420. const fuv = fract( uvScaled );
  6421. const g0x = g0( fuv.x );
  6422. const g1x = g1( fuv.x );
  6423. const h0x = h0( fuv.x );
  6424. const h1x = h1( fuv.x );
  6425. const h0y = h0( fuv.y );
  6426. const h1y = h1( fuv.y );
  6427. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  6428. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  6429. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  6430. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  6431. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.uv( p0 ).level( lod ) ), g1x.mul( textureNode.uv( p1 ).level( lod ) ) ) );
  6432. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.uv( p2 ).level( lod ) ), g1x.mul( textureNode.uv( p3 ).level( lod ) ) ) );
  6433. return a.add( b );
  6434. };
  6435. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, lodNode = float( 3 ) ] ) => {
  6436. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  6437. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  6438. const fLodSizeInv = div( 1.0, fLodSize );
  6439. const cLodSizeInv = div( 1.0, cLodSize );
  6440. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  6441. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  6442. return fract( lodNode ).mix( fSample, cSample );
  6443. } );
  6444. //
  6445. // Transmission
  6446. //
  6447. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  6448. // Direction of refracted light.
  6449. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  6450. // Compute rotation-independant scaling of the model matrix.
  6451. const modelScale = vec3(
  6452. length( modelMatrix[ 0 ].xyz ),
  6453. length( modelMatrix[ 1 ].xyz ),
  6454. length( modelMatrix[ 2 ].xyz )
  6455. );
  6456. // The thickness is specified in local space.
  6457. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  6458. } ).setLayout( {
  6459. name: 'getVolumeTransmissionRay',
  6460. type: 'vec3',
  6461. inputs: [
  6462. { name: 'n', type: 'vec3' },
  6463. { name: 'v', type: 'vec3' },
  6464. { name: 'thickness', type: 'float' },
  6465. { name: 'ior', type: 'float' },
  6466. { name: 'modelMatrix', type: 'mat4' }
  6467. ]
  6468. } );
  6469. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  6470. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  6471. // an IOR of 1.5 results in the default amount of microfacet refraction.
  6472. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  6473. } ).setLayout( {
  6474. name: 'applyIorToRoughness',
  6475. type: 'float',
  6476. inputs: [
  6477. { name: 'roughness', type: 'float' },
  6478. { name: 'ior', type: 'float' }
  6479. ]
  6480. } );
  6481. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  6482. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  6483. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  6484. const vTexture = material.side == BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  6485. const transmissionSample = vTexture.uv( fragCoord );
  6486. //const transmissionSample = viewportMipTexture( fragCoord );
  6487. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  6488. return textureBicubic( transmissionSample, lod );
  6489. } );
  6490. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  6491. If( attenuationDistance.notEqual( 0 ), () => {
  6492. // Compute light attenuation using Beer's law.
  6493. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  6494. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  6495. return transmittance;
  6496. } );
  6497. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  6498. return vec3( 1.0 );
  6499. } ).setLayout( {
  6500. name: 'volumeAttenuation',
  6501. type: 'vec3',
  6502. inputs: [
  6503. { name: 'transmissionDistance', type: 'float' },
  6504. { name: 'attenuationColor', type: 'vec3' },
  6505. { name: 'attenuationDistance', type: 'float' }
  6506. ]
  6507. } );
  6508. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  6509. let transmittedLight, transmittance;
  6510. if ( dispersion ) {
  6511. transmittedLight = vec4().toVar();
  6512. transmittance = vec3().toVar();
  6513. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  6514. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  6515. Loop( { start: 0, end: 3 }, ( { i } ) => {
  6516. const ior = iors.element( i );
  6517. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  6518. const refractedRayExit = position.add( transmissionRay );
  6519. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  6520. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  6521. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  6522. refractionCoords.addAssign( 1.0 );
  6523. refractionCoords.divAssign( 2.0 );
  6524. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  6525. // Sample framebuffer to get pixel the refracted ray hits.
  6526. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  6527. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  6528. transmittedLight.a.addAssign( transmissionSample.a );
  6529. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  6530. } );
  6531. transmittedLight.a.divAssign( 3.0 );
  6532. } else {
  6533. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  6534. const refractedRayExit = position.add( transmissionRay );
  6535. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  6536. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  6537. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  6538. refractionCoords.addAssign( 1.0 );
  6539. refractionCoords.divAssign( 2.0 );
  6540. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  6541. // Sample framebuffer to get pixel the refracted ray hits.
  6542. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  6543. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  6544. }
  6545. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  6546. const dotNV = n.dot( v ).clamp();
  6547. // Get the specular component.
  6548. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  6549. dotNV,
  6550. specularColor,
  6551. specularF90,
  6552. roughness
  6553. } ) );
  6554. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  6555. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  6556. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  6557. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  6558. } );
  6559. //
  6560. // Iridescence
  6561. //
  6562. // XYZ to linear-sRGB color space
  6563. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  6564. 3.2404542, - 0.9692660, 0.0556434,
  6565. - 1.5371385, 1.8760108, - 0.2040259,
  6566. - 0.4985314, 0.0415560, 1.0572252
  6567. );
  6568. // Assume air interface for top
  6569. // Note: We don't handle the case fresnel0 == 1
  6570. const Fresnel0ToIor = ( fresnel0 ) => {
  6571. const sqrtF0 = fresnel0.sqrt();
  6572. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  6573. };
  6574. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  6575. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  6576. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  6577. };
  6578. // Fresnel equations for dielectric/dielectric interfaces.
  6579. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  6580. // Evaluation XYZ sensitivity curves in Fourier space
  6581. const evalSensitivity = ( OPD, shift ) => {
  6582. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  6583. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  6584. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  6585. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  6586. 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() );
  6587. 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() );
  6588. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  6589. const rgb = XYZ_TO_REC709.mul( xyz );
  6590. return rgb;
  6591. };
  6592. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  6593. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  6594. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  6595. // Evaluate the cosTheta on the base layer (Snell law)
  6596. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  6597. // Handle TIR:
  6598. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  6599. If( cosTheta2Sq.lessThan( 0 ), () => {
  6600. return vec3( 1.0 );
  6601. } );
  6602. const cosTheta2 = cosTheta2Sq.sqrt();
  6603. // First interface
  6604. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  6605. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  6606. //const R21 = R12;
  6607. const T121 = R12.oneMinus();
  6608. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  6609. const phi21 = float( Math.PI ).sub( phi12 );
  6610. // Second interface
  6611. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  6612. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  6613. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  6614. const phi23 = vec3(
  6615. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  6616. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  6617. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  6618. );
  6619. // Phase shift
  6620. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  6621. const phi = vec3( phi21 ).add( phi23 );
  6622. // Compound terms
  6623. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  6624. const r123 = R123.sqrt();
  6625. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  6626. // Reflectance term for m = 0 (DC term amplitude)
  6627. const C0 = R12.add( Rs );
  6628. const I = C0.toVar();
  6629. // Reflectance term for m > 0 (pairs of diracs)
  6630. const Cm = Rs.sub( T121 ).toVar();
  6631. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  6632. Cm.mulAssign( r123 );
  6633. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  6634. I.addAssign( Cm.mul( Sm ) );
  6635. } );
  6636. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  6637. return I.max( vec3( 0.0 ) );
  6638. } ).setLayout( {
  6639. name: 'evalIridescence',
  6640. type: 'vec3',
  6641. inputs: [
  6642. { name: 'outsideIOR', type: 'float' },
  6643. { name: 'eta2', type: 'float' },
  6644. { name: 'cosTheta1', type: 'float' },
  6645. { name: 'thinFilmThickness', type: 'float' },
  6646. { name: 'baseF0', type: 'vec3' }
  6647. ]
  6648. } );
  6649. //
  6650. // Sheen
  6651. //
  6652. // This is a curve-fit approxmation to the "Charlie sheen" BRDF integrated over the hemisphere from
  6653. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  6654. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  6655. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  6656. const dotNV = normal.dot( viewDir ).saturate();
  6657. const r2 = roughness.pow2();
  6658. const a = select(
  6659. roughness.lessThan( 0.25 ),
  6660. float( - 339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  6661. float( - 8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  6662. );
  6663. const b = select(
  6664. roughness.lessThan( 0.25 ),
  6665. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  6666. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  6667. );
  6668. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  6669. return DG.mul( 1.0 / Math.PI ).saturate();
  6670. } );
  6671. const clearcoatF0 = vec3( 0.04 );
  6672. const clearcoatF90 = float( 1 );
  6673. //
  6674. class PhysicalLightingModel extends LightingModel {
  6675. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  6676. super();
  6677. this.clearcoat = clearcoat;
  6678. this.sheen = sheen;
  6679. this.iridescence = iridescence;
  6680. this.anisotropy = anisotropy;
  6681. this.transmission = transmission;
  6682. this.dispersion = dispersion;
  6683. this.clearcoatRadiance = null;
  6684. this.clearcoatSpecularDirect = null;
  6685. this.clearcoatSpecularIndirect = null;
  6686. this.sheenSpecularDirect = null;
  6687. this.sheenSpecularIndirect = null;
  6688. this.iridescenceFresnel = null;
  6689. this.iridescenceF0 = null;
  6690. }
  6691. start( context ) {
  6692. if ( this.clearcoat === true ) {
  6693. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  6694. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  6695. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  6696. }
  6697. if ( this.sheen === true ) {
  6698. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  6699. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  6700. }
  6701. if ( this.iridescence === true ) {
  6702. const dotNVi = transformedNormalView.dot( positionViewDirection ).clamp();
  6703. this.iridescenceFresnel = evalIridescence( {
  6704. outsideIOR: float( 1.0 ),
  6705. eta2: iridescenceIOR,
  6706. cosTheta1: dotNVi,
  6707. thinFilmThickness: iridescenceThickness,
  6708. baseF0: specularColor
  6709. } );
  6710. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  6711. }
  6712. if ( this.transmission === true ) {
  6713. const position = positionWorld;
  6714. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  6715. const n = transformedNormalWorld;
  6716. context.backdrop = getIBLVolumeRefraction(
  6717. n,
  6718. v,
  6719. roughness,
  6720. diffuseColor,
  6721. specularColor,
  6722. specularF90, // specularF90
  6723. position, // positionWorld
  6724. modelWorldMatrix, // modelMatrix
  6725. cameraViewMatrix, // viewMatrix
  6726. cameraProjectionMatrix, // projMatrix
  6727. ior,
  6728. thickness,
  6729. attenuationColor,
  6730. attenuationDistance,
  6731. this.dispersion ? dispersion : null
  6732. );
  6733. context.backdropAlpha = transmission;
  6734. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  6735. }
  6736. }
  6737. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  6738. // Approximates multiscattering in order to preserve energy.
  6739. // http://www.jcgt.org/published/0008/01/03/
  6740. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  6741. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  6742. const fab = DFGApprox( { roughness, dotNV } );
  6743. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  6744. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  6745. const Ess = fab.x.add( fab.y );
  6746. const Ems = Ess.oneMinus();
  6747. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  6748. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  6749. singleScatter.addAssign( FssEss );
  6750. multiScatter.addAssign( Fms.mul( Ems ) );
  6751. }
  6752. direct( { lightDirection, lightColor, reflectedLight } ) {
  6753. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  6754. const irradiance = dotNL.mul( lightColor );
  6755. if ( this.sheen === true ) {
  6756. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  6757. }
  6758. if ( this.clearcoat === true ) {
  6759. const dotNLcc = transformedClearcoatNormalView.dot( lightDirection ).clamp();
  6760. const ccIrradiance = dotNLcc.mul( lightColor );
  6761. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: transformedClearcoatNormalView } ) ) );
  6762. }
  6763. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  6764. 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 } ) ) );
  6765. }
  6766. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 } ) {
  6767. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  6768. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  6769. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  6770. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  6771. const N = transformedNormalView;
  6772. const V = positionViewDirection;
  6773. const P = positionView.toVar();
  6774. const uv = LTC_Uv( { N, V, roughness } );
  6775. const t1 = ltc_1.uv( uv ).toVar();
  6776. const t2 = ltc_2.uv( uv ).toVar();
  6777. const mInv = mat3(
  6778. vec3( t1.x, 0, t1.y ),
  6779. vec3( 0, 1, 0 ),
  6780. vec3( t1.z, 0, t1.w )
  6781. ).toVar();
  6782. // LTC Fresnel Approximation by Stephen Hill
  6783. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  6784. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  6785. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  6786. 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 } ) ) );
  6787. }
  6788. indirect( context, stack, builder ) {
  6789. this.indirectDiffuse( context, stack, builder );
  6790. this.indirectSpecular( context, stack, builder );
  6791. this.ambientOcclusion( context, stack, builder );
  6792. }
  6793. indirectDiffuse( { irradiance, reflectedLight } ) {
  6794. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  6795. }
  6796. indirectSpecular( { radiance, iblIrradiance, reflectedLight } ) {
  6797. if ( this.sheen === true ) {
  6798. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  6799. sheen,
  6800. IBLSheenBRDF( {
  6801. normal: transformedNormalView,
  6802. viewDir: positionViewDirection,
  6803. roughness: sheenRoughness
  6804. } )
  6805. ) );
  6806. }
  6807. if ( this.clearcoat === true ) {
  6808. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  6809. const clearcoatEnv = EnvironmentBRDF( {
  6810. dotNV: dotNVcc,
  6811. specularColor: clearcoatF0,
  6812. specularF90: clearcoatF90,
  6813. roughness: clearcoatRoughness
  6814. } );
  6815. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  6816. }
  6817. // Both indirect specular and indirect diffuse light accumulate here
  6818. const singleScattering = vec3().toVar( 'singleScattering' );
  6819. const multiScattering = vec3().toVar( 'multiScattering' );
  6820. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  6821. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  6822. const totalScattering = singleScattering.add( multiScattering );
  6823. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  6824. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  6825. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  6826. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  6827. }
  6828. ambientOcclusion( { ambientOcclusion, reflectedLight } ) {
  6829. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  6830. const aoNV = dotNV.add( ambientOcclusion );
  6831. const aoExp = roughness.mul( - 16.0 ).oneMinus().negate().exp2();
  6832. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  6833. if ( this.clearcoat === true ) {
  6834. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  6835. }
  6836. if ( this.sheen === true ) {
  6837. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  6838. }
  6839. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  6840. reflectedLight.indirectSpecular.mulAssign( aoNode );
  6841. }
  6842. finish( context ) {
  6843. const { outgoingLight } = context;
  6844. if ( this.clearcoat === true ) {
  6845. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  6846. const Fcc = F_Schlick( {
  6847. dotVH: dotNVcc,
  6848. f0: clearcoatF0,
  6849. f90: clearcoatF90
  6850. } );
  6851. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  6852. outgoingLight.assign( clearcoatLight );
  6853. }
  6854. if ( this.sheen === true ) {
  6855. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  6856. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  6857. outgoingLight.assign( sheenLight );
  6858. }
  6859. }
  6860. }
  6861. // These defines must match with PMREMGenerator
  6862. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  6863. const cubeUV_m0 = /*@__PURE__*/ float( - 2.0 );
  6864. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  6865. const cubeUV_m1 = /*@__PURE__*/ float( - 1.0 );
  6866. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  6867. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  6868. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  6869. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  6870. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  6871. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  6872. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  6873. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  6874. // These shader functions convert between the UV coordinates of a single face of
  6875. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  6876. // sampling a textureCube (not generally normalized ).
  6877. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  6878. const absDirection = vec3( abs( direction ) ).toVar();
  6879. const face = float( - 1.0 ).toVar();
  6880. If( absDirection.x.greaterThan( absDirection.z ), () => {
  6881. If( absDirection.x.greaterThan( absDirection.y ), () => {
  6882. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  6883. } ).Else( () => {
  6884. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  6885. } );
  6886. } ).Else( () => {
  6887. If( absDirection.z.greaterThan( absDirection.y ), () => {
  6888. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  6889. } ).Else( () => {
  6890. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  6891. } );
  6892. } );
  6893. return face;
  6894. } ).setLayout( {
  6895. name: 'getFace',
  6896. type: 'float',
  6897. inputs: [
  6898. { name: 'direction', type: 'vec3' }
  6899. ]
  6900. } );
  6901. // RH coordinate system; PMREM face-indexing convention
  6902. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  6903. const uv = vec2().toVar();
  6904. If( face.equal( 0.0 ), () => {
  6905. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  6906. } ).ElseIf( face.equal( 1.0 ), () => {
  6907. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  6908. } ).ElseIf( face.equal( 2.0 ), () => {
  6909. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  6910. } ).ElseIf( face.equal( 3.0 ), () => {
  6911. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  6912. } ).ElseIf( face.equal( 4.0 ), () => {
  6913. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  6914. } ).Else( () => {
  6915. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  6916. } );
  6917. return mul( 0.5, uv.add( 1.0 ) );
  6918. } ).setLayout( {
  6919. name: 'getUV',
  6920. type: 'vec2',
  6921. inputs: [
  6922. { name: 'direction', type: 'vec3' },
  6923. { name: 'face', type: 'float' }
  6924. ]
  6925. } );
  6926. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  6927. const mip = float( 0.0 ).toVar();
  6928. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  6929. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  6930. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  6931. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  6932. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  6933. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  6934. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  6935. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  6936. } ).Else( () => {
  6937. mip.assign( float( - 2.0 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  6938. } );
  6939. return mip;
  6940. } ).setLayout( {
  6941. name: 'roughnessToMip',
  6942. type: 'float',
  6943. inputs: [
  6944. { name: 'roughness', type: 'float' }
  6945. ]
  6946. } );
  6947. // RH coordinate system; PMREM face-indexing convention
  6948. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  6949. const uv = uv_immutable.toVar();
  6950. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  6951. const direction = vec3( uv, 1.0 ).toVar();
  6952. If( face.equal( 0.0 ), () => {
  6953. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  6954. } ).ElseIf( face.equal( 1.0 ), () => {
  6955. direction.assign( direction.xzy );
  6956. direction.xz.mulAssign( - 1.0 ); // ( -u, 1, -v ) pos y
  6957. } ).ElseIf( face.equal( 2.0 ), () => {
  6958. direction.x.mulAssign( - 1.0 ); // ( -u, v, 1 ) pos z
  6959. } ).ElseIf( face.equal( 3.0 ), () => {
  6960. direction.assign( direction.zyx );
  6961. direction.xz.mulAssign( - 1.0 ); // ( -1, v, -u ) neg x
  6962. } ).ElseIf( face.equal( 4.0 ), () => {
  6963. direction.assign( direction.xzy );
  6964. direction.xy.mulAssign( - 1.0 ); // ( -u, -1, v ) neg y
  6965. } ).ElseIf( face.equal( 5.0 ), () => {
  6966. direction.z.mulAssign( - 1.0 ); // ( u, v, -1 ) neg zS
  6967. } );
  6968. return direction;
  6969. } ).setLayout( {
  6970. name: 'getDirection',
  6971. type: 'vec3',
  6972. inputs: [
  6973. { name: 'uv', type: 'vec2' },
  6974. { name: 'face', type: 'float' }
  6975. ]
  6976. } );
  6977. //
  6978. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  6979. const roughness = float( roughness_immutable );
  6980. const sampleDir = vec3( sampleDir_immutable );
  6981. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  6982. const mipF = fract( mip );
  6983. const mipInt = floor( mip );
  6984. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  6985. If( mipF.notEqual( 0.0 ), () => {
  6986. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  6987. color0.assign( mix( color0, color1, mipF ) );
  6988. } );
  6989. return color0;
  6990. } );
  6991. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  6992. const mipInt = float( mipInt_immutable ).toVar();
  6993. const direction = vec3( direction_immutable );
  6994. const face = float( getFace( direction ) ).toVar();
  6995. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  6996. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  6997. const faceSize = float( exp2( mipInt ) ).toVar();
  6998. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  6999. If( face.greaterThan( 2.0 ), () => {
  7000. uv.y.addAssign( faceSize );
  7001. face.subAssign( 3.0 );
  7002. } );
  7003. uv.x.addAssign( face.mul( faceSize ) );
  7004. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  7005. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  7006. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  7007. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  7008. return envMap.uv( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  7009. } );
  7010. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  7011. const cosTheta = cos( theta );
  7012. // Rodrigues' axis-angle rotation
  7013. const sampleDirection = outputDirection.mul( cosTheta )
  7014. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  7015. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  7016. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  7017. } );
  7018. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  7019. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  7020. If( all( axis.equals( vec3( 0.0 ) ) ), () => {
  7021. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  7022. } );
  7023. axis.assign( normalize( axis ) );
  7024. const gl_FragColor = vec3().toVar();
  7025. 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 } ) ) );
  7026. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  7027. If( i.greaterThanEqual( samples ), () => {
  7028. Break();
  7029. } );
  7030. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  7031. 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 } ) ) );
  7032. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  7033. } );
  7034. return vec4( gl_FragColor, 1 );
  7035. } );
  7036. let _generator = null;
  7037. const _cache = new WeakMap();
  7038. function _generateCubeUVSize( imageHeight ) {
  7039. const maxMip = Math.log2( imageHeight ) - 2;
  7040. const texelHeight = 1.0 / imageHeight;
  7041. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  7042. return { texelWidth, texelHeight, maxMip };
  7043. }
  7044. function _getPMREMFromTexture( texture ) {
  7045. let cacheTexture = _cache.get( texture );
  7046. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : - 1;
  7047. if ( pmremVersion !== texture.pmremVersion ) {
  7048. const image = texture.image;
  7049. if ( texture.isCubeTexture ) {
  7050. if ( isCubeMapReady( image ) ) {
  7051. cacheTexture = _generator.fromCubemap( texture, cacheTexture );
  7052. } else {
  7053. return null;
  7054. }
  7055. } else {
  7056. if ( isEquirectangularMapReady( image ) ) {
  7057. cacheTexture = _generator.fromEquirectangular( texture, cacheTexture );
  7058. } else {
  7059. return null;
  7060. }
  7061. }
  7062. cacheTexture.pmremVersion = texture.pmremVersion;
  7063. _cache.set( texture, cacheTexture );
  7064. }
  7065. return cacheTexture.texture;
  7066. }
  7067. class PMREMNode extends TempNode {
  7068. static get type() {
  7069. return 'PMREMNode';
  7070. }
  7071. constructor( value, uvNode = null, levelNode = null ) {
  7072. super( 'vec3' );
  7073. this._value = value;
  7074. this._pmrem = null;
  7075. this.uvNode = uvNode;
  7076. this.levelNode = levelNode;
  7077. this._generator = null;
  7078. const defaultTexture = new Texture();
  7079. defaultTexture.isRenderTargetTexture = true;
  7080. this._texture = texture( defaultTexture );
  7081. this._width = uniform( 0 );
  7082. this._height = uniform( 0 );
  7083. this._maxMip = uniform( 0 );
  7084. this.updateBeforeType = NodeUpdateType.RENDER;
  7085. }
  7086. set value( value ) {
  7087. this._value = value;
  7088. this._pmrem = null;
  7089. }
  7090. get value() {
  7091. return this._value;
  7092. }
  7093. updateFromTexture( texture ) {
  7094. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  7095. this._texture.value = texture;
  7096. this._width.value = cubeUVSize.texelWidth;
  7097. this._height.value = cubeUVSize.texelHeight;
  7098. this._maxMip.value = cubeUVSize.maxMip;
  7099. }
  7100. updateBefore() {
  7101. let pmrem = this._pmrem;
  7102. const pmremVersion = pmrem ? pmrem.pmremVersion : - 1;
  7103. const texture = this._value;
  7104. if ( pmremVersion !== texture.pmremVersion ) {
  7105. if ( texture.isPMREMTexture === true ) {
  7106. pmrem = texture;
  7107. } else {
  7108. pmrem = _getPMREMFromTexture( texture );
  7109. }
  7110. if ( pmrem !== null ) {
  7111. this._pmrem = pmrem;
  7112. this.updateFromTexture( pmrem );
  7113. }
  7114. }
  7115. }
  7116. setup( builder ) {
  7117. if ( _generator === null ) {
  7118. _generator = builder.createPMREMGenerator();
  7119. }
  7120. //
  7121. this.updateBefore( builder );
  7122. //
  7123. let uvNode = this.uvNode;
  7124. if ( uvNode === null && builder.context.getUV ) {
  7125. uvNode = builder.context.getUV( this );
  7126. }
  7127. //
  7128. const texture = this.value;
  7129. if ( builder.renderer.coordinateSystem === WebGLCoordinateSystem && texture.isPMREMTexture !== true && texture.isRenderTargetTexture === true ) {
  7130. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  7131. }
  7132. //
  7133. let levelNode = this.levelNode;
  7134. if ( levelNode === null && builder.context.getTextureLevel ) {
  7135. levelNode = builder.context.getTextureLevel( this );
  7136. }
  7137. //
  7138. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  7139. }
  7140. }
  7141. function isCubeMapReady( image ) {
  7142. if ( image === null || image === undefined ) return false;
  7143. let count = 0;
  7144. const length = 6;
  7145. for ( let i = 0; i < length; i ++ ) {
  7146. if ( image[ i ] !== undefined ) count ++;
  7147. }
  7148. return count === length;
  7149. }
  7150. function isEquirectangularMapReady( image ) {
  7151. if ( image === null || image === undefined ) return false;
  7152. return image.height > 0;
  7153. }
  7154. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode );
  7155. const _envNodeCache = new WeakMap();
  7156. class EnvironmentNode extends LightingNode {
  7157. static get type() {
  7158. return 'EnvironmentNode';
  7159. }
  7160. constructor( envNode = null ) {
  7161. super();
  7162. this.envNode = envNode;
  7163. }
  7164. setup( builder ) {
  7165. const { material } = builder;
  7166. let envNode = this.envNode;
  7167. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  7168. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  7169. let cacheEnvNode = _envNodeCache.get( value );
  7170. if ( cacheEnvNode === undefined ) {
  7171. cacheEnvNode = pmremTexture( value );
  7172. _envNodeCache.set( value, cacheEnvNode );
  7173. }
  7174. envNode = cacheEnvNode;
  7175. }
  7176. //
  7177. const envMap = material.envMap;
  7178. const intensity = envMap ? reference( 'envMapIntensity', 'float', builder.material ) : reference( 'environmentIntensity', 'float', builder.scene ); // @TODO: Add materialEnvIntensity in MaterialNode
  7179. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  7180. const radianceNormalView = useAnisotropy ? transformedBentNormalView : transformedNormalView;
  7181. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( intensity );
  7182. const irradiance = envNode.context( createIrradianceContext( transformedNormalWorld ) ).mul( Math.PI ).mul( intensity );
  7183. const isolateRadiance = cache( radiance );
  7184. const isolateIrradiance = cache( irradiance );
  7185. //
  7186. builder.context.radiance.addAssign( isolateRadiance );
  7187. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  7188. //
  7189. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  7190. if ( clearcoatRadiance ) {
  7191. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, transformedClearcoatNormalView ) ).mul( intensity );
  7192. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  7193. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  7194. }
  7195. }
  7196. }
  7197. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  7198. let reflectVec = null;
  7199. return {
  7200. getUV: () => {
  7201. if ( reflectVec === null ) {
  7202. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  7203. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  7204. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  7205. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  7206. }
  7207. return reflectVec;
  7208. },
  7209. getTextureLevel: () => {
  7210. return roughnessNode;
  7211. }
  7212. };
  7213. };
  7214. const createIrradianceContext = ( normalWorldNode ) => {
  7215. return {
  7216. getUV: () => {
  7217. return normalWorldNode;
  7218. },
  7219. getTextureLevel: () => {
  7220. return float( 1.0 );
  7221. }
  7222. };
  7223. };
  7224. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  7225. class MeshStandardNodeMaterial extends NodeMaterial {
  7226. static get type() {
  7227. return 'MeshStandardNodeMaterial';
  7228. }
  7229. constructor( parameters ) {
  7230. super();
  7231. this.isMeshStandardNodeMaterial = true;
  7232. this.lights = true;
  7233. this.emissiveNode = null;
  7234. this.metalnessNode = null;
  7235. this.roughnessNode = null;
  7236. this.setDefaultValues( _defaultValues$6 );
  7237. this.setValues( parameters );
  7238. }
  7239. setupEnvironment( builder ) {
  7240. let envNode = super.setupEnvironment( builder );
  7241. if ( envNode === null && builder.environmentNode ) {
  7242. envNode = builder.environmentNode;
  7243. }
  7244. return envNode ? new EnvironmentNode( envNode ) : null;
  7245. }
  7246. setupLightingModel( /*builder*/ ) {
  7247. return new PhysicalLightingModel();
  7248. }
  7249. setupSpecular() {
  7250. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  7251. specularColor.assign( specularColorNode );
  7252. specularF90.assign( 1.0 );
  7253. }
  7254. setupVariants() {
  7255. // METALNESS
  7256. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  7257. metalness.assign( metalnessNode );
  7258. // ROUGHNESS
  7259. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  7260. roughnessNode = getRoughness( { roughness: roughnessNode } );
  7261. roughness.assign( roughnessNode );
  7262. // SPECULAR COLOR
  7263. this.setupSpecular();
  7264. // DIFFUSE COLOR
  7265. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  7266. }
  7267. copy( source ) {
  7268. this.emissiveNode = source.emissiveNode;
  7269. this.metalnessNode = source.metalnessNode;
  7270. this.roughnessNode = source.roughnessNode;
  7271. return super.copy( source );
  7272. }
  7273. }
  7274. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  7275. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  7276. static get type() {
  7277. return 'MeshPhysicalNodeMaterial';
  7278. }
  7279. constructor( parameters ) {
  7280. super();
  7281. this.isMeshPhysicalNodeMaterial = true;
  7282. this.clearcoatNode = null;
  7283. this.clearcoatRoughnessNode = null;
  7284. this.clearcoatNormalNode = null;
  7285. this.sheenNode = null;
  7286. this.sheenRoughnessNode = null;
  7287. this.iridescenceNode = null;
  7288. this.iridescenceIORNode = null;
  7289. this.iridescenceThicknessNode = null;
  7290. this.specularIntensityNode = null;
  7291. this.specularColorNode = null;
  7292. this.iorNode = null;
  7293. this.transmissionNode = null;
  7294. this.thicknessNode = null;
  7295. this.attenuationDistanceNode = null;
  7296. this.attenuationColorNode = null;
  7297. this.dispersionNode = null;
  7298. this.anisotropyNode = null;
  7299. this.setDefaultValues( _defaultValues$5 );
  7300. this.setValues( parameters );
  7301. }
  7302. get useClearcoat() {
  7303. return this.clearcoat > 0 || this.clearcoatNode !== null;
  7304. }
  7305. get useIridescence() {
  7306. return this.iridescence > 0 || this.iridescenceNode !== null;
  7307. }
  7308. get useSheen() {
  7309. return this.sheen > 0 || this.sheenNode !== null;
  7310. }
  7311. get useAnisotropy() {
  7312. return this.anisotropy > 0 || this.anisotropyNode !== null;
  7313. }
  7314. get useTransmission() {
  7315. return this.transmission > 0 || this.transmissionNode !== null;
  7316. }
  7317. get useDispersion() {
  7318. return this.dispersion > 0 || this.dispersionNode !== null;
  7319. }
  7320. setupSpecular() {
  7321. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  7322. ior.assign( iorNode );
  7323. 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 ) );
  7324. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  7325. }
  7326. setupLightingModel( /*builder*/ ) {
  7327. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  7328. }
  7329. setupVariants( builder ) {
  7330. super.setupVariants( builder );
  7331. // CLEARCOAT
  7332. if ( this.useClearcoat ) {
  7333. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  7334. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  7335. clearcoat.assign( clearcoatNode );
  7336. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  7337. }
  7338. // SHEEN
  7339. if ( this.useSheen ) {
  7340. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  7341. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  7342. sheen.assign( sheenNode );
  7343. sheenRoughness.assign( sheenRoughnessNode );
  7344. }
  7345. // IRIDESCENCE
  7346. if ( this.useIridescence ) {
  7347. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  7348. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  7349. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  7350. iridescence.assign( iridescenceNode );
  7351. iridescenceIOR.assign( iridescenceIORNode );
  7352. iridescenceThickness.assign( iridescenceThicknessNode );
  7353. }
  7354. // ANISOTROPY
  7355. if ( this.useAnisotropy ) {
  7356. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  7357. anisotropy.assign( anisotropyV.length() );
  7358. If( anisotropy.equal( 0.0 ), () => {
  7359. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  7360. } ).Else( () => {
  7361. anisotropyV.divAssign( vec2( anisotropy ) );
  7362. anisotropy.assign( anisotropy.saturate() );
  7363. } );
  7364. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  7365. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  7366. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  7367. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  7368. }
  7369. // TRANSMISSION
  7370. if ( this.useTransmission ) {
  7371. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  7372. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  7373. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  7374. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  7375. transmission.assign( transmissionNode );
  7376. thickness.assign( thicknessNode );
  7377. attenuationDistance.assign( attenuationDistanceNode );
  7378. attenuationColor.assign( attenuationColorNode );
  7379. if ( this.useDispersion ) {
  7380. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  7381. dispersion.assign( dispersionNode );
  7382. }
  7383. }
  7384. }
  7385. setupClearcoatNormal() {
  7386. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  7387. }
  7388. setup( builder ) {
  7389. builder.context.setupClearcoatNormal = () => this.setupClearcoatNormal( builder );
  7390. super.setup( builder );
  7391. }
  7392. copy( source ) {
  7393. this.clearcoatNode = source.clearcoatNode;
  7394. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  7395. this.clearcoatNormalNode = source.clearcoatNormalNode;
  7396. this.sheenNode = source.sheenNode;
  7397. this.sheenRoughnessNode = source.sheenRoughnessNode;
  7398. this.iridescenceNode = source.iridescenceNode;
  7399. this.iridescenceIORNode = source.iridescenceIORNode;
  7400. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  7401. this.specularIntensityNode = source.specularIntensityNode;
  7402. this.specularColorNode = source.specularColorNode;
  7403. this.transmissionNode = source.transmissionNode;
  7404. this.thicknessNode = source.thicknessNode;
  7405. this.attenuationDistanceNode = source.attenuationDistanceNode;
  7406. this.attenuationColorNode = source.attenuationColorNode;
  7407. this.dispersionNode = source.dispersionNode;
  7408. this.anisotropyNode = source.anisotropyNode;
  7409. return super.copy( source );
  7410. }
  7411. }
  7412. class SSSLightingModel extends PhysicalLightingModel {
  7413. constructor( useClearcoat, useSheen, useIridescence, useSSS ) {
  7414. super( useClearcoat, useSheen, useIridescence );
  7415. this.useSSS = useSSS;
  7416. }
  7417. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  7418. if ( this.useSSS === true ) {
  7419. const material = builder.material;
  7420. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  7421. const scatteringHalf = lightDirection.add( transformedNormalView.mul( thicknessDistortionNode ) ).normalize();
  7422. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  7423. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  7424. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  7425. }
  7426. super.direct( { lightDirection, lightColor, reflectedLight }, stack, builder );
  7427. }
  7428. }
  7429. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  7430. static get type() {
  7431. return 'MeshSSSNodeMaterial';
  7432. }
  7433. constructor( parameters ) {
  7434. super( parameters );
  7435. this.thicknessColorNode = null;
  7436. this.thicknessDistortionNode = float( 0.1 );
  7437. this.thicknessAmbientNode = float( 0.0 );
  7438. this.thicknessAttenuationNode = float( .1 );
  7439. this.thicknessPowerNode = float( 2.0 );
  7440. this.thicknessScaleNode = float( 10.0 );
  7441. }
  7442. get useSSS() {
  7443. return this.thicknessColorNode !== null;
  7444. }
  7445. setupLightingModel( /*builder*/ ) {
  7446. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useSSS );
  7447. }
  7448. copy( source ) {
  7449. this.thicknessColorNode = source.thicknessColorNode;
  7450. this.thicknessDistortionNode = source.thicknessDistortionNode;
  7451. this.thicknessAmbientNode = source.thicknessAmbientNode;
  7452. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  7453. this.thicknessPowerNode = source.thicknessPowerNode;
  7454. this.thicknessScaleNode = source.thicknessScaleNode;
  7455. return super.copy( source );
  7456. }
  7457. }
  7458. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  7459. // dotNL will be from -1.0 to 1.0
  7460. const dotNL = normal.dot( lightDirection );
  7461. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  7462. if ( builder.material.gradientMap ) {
  7463. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  7464. return vec3( gradientMap.r );
  7465. } else {
  7466. const fw = coord.fwidth().mul( 0.5 );
  7467. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  7468. }
  7469. } );
  7470. class ToonLightingModel extends LightingModel {
  7471. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  7472. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  7473. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  7474. }
  7475. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  7476. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  7477. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  7478. }
  7479. }
  7480. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  7481. class MeshToonNodeMaterial extends NodeMaterial {
  7482. static get type() {
  7483. return 'MeshToonNodeMaterial';
  7484. }
  7485. constructor( parameters ) {
  7486. super();
  7487. this.isMeshToonNodeMaterial = true;
  7488. this.lights = true;
  7489. this.setDefaultValues( _defaultValues$4 );
  7490. this.setValues( parameters );
  7491. }
  7492. setupLightingModel( /*builder*/ ) {
  7493. return new ToonLightingModel();
  7494. }
  7495. }
  7496. class MatcapUVNode extends TempNode {
  7497. static get type() {
  7498. return 'MatcapUVNode';
  7499. }
  7500. constructor() {
  7501. super( 'vec2' );
  7502. }
  7503. setup() {
  7504. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  7505. const y = positionViewDirection.cross( x );
  7506. return vec2( x.dot( transformedNormalView ), y.dot( transformedNormalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  7507. }
  7508. }
  7509. const matcapUV = /*@__PURE__*/ nodeImmutable( MatcapUVNode );
  7510. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  7511. class MeshMatcapNodeMaterial extends NodeMaterial {
  7512. static get type() {
  7513. return 'MeshMatcapNodeMaterial';
  7514. }
  7515. constructor( parameters ) {
  7516. super();
  7517. this.lights = false;
  7518. this.isMeshMatcapNodeMaterial = true;
  7519. this.setDefaultValues( _defaultValues$3 );
  7520. this.setValues( parameters );
  7521. }
  7522. setupVariants( builder ) {
  7523. const uv = matcapUV;
  7524. let matcapColor;
  7525. if ( builder.material.matcap ) {
  7526. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  7527. } else {
  7528. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  7529. }
  7530. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  7531. }
  7532. }
  7533. const _defaultValues$2 = /*@__PURE__*/ new PointsMaterial();
  7534. class PointsNodeMaterial extends NodeMaterial {
  7535. static get type() {
  7536. return 'PointsNodeMaterial';
  7537. }
  7538. constructor( parameters ) {
  7539. super();
  7540. this.isPointsNodeMaterial = true;
  7541. this.lights = false;
  7542. this.transparent = true;
  7543. this.sizeNode = null;
  7544. this.setDefaultValues( _defaultValues$2 );
  7545. this.setValues( parameters );
  7546. }
  7547. copy( source ) {
  7548. this.sizeNode = source.sizeNode;
  7549. return super.copy( source );
  7550. }
  7551. }
  7552. class RotateNode extends TempNode {
  7553. static get type() {
  7554. return 'RotateNode';
  7555. }
  7556. constructor( positionNode, rotationNode ) {
  7557. super();
  7558. this.positionNode = positionNode;
  7559. this.rotationNode = rotationNode;
  7560. }
  7561. getNodeType( builder ) {
  7562. return this.positionNode.getNodeType( builder );
  7563. }
  7564. setup( builder ) {
  7565. const { rotationNode, positionNode } = this;
  7566. const nodeType = this.getNodeType( builder );
  7567. if ( nodeType === 'vec2' ) {
  7568. const cosAngle = rotationNode.cos();
  7569. const sinAngle = rotationNode.sin();
  7570. const rotationMatrix = mat2(
  7571. cosAngle, sinAngle,
  7572. sinAngle.negate(), cosAngle
  7573. );
  7574. return rotationMatrix.mul( positionNode );
  7575. } else {
  7576. const rotation = rotationNode;
  7577. 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 ) );
  7578. 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 ) );
  7579. 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 ) );
  7580. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  7581. }
  7582. }
  7583. }
  7584. const rotate = /*@__PURE__*/ nodeProxy( RotateNode );
  7585. const _defaultValues$1 = /*@__PURE__*/ new SpriteMaterial();
  7586. class SpriteNodeMaterial extends NodeMaterial {
  7587. static get type() {
  7588. return 'SpriteNodeMaterial';
  7589. }
  7590. constructor( parameters ) {
  7591. super();
  7592. this.isSpriteNodeMaterial = true;
  7593. this.lights = false;
  7594. this._useSizeAttenuation = true;
  7595. this.positionNode = null;
  7596. this.rotationNode = null;
  7597. this.scaleNode = null;
  7598. this.setDefaultValues( _defaultValues$1 );
  7599. this.setValues( parameters );
  7600. }
  7601. setupPosition( { object, camera, context } ) {
  7602. const sizeAttenuation = this.sizeAttenuation;
  7603. // < VERTEX STAGE >
  7604. const { positionNode, rotationNode, scaleNode } = this;
  7605. const vertex = positionLocal;
  7606. let mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  7607. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  7608. if ( scaleNode !== null ) {
  7609. scale = scale.mul( scaleNode );
  7610. }
  7611. if ( ! sizeAttenuation ) {
  7612. if ( camera.isPerspectiveCamera ) {
  7613. scale = scale.mul( mvPosition.z.negate() );
  7614. } else {
  7615. const orthoScale = float( 2.0 ).div( cameraProjectionMatrix.element( 1 ).element( 1 ) );
  7616. scale = scale.mul( orthoScale.mul( 2 ) );
  7617. }
  7618. }
  7619. let alignedPosition = vertex.xy;
  7620. if ( object.center && object.center.isVector2 === true ) {
  7621. const center = reference$1( 'center', 'vec2' );
  7622. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  7623. }
  7624. alignedPosition = alignedPosition.mul( scale );
  7625. const rotation = float( rotationNode || materialRotation );
  7626. const rotatedPosition = rotate( alignedPosition, rotation );
  7627. mvPosition = vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  7628. const modelViewProjection = cameraProjectionMatrix.mul( mvPosition );
  7629. context.vertex = vertex;
  7630. return modelViewProjection;
  7631. }
  7632. copy( source ) {
  7633. this.positionNode = source.positionNode;
  7634. this.rotationNode = source.rotationNode;
  7635. this.scaleNode = source.scaleNode;
  7636. return super.copy( source );
  7637. }
  7638. get sizeAttenuation() {
  7639. return this._useSizeAttenuation;
  7640. }
  7641. set sizeAttenuation( value ) {
  7642. if ( this._useSizeAttenuation !== value ) {
  7643. this._useSizeAttenuation = value;
  7644. this.needsUpdate = true;
  7645. }
  7646. }
  7647. }
  7648. class ShadowMaskModel extends LightingModel {
  7649. constructor() {
  7650. super();
  7651. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  7652. }
  7653. direct( { shadowMask } ) {
  7654. this.shadowNode.mulAssign( shadowMask );
  7655. }
  7656. finish( context ) {
  7657. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  7658. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  7659. }
  7660. }
  7661. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  7662. class ShadowNodeMaterial extends NodeMaterial {
  7663. static get type() {
  7664. return 'ShadowNodeMaterial';
  7665. }
  7666. constructor( parameters ) {
  7667. super();
  7668. this.isShadowNodeMaterial = true;
  7669. this.lights = true;
  7670. this.setDefaultValues( _defaultValues );
  7671. this.setValues( parameters );
  7672. }
  7673. setupLightingModel( /*builder*/ ) {
  7674. return new ShadowMaskModel();
  7675. }
  7676. }
  7677. const normal = Fn( ( { texture, uv } ) => {
  7678. const epsilon = 0.0001;
  7679. const ret = vec3().toVar();
  7680. If( uv.x.lessThan( epsilon ), () => {
  7681. ret.assign( vec3( 1, 0, 0 ) );
  7682. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  7683. ret.assign( vec3( 0, 1, 0 ) );
  7684. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  7685. ret.assign( vec3( 0, 0, 1 ) );
  7686. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  7687. ret.assign( vec3( - 1, 0, 0 ) );
  7688. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  7689. ret.assign( vec3( 0, - 1, 0 ) );
  7690. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  7691. ret.assign( vec3( 0, 0, - 1 ) );
  7692. } ).Else( () => {
  7693. const step = 0.01;
  7694. const x = texture.uv( uv.add( vec3( - step, 0.0, 0.0 ) ) ).r.sub( texture.uv( uv.add( vec3( step, 0.0, 0.0 ) ) ).r );
  7695. const y = texture.uv( uv.add( vec3( 0.0, - step, 0.0 ) ) ).r.sub( texture.uv( uv.add( vec3( 0.0, step, 0.0 ) ) ).r );
  7696. const z = texture.uv( uv.add( vec3( 0.0, 0.0, - step ) ) ).r.sub( texture.uv( uv.add( vec3( 0.0, 0.0, step ) ) ).r );
  7697. ret.assign( vec3( x, y, z ) );
  7698. } );
  7699. return ret.normalize();
  7700. } );
  7701. class Texture3DNode extends TextureNode {
  7702. static get type() {
  7703. return 'Texture3DNode';
  7704. }
  7705. constructor( value, uvNode = null, levelNode = null ) {
  7706. super( value, uvNode, levelNode );
  7707. this.isTexture3DNode = true;
  7708. }
  7709. getInputType( /*builder*/ ) {
  7710. return 'texture3D';
  7711. }
  7712. getDefaultUV() {
  7713. return vec3( 0.5, 0.5, 0.5 );
  7714. }
  7715. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  7716. setupUV( builder, uvNode ) {
  7717. return uvNode;
  7718. }
  7719. generateUV( builder, uvNode ) {
  7720. return uvNode.build( builder, 'vec3' );
  7721. }
  7722. normal( uvNode ) {
  7723. return normal( { texture: this, uv: uvNode } );
  7724. }
  7725. }
  7726. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode );
  7727. class VolumeNodeMaterial extends NodeMaterial {
  7728. static get type() {
  7729. return 'VolumeNodeMaterial';
  7730. }
  7731. constructor( params = {} ) {
  7732. super();
  7733. this.lights = false;
  7734. this.isVolumeNodeMaterial = true;
  7735. this.testNode = null;
  7736. this.setValues( params );
  7737. }
  7738. setup( builder ) {
  7739. const map = texture3D( this.map, null, 0 );
  7740. const hitBox = Fn( ( { orig, dir } ) => {
  7741. const box_min = vec3( - 0.5 );
  7742. const box_max = vec3( 0.5 );
  7743. const inv_dir = dir.reciprocal();
  7744. const tmin_tmp = box_min.sub( orig ).mul( inv_dir );
  7745. const tmax_tmp = box_max.sub( orig ).mul( inv_dir );
  7746. const tmin = min$1( tmin_tmp, tmax_tmp );
  7747. const tmax = max$1( tmin_tmp, tmax_tmp );
  7748. const t0 = max$1( tmin.x, max$1( tmin.y, tmin.z ) );
  7749. const t1 = min$1( tmax.x, min$1( tmax.y, tmax.z ) );
  7750. return vec2( t0, t1 );
  7751. } );
  7752. this.fragmentNode = Fn( () => {
  7753. const vOrigin = varying( vec3( modelWorldMatrixInverse.mul( vec4( cameraPosition, 1.0 ) ) ) );
  7754. const vDirection = varying( positionGeometry.sub( vOrigin ) );
  7755. const rayDir = vDirection.normalize();
  7756. const bounds = vec2( hitBox( { orig: vOrigin, dir: rayDir } ) ).toVar();
  7757. bounds.x.greaterThan( bounds.y ).discard();
  7758. bounds.assign( vec2( max$1( bounds.x, 0.0 ), bounds.y ) );
  7759. const p = vec3( vOrigin.add( bounds.x.mul( rayDir ) ) ).toVar();
  7760. const inc = vec3( rayDir.abs().reciprocal() ).toVar();
  7761. const delta = float( min$1( inc.x, min$1( inc.y, inc.z ) ) ).toVar( 'delta' ); // used 'delta' name in loop
  7762. delta.divAssign( materialReference( 'steps', 'float' ) );
  7763. const ac = vec4( materialReference( 'base', 'color' ), 0.0 ).toVar();
  7764. Loop( { type: 'float', start: bounds.x, end: bounds.y, update: '+= delta' }, () => {
  7765. const d = property( 'float', 'd' ).assign( map.uv( p.add( 0.5 ) ).r );
  7766. if ( this.testNode !== null ) {
  7767. this.testNode( { map: map, mapValue: d, probe: p, finalColor: ac } ).append();
  7768. } else {
  7769. // default to show surface of mesh
  7770. ac.a.assign( 1 );
  7771. Break();
  7772. }
  7773. p.addAssign( rayDir.mul( delta ) );
  7774. } );
  7775. ac.a.equal( 0 ).discard();
  7776. return vec4( ac );
  7777. } )();
  7778. super.setup( builder );
  7779. }
  7780. }
  7781. class Animation {
  7782. constructor( nodes, info ) {
  7783. this.nodes = nodes;
  7784. this.info = info;
  7785. this._context = self;
  7786. this._animationLoop = null;
  7787. this._requestId = null;
  7788. }
  7789. start() {
  7790. const update = ( time, frame ) => {
  7791. this._requestId = this._context.requestAnimationFrame( update );
  7792. if ( this.info.autoReset === true ) this.info.reset();
  7793. this.nodes.nodeFrame.update();
  7794. this.info.frame = this.nodes.nodeFrame.frameId;
  7795. if ( this._animationLoop !== null ) this._animationLoop( time, frame );
  7796. };
  7797. update();
  7798. }
  7799. stop() {
  7800. this._context.cancelAnimationFrame( this._requestId );
  7801. this._requestId = null;
  7802. }
  7803. setAnimationLoop( callback ) {
  7804. this._animationLoop = callback;
  7805. }
  7806. setContext( context ) {
  7807. this._context = context;
  7808. }
  7809. dispose() {
  7810. this.stop();
  7811. }
  7812. }
  7813. class ChainMap {
  7814. constructor() {
  7815. this.weakMap = new WeakMap();
  7816. }
  7817. get( keys ) {
  7818. let map = this.weakMap;
  7819. for ( let i = 0; i < keys.length; i ++ ) {
  7820. map = map.get( keys[ i ] );
  7821. if ( map === undefined ) return undefined;
  7822. }
  7823. return map.get( keys[ keys.length - 1 ] );
  7824. }
  7825. set( keys, value ) {
  7826. let map = this.weakMap;
  7827. for ( let i = 0; i < keys.length; i ++ ) {
  7828. const key = keys[ i ];
  7829. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  7830. map = map.get( key );
  7831. }
  7832. return map.set( keys[ keys.length - 1 ], value );
  7833. }
  7834. delete( keys ) {
  7835. let map = this.weakMap;
  7836. for ( let i = 0; i < keys.length; i ++ ) {
  7837. map = map.get( keys[ i ] );
  7838. if ( map === undefined ) return false;
  7839. }
  7840. return map.delete( keys[ keys.length - 1 ] );
  7841. }
  7842. }
  7843. let _id$7 = 0;
  7844. function getKeys( obj ) {
  7845. const keys = Object.keys( obj );
  7846. let proto = Object.getPrototypeOf( obj );
  7847. while ( proto ) {
  7848. const descriptors = Object.getOwnPropertyDescriptors( proto );
  7849. for ( const key in descriptors ) {
  7850. if ( descriptors[ key ] !== undefined ) {
  7851. const descriptor = descriptors[ key ];
  7852. if ( descriptor && typeof descriptor.get === 'function' ) {
  7853. keys.push( key );
  7854. }
  7855. }
  7856. }
  7857. proto = Object.getPrototypeOf( proto );
  7858. }
  7859. return keys;
  7860. }
  7861. class RenderObject {
  7862. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  7863. this._nodes = nodes;
  7864. this._geometries = geometries;
  7865. this.id = _id$7 ++;
  7866. this.renderer = renderer;
  7867. this.object = object;
  7868. this.material = material;
  7869. this.scene = scene;
  7870. this.camera = camera;
  7871. this.lightsNode = lightsNode;
  7872. this.context = renderContext;
  7873. this.geometry = object.geometry;
  7874. this.version = material.version;
  7875. this.drawRange = null;
  7876. this.attributes = null;
  7877. this.pipeline = null;
  7878. this.vertexBuffers = null;
  7879. this.drawParams = null;
  7880. this.bundle = null;
  7881. this.clippingContext = clippingContext;
  7882. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  7883. this.initialNodesCacheKey = this.getDynamicCacheKey();
  7884. this.initialCacheKey = this.getCacheKey();
  7885. this._nodeBuilderState = null;
  7886. this._bindings = null;
  7887. this._monitor = null;
  7888. this.onDispose = null;
  7889. this.isRenderObject = true;
  7890. this.onMaterialDispose = () => {
  7891. this.dispose();
  7892. };
  7893. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  7894. }
  7895. updateClipping( parent ) {
  7896. this.clippingContext = parent;
  7897. }
  7898. get clippingNeedsUpdate() {
  7899. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  7900. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  7901. return true;
  7902. }
  7903. get hardwareClippingPlanes() {
  7904. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  7905. }
  7906. getNodeBuilderState() {
  7907. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  7908. }
  7909. getMonitor() {
  7910. return this._monitor || ( this._monitor = this.getNodeBuilderState().monitor );
  7911. }
  7912. getBindings() {
  7913. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  7914. }
  7915. getIndex() {
  7916. return this._geometries.getIndex( this );
  7917. }
  7918. getIndirect() {
  7919. return this._geometries.getIndirect( this );
  7920. }
  7921. getChainArray() {
  7922. return [ this.object, this.material, this.context, this.lightsNode ];
  7923. }
  7924. setGeometry( geometry ) {
  7925. this.geometry = geometry;
  7926. this.attributes = null;
  7927. }
  7928. getAttributes() {
  7929. if ( this.attributes !== null ) return this.attributes;
  7930. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  7931. const geometry = this.geometry;
  7932. const attributes = [];
  7933. const vertexBuffers = new Set();
  7934. for ( const nodeAttribute of nodeAttributes ) {
  7935. const attribute = nodeAttribute.node && nodeAttribute.node.attribute ? nodeAttribute.node.attribute : geometry.getAttribute( nodeAttribute.name );
  7936. if ( attribute === undefined ) continue;
  7937. attributes.push( attribute );
  7938. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  7939. vertexBuffers.add( bufferAttribute );
  7940. }
  7941. this.attributes = attributes;
  7942. this.vertexBuffers = Array.from( vertexBuffers.values() );
  7943. return attributes;
  7944. }
  7945. getVertexBuffers() {
  7946. if ( this.vertexBuffers === null ) this.getAttributes();
  7947. return this.vertexBuffers;
  7948. }
  7949. getDrawParameters() {
  7950. const { object, material, geometry, group, drawRange } = this;
  7951. const drawParams = this.drawParams || ( this.drawParams = {
  7952. vertexCount: 0,
  7953. firstVertex: 0,
  7954. instanceCount: 0,
  7955. firstInstance: 0
  7956. } );
  7957. const index = this.getIndex();
  7958. const hasIndex = ( index !== null );
  7959. const instanceCount = geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  7960. if ( instanceCount === 0 ) return null;
  7961. drawParams.instanceCount = instanceCount;
  7962. if ( object.isBatchedMesh === true ) return drawParams;
  7963. let rangeFactor = 1;
  7964. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  7965. rangeFactor = 2;
  7966. }
  7967. let firstVertex = drawRange.start * rangeFactor;
  7968. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  7969. if ( group !== null ) {
  7970. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  7971. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  7972. }
  7973. const position = geometry.attributes.position;
  7974. let itemCount = Infinity;
  7975. if ( hasIndex ) {
  7976. itemCount = index.count;
  7977. } else if ( position !== undefined && position !== null ) {
  7978. itemCount = position.count;
  7979. }
  7980. firstVertex = Math.max( firstVertex, 0 );
  7981. lastVertex = Math.min( lastVertex, itemCount );
  7982. const count = lastVertex - firstVertex;
  7983. if ( count < 0 || count === Infinity ) return null;
  7984. drawParams.vertexCount = count;
  7985. drawParams.firstVertex = firstVertex;
  7986. return drawParams;
  7987. }
  7988. getGeometryCacheKey() {
  7989. const { geometry } = this;
  7990. let cacheKey = '';
  7991. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  7992. const attribute = geometry.attributes[ name ];
  7993. cacheKey += name + ',';
  7994. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  7995. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  7996. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  7997. if ( attribute.normalized ) cacheKey += 'n,';
  7998. }
  7999. if ( geometry.index ) {
  8000. cacheKey += 'index,';
  8001. }
  8002. return cacheKey;
  8003. }
  8004. getMaterialCacheKey() {
  8005. const { object, material } = this;
  8006. let cacheKey = material.customProgramCacheKey();
  8007. for ( const property of getKeys( material ) ) {
  8008. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  8009. const value = material[ property ];
  8010. let valueKey;
  8011. if ( value !== null ) {
  8012. // some material values require a formatting
  8013. const type = typeof value;
  8014. if ( type === 'number' ) {
  8015. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  8016. } else if ( type === 'object' ) {
  8017. valueKey = '{';
  8018. if ( value.isTexture ) {
  8019. valueKey += value.mapping;
  8020. }
  8021. valueKey += '}';
  8022. } else {
  8023. valueKey = String( value );
  8024. }
  8025. } else {
  8026. valueKey = String( value );
  8027. }
  8028. cacheKey += /*property + ':' +*/ valueKey + ',';
  8029. }
  8030. cacheKey += this.clippingContextCacheKey + ',';
  8031. if ( object.geometry ) {
  8032. cacheKey += this.getGeometryCacheKey();
  8033. }
  8034. if ( object.skeleton ) {
  8035. cacheKey += object.skeleton.bones.length + ',';
  8036. }
  8037. if ( object.morphTargetInfluences ) {
  8038. cacheKey += object.morphTargetInfluences.length + ',';
  8039. }
  8040. if ( object.isBatchedMesh ) {
  8041. cacheKey += object._matricesTexture.uuid + ',';
  8042. if ( object._colorsTexture !== null ) {
  8043. cacheKey += object._colorsTexture.uuid + ',';
  8044. }
  8045. }
  8046. if ( object.count > 1 ) {
  8047. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  8048. cacheKey += object.uuid + ',';
  8049. }
  8050. cacheKey += object.receiveShadow + ',';
  8051. return hashString( cacheKey );
  8052. }
  8053. get needsGeometryUpdate() {
  8054. return this.geometry.id !== this.object.geometry.id;
  8055. }
  8056. get needsUpdate() {
  8057. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  8058. }
  8059. getDynamicCacheKey() {
  8060. // Environment Nodes Cache Key
  8061. let cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  8062. if ( this.object.receiveShadow ) {
  8063. cacheKey += 1;
  8064. }
  8065. return cacheKey;
  8066. }
  8067. getCacheKey() {
  8068. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  8069. }
  8070. dispose() {
  8071. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  8072. this.onDispose();
  8073. }
  8074. }
  8075. const chainArray = [];
  8076. class RenderObjects {
  8077. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  8078. this.renderer = renderer;
  8079. this.nodes = nodes;
  8080. this.geometries = geometries;
  8081. this.pipelines = pipelines;
  8082. this.bindings = bindings;
  8083. this.info = info;
  8084. this.chainMaps = {};
  8085. }
  8086. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  8087. const chainMap = this.getChainMap( passId );
  8088. // reuse chainArray
  8089. chainArray[ 0 ] = object;
  8090. chainArray[ 1 ] = material;
  8091. chainArray[ 2 ] = renderContext;
  8092. chainArray[ 3 ] = lightsNode;
  8093. let renderObject = chainMap.get( chainArray );
  8094. if ( renderObject === undefined ) {
  8095. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  8096. chainMap.set( chainArray, renderObject );
  8097. } else {
  8098. renderObject.updateClipping( clippingContext );
  8099. if ( renderObject.needsGeometryUpdate ) {
  8100. renderObject.setGeometry( object.geometry );
  8101. }
  8102. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  8103. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  8104. renderObject.dispose();
  8105. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  8106. } else {
  8107. renderObject.version = material.version;
  8108. }
  8109. }
  8110. }
  8111. return renderObject;
  8112. }
  8113. getChainMap( passId = 'default' ) {
  8114. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  8115. }
  8116. dispose() {
  8117. this.chainMaps = {};
  8118. }
  8119. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  8120. const chainMap = this.getChainMap( passId );
  8121. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  8122. renderObject.onDispose = () => {
  8123. this.pipelines.delete( renderObject );
  8124. this.bindings.delete( renderObject );
  8125. this.nodes.delete( renderObject );
  8126. chainMap.delete( renderObject.getChainArray() );
  8127. };
  8128. return renderObject;
  8129. }
  8130. }
  8131. class DataMap {
  8132. constructor() {
  8133. this.data = new WeakMap();
  8134. }
  8135. get( object ) {
  8136. let map = this.data.get( object );
  8137. if ( map === undefined ) {
  8138. map = {};
  8139. this.data.set( object, map );
  8140. }
  8141. return map;
  8142. }
  8143. delete( object ) {
  8144. let map;
  8145. if ( this.data.has( object ) ) {
  8146. map = this.data.get( object );
  8147. this.data.delete( object );
  8148. }
  8149. return map;
  8150. }
  8151. has( object ) {
  8152. return this.data.has( object );
  8153. }
  8154. dispose() {
  8155. this.data = new WeakMap();
  8156. }
  8157. }
  8158. const AttributeType = {
  8159. VERTEX: 1,
  8160. INDEX: 2,
  8161. STORAGE: 3,
  8162. INDIRECT: 4
  8163. };
  8164. // size of a chunk in bytes (STD140 layout)
  8165. const GPU_CHUNK_BYTES = 16;
  8166. // @TODO: Move to src/constants.js
  8167. const BlendColorFactor = 211;
  8168. const OneMinusBlendColorFactor = 212;
  8169. class Attributes extends DataMap {
  8170. constructor( backend ) {
  8171. super();
  8172. this.backend = backend;
  8173. }
  8174. delete( attribute ) {
  8175. const attributeData = super.delete( attribute );
  8176. if ( attributeData !== undefined ) {
  8177. this.backend.destroyAttribute( attribute );
  8178. }
  8179. return attributeData;
  8180. }
  8181. update( attribute, type ) {
  8182. const data = this.get( attribute );
  8183. if ( data.version === undefined ) {
  8184. if ( type === AttributeType.VERTEX ) {
  8185. this.backend.createAttribute( attribute );
  8186. } else if ( type === AttributeType.INDEX ) {
  8187. this.backend.createIndexAttribute( attribute );
  8188. } else if ( type === AttributeType.STORAGE ) {
  8189. this.backend.createStorageAttribute( attribute );
  8190. } else if ( type === AttributeType.INDIRECT ) {
  8191. this.backend.createIndirectStorageAttribute( attribute );
  8192. }
  8193. data.version = this._getBufferAttribute( attribute ).version;
  8194. } else {
  8195. const bufferAttribute = this._getBufferAttribute( attribute );
  8196. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  8197. this.backend.updateAttribute( attribute );
  8198. data.version = bufferAttribute.version;
  8199. }
  8200. }
  8201. }
  8202. _getBufferAttribute( attribute ) {
  8203. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8204. return attribute;
  8205. }
  8206. }
  8207. function arrayNeedsUint32( array ) {
  8208. // assumes larger values usually on last
  8209. for ( let i = array.length - 1; i >= 0; -- i ) {
  8210. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  8211. }
  8212. return false;
  8213. }
  8214. function getWireframeVersion( geometry ) {
  8215. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  8216. }
  8217. function getWireframeIndex( geometry ) {
  8218. const indices = [];
  8219. const geometryIndex = geometry.index;
  8220. const geometryPosition = geometry.attributes.position;
  8221. if ( geometryIndex !== null ) {
  8222. const array = geometryIndex.array;
  8223. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  8224. const a = array[ i + 0 ];
  8225. const b = array[ i + 1 ];
  8226. const c = array[ i + 2 ];
  8227. indices.push( a, b, b, c, c, a );
  8228. }
  8229. } else {
  8230. const array = geometryPosition.array;
  8231. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  8232. const a = i + 0;
  8233. const b = i + 1;
  8234. const c = i + 2;
  8235. indices.push( a, b, b, c, c, a );
  8236. }
  8237. }
  8238. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  8239. attribute.version = getWireframeVersion( geometry );
  8240. return attribute;
  8241. }
  8242. class Geometries extends DataMap {
  8243. constructor( attributes, info ) {
  8244. super();
  8245. this.attributes = attributes;
  8246. this.info = info;
  8247. this.wireframes = new WeakMap();
  8248. this.attributeCall = new WeakMap();
  8249. }
  8250. has( renderObject ) {
  8251. const geometry = renderObject.geometry;
  8252. return super.has( geometry ) && this.get( geometry ).initialized === true;
  8253. }
  8254. updateForRender( renderObject ) {
  8255. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  8256. this.updateAttributes( renderObject );
  8257. }
  8258. initGeometry( renderObject ) {
  8259. const geometry = renderObject.geometry;
  8260. const geometryData = this.get( geometry );
  8261. geometryData.initialized = true;
  8262. this.info.memory.geometries ++;
  8263. const onDispose = () => {
  8264. this.info.memory.geometries --;
  8265. const index = geometry.index;
  8266. const geometryAttributes = renderObject.getAttributes();
  8267. if ( index !== null ) {
  8268. this.attributes.delete( index );
  8269. }
  8270. for ( const geometryAttribute of geometryAttributes ) {
  8271. this.attributes.delete( geometryAttribute );
  8272. }
  8273. const wireframeAttribute = this.wireframes.get( geometry );
  8274. if ( wireframeAttribute !== undefined ) {
  8275. this.attributes.delete( wireframeAttribute );
  8276. }
  8277. geometry.removeEventListener( 'dispose', onDispose );
  8278. };
  8279. geometry.addEventListener( 'dispose', onDispose );
  8280. }
  8281. updateAttributes( renderObject ) {
  8282. // attributes
  8283. const attributes = renderObject.getAttributes();
  8284. for ( const attribute of attributes ) {
  8285. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  8286. this.updateAttribute( attribute, AttributeType.STORAGE );
  8287. } else {
  8288. this.updateAttribute( attribute, AttributeType.VERTEX );
  8289. }
  8290. }
  8291. // indexes
  8292. const index = this.getIndex( renderObject );
  8293. if ( index !== null ) {
  8294. this.updateAttribute( index, AttributeType.INDEX );
  8295. }
  8296. // indirect
  8297. const indirect = renderObject.geometry.indirect;
  8298. if ( indirect !== null ) {
  8299. this.updateAttribute( indirect, AttributeType.INDIRECT );
  8300. }
  8301. }
  8302. updateAttribute( attribute, type ) {
  8303. const callId = this.info.render.calls;
  8304. if ( ! attribute.isInterleavedBufferAttribute ) {
  8305. if ( this.attributeCall.get( attribute ) !== callId ) {
  8306. this.attributes.update( attribute, type );
  8307. this.attributeCall.set( attribute, callId );
  8308. }
  8309. } else {
  8310. if ( this.attributeCall.get( attribute ) === undefined ) {
  8311. this.attributes.update( attribute, type );
  8312. this.attributeCall.set( attribute, callId );
  8313. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  8314. this.attributes.update( attribute, type );
  8315. this.attributeCall.set( attribute.data, callId );
  8316. this.attributeCall.set( attribute, callId );
  8317. }
  8318. }
  8319. }
  8320. getIndirect( renderObject ) {
  8321. return renderObject.geometry.indirect;
  8322. }
  8323. getIndex( renderObject ) {
  8324. const { geometry, material } = renderObject;
  8325. let index = geometry.index;
  8326. if ( material.wireframe === true ) {
  8327. const wireframes = this.wireframes;
  8328. let wireframeAttribute = wireframes.get( geometry );
  8329. if ( wireframeAttribute === undefined ) {
  8330. wireframeAttribute = getWireframeIndex( geometry );
  8331. wireframes.set( geometry, wireframeAttribute );
  8332. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  8333. this.attributes.delete( wireframeAttribute );
  8334. wireframeAttribute = getWireframeIndex( geometry );
  8335. wireframes.set( geometry, wireframeAttribute );
  8336. }
  8337. index = wireframeAttribute;
  8338. }
  8339. return index;
  8340. }
  8341. }
  8342. class Info {
  8343. constructor() {
  8344. this.autoReset = true;
  8345. this.frame = 0;
  8346. this.calls = 0;
  8347. this.render = {
  8348. calls: 0,
  8349. frameCalls: 0,
  8350. drawCalls: 0,
  8351. triangles: 0,
  8352. points: 0,
  8353. lines: 0,
  8354. timestamp: 0,
  8355. previousFrameCalls: 0,
  8356. timestampCalls: 0
  8357. };
  8358. this.compute = {
  8359. calls: 0,
  8360. frameCalls: 0,
  8361. timestamp: 0,
  8362. previousFrameCalls: 0,
  8363. timestampCalls: 0
  8364. };
  8365. this.memory = {
  8366. geometries: 0,
  8367. textures: 0
  8368. };
  8369. }
  8370. update( object, count, instanceCount ) {
  8371. this.render.drawCalls ++;
  8372. if ( object.isMesh || object.isSprite ) {
  8373. this.render.triangles += instanceCount * ( count / 3 );
  8374. } else if ( object.isPoints ) {
  8375. this.render.points += instanceCount * count;
  8376. } else if ( object.isLineSegments ) {
  8377. this.render.lines += instanceCount * ( count / 2 );
  8378. } else if ( object.isLine ) {
  8379. this.render.lines += instanceCount * ( count - 1 );
  8380. } else {
  8381. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  8382. }
  8383. }
  8384. updateTimestamp( type, time ) {
  8385. if ( this[ type ].timestampCalls === 0 ) {
  8386. this[ type ].timestamp = 0;
  8387. }
  8388. this[ type ].timestamp += time;
  8389. this[ type ].timestampCalls ++;
  8390. if ( this[ type ].timestampCalls >= this[ type ].previousFrameCalls ) {
  8391. this[ type ].timestampCalls = 0;
  8392. }
  8393. }
  8394. reset() {
  8395. const previousRenderFrameCalls = this.render.frameCalls;
  8396. this.render.previousFrameCalls = previousRenderFrameCalls;
  8397. const previousComputeFrameCalls = this.compute.frameCalls;
  8398. this.compute.previousFrameCalls = previousComputeFrameCalls;
  8399. this.render.drawCalls = 0;
  8400. this.render.frameCalls = 0;
  8401. this.compute.frameCalls = 0;
  8402. this.render.triangles = 0;
  8403. this.render.points = 0;
  8404. this.render.lines = 0;
  8405. }
  8406. dispose() {
  8407. this.reset();
  8408. this.calls = 0;
  8409. this.render.calls = 0;
  8410. this.compute.calls = 0;
  8411. this.render.timestamp = 0;
  8412. this.compute.timestamp = 0;
  8413. this.memory.geometries = 0;
  8414. this.memory.textures = 0;
  8415. }
  8416. }
  8417. class Pipeline {
  8418. constructor( cacheKey ) {
  8419. this.cacheKey = cacheKey;
  8420. this.usedTimes = 0;
  8421. }
  8422. }
  8423. class RenderPipeline extends Pipeline {
  8424. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  8425. super( cacheKey );
  8426. this.vertexProgram = vertexProgram;
  8427. this.fragmentProgram = fragmentProgram;
  8428. }
  8429. }
  8430. class ComputePipeline extends Pipeline {
  8431. constructor( cacheKey, computeProgram ) {
  8432. super( cacheKey );
  8433. this.computeProgram = computeProgram;
  8434. this.isComputePipeline = true;
  8435. }
  8436. }
  8437. let _id$6 = 0;
  8438. class ProgrammableStage {
  8439. constructor( code, type, transforms = null, attributes = null ) {
  8440. this.id = _id$6 ++;
  8441. this.code = code;
  8442. this.stage = type;
  8443. this.transforms = transforms;
  8444. this.attributes = attributes;
  8445. this.usedTimes = 0;
  8446. }
  8447. }
  8448. class Pipelines extends DataMap {
  8449. constructor( backend, nodes ) {
  8450. super();
  8451. this.backend = backend;
  8452. this.nodes = nodes;
  8453. this.bindings = null; // set by the bindings
  8454. this.caches = new Map();
  8455. this.programs = {
  8456. vertex: new Map(),
  8457. fragment: new Map(),
  8458. compute: new Map()
  8459. };
  8460. }
  8461. getForCompute( computeNode, bindings ) {
  8462. const { backend } = this;
  8463. const data = this.get( computeNode );
  8464. if ( this._needsComputeUpdate( computeNode ) ) {
  8465. const previousPipeline = data.pipeline;
  8466. if ( previousPipeline ) {
  8467. previousPipeline.usedTimes --;
  8468. previousPipeline.computeProgram.usedTimes --;
  8469. }
  8470. // get shader
  8471. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  8472. // programmable stage
  8473. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  8474. if ( stageCompute === undefined ) {
  8475. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  8476. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  8477. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  8478. backend.createProgram( stageCompute );
  8479. }
  8480. // determine compute pipeline
  8481. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  8482. let pipeline = this.caches.get( cacheKey );
  8483. if ( pipeline === undefined ) {
  8484. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  8485. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  8486. }
  8487. // keep track of all used times
  8488. pipeline.usedTimes ++;
  8489. stageCompute.usedTimes ++;
  8490. //
  8491. data.version = computeNode.version;
  8492. data.pipeline = pipeline;
  8493. }
  8494. return data.pipeline;
  8495. }
  8496. getForRender( renderObject, promises = null ) {
  8497. const { backend } = this;
  8498. const data = this.get( renderObject );
  8499. if ( this._needsRenderUpdate( renderObject ) ) {
  8500. const previousPipeline = data.pipeline;
  8501. if ( previousPipeline ) {
  8502. previousPipeline.usedTimes --;
  8503. previousPipeline.vertexProgram.usedTimes --;
  8504. previousPipeline.fragmentProgram.usedTimes --;
  8505. }
  8506. // get shader
  8507. const nodeBuilderState = renderObject.getNodeBuilderState();
  8508. // programmable stages
  8509. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  8510. if ( stageVertex === undefined ) {
  8511. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  8512. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex' );
  8513. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  8514. backend.createProgram( stageVertex );
  8515. }
  8516. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  8517. if ( stageFragment === undefined ) {
  8518. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  8519. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment' );
  8520. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  8521. backend.createProgram( stageFragment );
  8522. }
  8523. // determine render pipeline
  8524. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  8525. let pipeline = this.caches.get( cacheKey );
  8526. if ( pipeline === undefined ) {
  8527. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  8528. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  8529. } else {
  8530. renderObject.pipeline = pipeline;
  8531. }
  8532. // keep track of all used times
  8533. pipeline.usedTimes ++;
  8534. stageVertex.usedTimes ++;
  8535. stageFragment.usedTimes ++;
  8536. //
  8537. data.pipeline = pipeline;
  8538. }
  8539. return data.pipeline;
  8540. }
  8541. delete( object ) {
  8542. const pipeline = this.get( object ).pipeline;
  8543. if ( pipeline ) {
  8544. // pipeline
  8545. pipeline.usedTimes --;
  8546. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  8547. // programs
  8548. if ( pipeline.isComputePipeline ) {
  8549. pipeline.computeProgram.usedTimes --;
  8550. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  8551. } else {
  8552. pipeline.fragmentProgram.usedTimes --;
  8553. pipeline.vertexProgram.usedTimes --;
  8554. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  8555. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  8556. }
  8557. }
  8558. return super.delete( object );
  8559. }
  8560. dispose() {
  8561. super.dispose();
  8562. this.caches = new Map();
  8563. this.programs = {
  8564. vertex: new Map(),
  8565. fragment: new Map(),
  8566. compute: new Map()
  8567. };
  8568. }
  8569. updateForRender( renderObject ) {
  8570. this.getForRender( renderObject );
  8571. }
  8572. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  8573. // check for existing pipeline
  8574. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  8575. let pipeline = this.caches.get( cacheKey );
  8576. if ( pipeline === undefined ) {
  8577. pipeline = new ComputePipeline( cacheKey, stageCompute );
  8578. this.caches.set( cacheKey, pipeline );
  8579. this.backend.createComputePipeline( pipeline, bindings );
  8580. }
  8581. return pipeline;
  8582. }
  8583. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  8584. // check for existing pipeline
  8585. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  8586. let pipeline = this.caches.get( cacheKey );
  8587. if ( pipeline === undefined ) {
  8588. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  8589. this.caches.set( cacheKey, pipeline );
  8590. renderObject.pipeline = pipeline;
  8591. this.backend.createRenderPipeline( renderObject, promises );
  8592. }
  8593. return pipeline;
  8594. }
  8595. _getComputeCacheKey( computeNode, stageCompute ) {
  8596. return computeNode.id + ',' + stageCompute.id;
  8597. }
  8598. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  8599. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  8600. }
  8601. _releasePipeline( pipeline ) {
  8602. this.caches.delete( pipeline.cacheKey );
  8603. }
  8604. _releaseProgram( program ) {
  8605. const code = program.code;
  8606. const stage = program.stage;
  8607. this.programs[ stage ].delete( code );
  8608. }
  8609. _needsComputeUpdate( computeNode ) {
  8610. const data = this.get( computeNode );
  8611. return data.pipeline === undefined || data.version !== computeNode.version;
  8612. }
  8613. _needsRenderUpdate( renderObject ) {
  8614. const data = this.get( renderObject );
  8615. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  8616. }
  8617. }
  8618. class Bindings extends DataMap {
  8619. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  8620. super();
  8621. this.backend = backend;
  8622. this.textures = textures;
  8623. this.pipelines = pipelines;
  8624. this.attributes = attributes;
  8625. this.nodes = nodes;
  8626. this.info = info;
  8627. this.pipelines.bindings = this; // assign bindings to pipelines
  8628. }
  8629. getForRender( renderObject ) {
  8630. const bindings = renderObject.getBindings();
  8631. for ( const bindGroup of bindings ) {
  8632. const groupData = this.get( bindGroup );
  8633. if ( groupData.bindGroup === undefined ) {
  8634. // each object defines an array of bindings (ubos, textures, samplers etc.)
  8635. this._init( bindGroup );
  8636. this.backend.createBindings( bindGroup, bindings, 0 );
  8637. groupData.bindGroup = bindGroup;
  8638. }
  8639. }
  8640. return bindings;
  8641. }
  8642. getForCompute( computeNode ) {
  8643. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  8644. for ( const bindGroup of bindings ) {
  8645. const groupData = this.get( bindGroup );
  8646. if ( groupData.bindGroup === undefined ) {
  8647. this._init( bindGroup );
  8648. this.backend.createBindings( bindGroup, bindings, 0 );
  8649. groupData.bindGroup = bindGroup;
  8650. }
  8651. }
  8652. return bindings;
  8653. }
  8654. updateForCompute( computeNode ) {
  8655. this._updateBindings( this.getForCompute( computeNode ) );
  8656. }
  8657. updateForRender( renderObject ) {
  8658. this._updateBindings( this.getForRender( renderObject ) );
  8659. }
  8660. _updateBindings( bindings ) {
  8661. for ( const bindGroup of bindings ) {
  8662. this._update( bindGroup, bindings );
  8663. }
  8664. }
  8665. _init( bindGroup ) {
  8666. for ( const binding of bindGroup.bindings ) {
  8667. if ( binding.isSampledTexture ) {
  8668. this.textures.updateTexture( binding.texture );
  8669. } else if ( binding.isStorageBuffer ) {
  8670. const attribute = binding.attribute;
  8671. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  8672. this.attributes.update( attribute, attributeType );
  8673. }
  8674. }
  8675. }
  8676. _update( bindGroup, bindings ) {
  8677. const { backend } = this;
  8678. let needsBindingsUpdate = false;
  8679. let cacheBindings = true;
  8680. let cacheIndex = 0;
  8681. let version = 0;
  8682. // iterate over all bindings and check if buffer updates or a new binding group is required
  8683. for ( const binding of bindGroup.bindings ) {
  8684. if ( binding.isNodeUniformsGroup ) {
  8685. const updated = this.nodes.updateGroup( binding );
  8686. if ( ! updated ) continue;
  8687. }
  8688. if ( binding.isUniformBuffer ) {
  8689. const updated = binding.update();
  8690. if ( updated ) {
  8691. backend.updateBinding( binding );
  8692. }
  8693. } else if ( binding.isSampler ) {
  8694. binding.update();
  8695. } else if ( binding.isSampledTexture ) {
  8696. const texturesTextureData = this.textures.get( binding.texture );
  8697. if ( binding.needsBindingsUpdate( texturesTextureData.generation ) ) needsBindingsUpdate = true;
  8698. const updated = binding.update();
  8699. const texture = binding.texture;
  8700. if ( updated ) {
  8701. this.textures.updateTexture( texture );
  8702. }
  8703. const textureData = backend.get( texture );
  8704. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  8705. cacheBindings = false;
  8706. } else {
  8707. cacheIndex = cacheIndex * 10 + texture.id;
  8708. version += texture.version;
  8709. }
  8710. if ( backend.isWebGPUBackend === true && textureData.texture === undefined && textureData.externalTexture === undefined ) {
  8711. // TODO: Remove this once we found why updated === false isn't bound to a texture in the WebGPU backend
  8712. console.error( 'Bindings._update: binding should be available:', binding, updated, texture, binding.textureNode.value, needsBindingsUpdate );
  8713. this.textures.updateTexture( texture );
  8714. needsBindingsUpdate = true;
  8715. }
  8716. if ( texture.isStorageTexture === true ) {
  8717. const textureData = this.get( texture );
  8718. if ( binding.store === true ) {
  8719. textureData.needsMipmap = true;
  8720. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  8721. this.backend.generateMipmaps( texture );
  8722. textureData.needsMipmap = false;
  8723. }
  8724. }
  8725. }
  8726. }
  8727. if ( needsBindingsUpdate === true ) {
  8728. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  8729. }
  8730. }
  8731. }
  8732. function painterSortStable( a, b ) {
  8733. if ( a.groupOrder !== b.groupOrder ) {
  8734. return a.groupOrder - b.groupOrder;
  8735. } else if ( a.renderOrder !== b.renderOrder ) {
  8736. return a.renderOrder - b.renderOrder;
  8737. } else if ( a.material.id !== b.material.id ) {
  8738. return a.material.id - b.material.id;
  8739. } else if ( a.z !== b.z ) {
  8740. return a.z - b.z;
  8741. } else {
  8742. return a.id - b.id;
  8743. }
  8744. }
  8745. function reversePainterSortStable( a, b ) {
  8746. if ( a.groupOrder !== b.groupOrder ) {
  8747. return a.groupOrder - b.groupOrder;
  8748. } else if ( a.renderOrder !== b.renderOrder ) {
  8749. return a.renderOrder - b.renderOrder;
  8750. } else if ( a.z !== b.z ) {
  8751. return b.z - a.z;
  8752. } else {
  8753. return a.id - b.id;
  8754. }
  8755. }
  8756. function needsDoublePass( material ) {
  8757. const hasTransmission = material.transmission > 0 || material.transmissionNode;
  8758. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  8759. }
  8760. class RenderList {
  8761. constructor( lighting, scene, camera ) {
  8762. this.renderItems = [];
  8763. this.renderItemsIndex = 0;
  8764. this.opaque = [];
  8765. this.transparentDoublePass = [];
  8766. this.transparent = [];
  8767. this.bundles = [];
  8768. this.lightsNode = lighting.getNode( scene, camera );
  8769. this.lightsArray = [];
  8770. this.scene = scene;
  8771. this.camera = camera;
  8772. this.occlusionQueryCount = 0;
  8773. }
  8774. begin() {
  8775. this.renderItemsIndex = 0;
  8776. this.opaque.length = 0;
  8777. this.transparentDoublePass.length = 0;
  8778. this.transparent.length = 0;
  8779. this.bundles.length = 0;
  8780. this.lightsArray.length = 0;
  8781. this.occlusionQueryCount = 0;
  8782. return this;
  8783. }
  8784. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  8785. let renderItem = this.renderItems[ this.renderItemsIndex ];
  8786. if ( renderItem === undefined ) {
  8787. renderItem = {
  8788. id: object.id,
  8789. object: object,
  8790. geometry: geometry,
  8791. material: material,
  8792. groupOrder: groupOrder,
  8793. renderOrder: object.renderOrder,
  8794. z: z,
  8795. group: group,
  8796. clippingContext: clippingContext
  8797. };
  8798. this.renderItems[ this.renderItemsIndex ] = renderItem;
  8799. } else {
  8800. renderItem.id = object.id;
  8801. renderItem.object = object;
  8802. renderItem.geometry = geometry;
  8803. renderItem.material = material;
  8804. renderItem.groupOrder = groupOrder;
  8805. renderItem.renderOrder = object.renderOrder;
  8806. renderItem.z = z;
  8807. renderItem.group = group;
  8808. renderItem.clippingContext = clippingContext;
  8809. }
  8810. this.renderItemsIndex ++;
  8811. return renderItem;
  8812. }
  8813. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  8814. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  8815. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  8816. if ( material.transparent === true || material.transmission > 0 ) {
  8817. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  8818. this.transparent.push( renderItem );
  8819. } else {
  8820. this.opaque.push( renderItem );
  8821. }
  8822. }
  8823. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  8824. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  8825. if ( material.transparent === true || material.transmission > 0 ) {
  8826. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  8827. this.transparent.unshift( renderItem );
  8828. } else {
  8829. this.opaque.unshift( renderItem );
  8830. }
  8831. }
  8832. pushBundle( group ) {
  8833. this.bundles.push( group );
  8834. }
  8835. pushLight( light ) {
  8836. this.lightsArray.push( light );
  8837. }
  8838. sort( customOpaqueSort, customTransparentSort ) {
  8839. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  8840. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  8841. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  8842. }
  8843. finish() {
  8844. // update lights
  8845. this.lightsNode.setLights( this.lightsArray );
  8846. // Clear references from inactive renderItems in the list
  8847. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  8848. const renderItem = this.renderItems[ i ];
  8849. if ( renderItem.id === null ) break;
  8850. renderItem.id = null;
  8851. renderItem.object = null;
  8852. renderItem.geometry = null;
  8853. renderItem.material = null;
  8854. renderItem.groupOrder = null;
  8855. renderItem.renderOrder = null;
  8856. renderItem.z = null;
  8857. renderItem.group = null;
  8858. renderItem.clippingContext = null;
  8859. }
  8860. }
  8861. }
  8862. class RenderLists {
  8863. constructor( lighting ) {
  8864. this.lighting = lighting;
  8865. this.lists = new ChainMap();
  8866. }
  8867. get( scene, camera ) {
  8868. const lists = this.lists;
  8869. const keys = [ scene, camera ];
  8870. let list = lists.get( keys );
  8871. if ( list === undefined ) {
  8872. list = new RenderList( this.lighting, scene, camera );
  8873. lists.set( keys, list );
  8874. }
  8875. return list;
  8876. }
  8877. dispose() {
  8878. this.lists = new ChainMap();
  8879. }
  8880. }
  8881. let id$1 = 0;
  8882. class RenderContext {
  8883. constructor() {
  8884. this.id = id$1 ++;
  8885. this.color = true;
  8886. this.clearColor = true;
  8887. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  8888. this.depth = true;
  8889. this.clearDepth = true;
  8890. this.clearDepthValue = 1;
  8891. this.stencil = false;
  8892. this.clearStencil = true;
  8893. this.clearStencilValue = 1;
  8894. this.viewport = false;
  8895. this.viewportValue = new Vector4();
  8896. this.scissor = false;
  8897. this.scissorValue = new Vector4();
  8898. this.textures = null;
  8899. this.depthTexture = null;
  8900. this.activeCubeFace = 0;
  8901. this.sampleCount = 1;
  8902. this.width = 0;
  8903. this.height = 0;
  8904. this.isRenderContext = true;
  8905. }
  8906. getCacheKey() {
  8907. return getCacheKey( this );
  8908. }
  8909. }
  8910. function getCacheKey( renderContext ) {
  8911. const { textures, activeCubeFace } = renderContext;
  8912. const values = [ activeCubeFace ];
  8913. for ( const texture of textures ) {
  8914. values.push( texture.id );
  8915. }
  8916. return hashArray( values );
  8917. }
  8918. class RenderContexts {
  8919. constructor() {
  8920. this.chainMaps = {};
  8921. }
  8922. get( scene, camera, renderTarget = null ) {
  8923. const chainKey = [ scene, camera ];
  8924. let attachmentState;
  8925. if ( renderTarget === null ) {
  8926. attachmentState = 'default';
  8927. } else {
  8928. const format = renderTarget.texture.format;
  8929. const count = renderTarget.textures.length;
  8930. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  8931. }
  8932. const chainMap = this.getChainMap( attachmentState );
  8933. let renderState = chainMap.get( chainKey );
  8934. if ( renderState === undefined ) {
  8935. renderState = new RenderContext();
  8936. chainMap.set( chainKey, renderState );
  8937. }
  8938. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  8939. return renderState;
  8940. }
  8941. getChainMap( attachmentState ) {
  8942. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  8943. }
  8944. dispose() {
  8945. this.chainMaps = {};
  8946. }
  8947. }
  8948. const _size$3 = /*@__PURE__*/ new Vector3();
  8949. class Textures extends DataMap {
  8950. constructor( renderer, backend, info ) {
  8951. super();
  8952. this.renderer = renderer;
  8953. this.backend = backend;
  8954. this.info = info;
  8955. }
  8956. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  8957. const renderTargetData = this.get( renderTarget );
  8958. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  8959. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  8960. const textures = renderTarget.textures;
  8961. const size = this.getSize( textures[ 0 ] );
  8962. const mipWidth = size.width >> activeMipmapLevel;
  8963. const mipHeight = size.height >> activeMipmapLevel;
  8964. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  8965. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  8966. let textureNeedsUpdate = false;
  8967. if ( depthTexture === undefined && useDepthTexture ) {
  8968. depthTexture = new DepthTexture();
  8969. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  8970. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  8971. depthTexture.image.width = mipWidth;
  8972. depthTexture.image.height = mipHeight;
  8973. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  8974. }
  8975. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  8976. textureNeedsUpdate = true;
  8977. if ( depthTexture ) {
  8978. depthTexture.needsUpdate = true;
  8979. depthTexture.image.width = mipWidth;
  8980. depthTexture.image.height = mipHeight;
  8981. }
  8982. }
  8983. renderTargetData.width = size.width;
  8984. renderTargetData.height = size.height;
  8985. renderTargetData.textures = textures;
  8986. renderTargetData.depthTexture = depthTexture || null;
  8987. renderTargetData.depth = renderTarget.depthBuffer;
  8988. renderTargetData.stencil = renderTarget.stencilBuffer;
  8989. renderTargetData.renderTarget = renderTarget;
  8990. if ( renderTargetData.sampleCount !== sampleCount ) {
  8991. textureNeedsUpdate = true;
  8992. if ( depthTexture ) {
  8993. depthTexture.needsUpdate = true;
  8994. }
  8995. renderTargetData.sampleCount = sampleCount;
  8996. }
  8997. //
  8998. const options = { sampleCount };
  8999. for ( let i = 0; i < textures.length; i ++ ) {
  9000. const texture = textures[ i ];
  9001. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  9002. this.updateTexture( texture, options );
  9003. }
  9004. if ( depthTexture ) {
  9005. this.updateTexture( depthTexture, options );
  9006. }
  9007. // dispose handler
  9008. if ( renderTargetData.initialized !== true ) {
  9009. renderTargetData.initialized = true;
  9010. // dispose
  9011. const onDispose = () => {
  9012. renderTarget.removeEventListener( 'dispose', onDispose );
  9013. for ( let i = 0; i < textures.length; i ++ ) {
  9014. this._destroyTexture( textures[ i ] );
  9015. }
  9016. if ( depthTexture ) {
  9017. this._destroyTexture( depthTexture );
  9018. }
  9019. this.delete( renderTarget );
  9020. };
  9021. renderTarget.addEventListener( 'dispose', onDispose );
  9022. }
  9023. }
  9024. updateTexture( texture, options = {} ) {
  9025. const textureData = this.get( texture );
  9026. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  9027. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  9028. const backend = this.backend;
  9029. if ( isRenderTarget && textureData.initialized === true ) {
  9030. // it's an update
  9031. backend.destroySampler( texture );
  9032. backend.destroyTexture( texture );
  9033. }
  9034. //
  9035. if ( texture.isFramebufferTexture ) {
  9036. const renderTarget = this.renderer.getRenderTarget();
  9037. if ( renderTarget ) {
  9038. texture.type = renderTarget.texture.type;
  9039. } else {
  9040. texture.type = UnsignedByteType;
  9041. }
  9042. }
  9043. //
  9044. const { width, height, depth } = this.getSize( texture );
  9045. options.width = width;
  9046. options.height = height;
  9047. options.depth = depth;
  9048. options.needsMipmaps = this.needsMipmaps( texture );
  9049. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  9050. //
  9051. if ( isRenderTarget || texture.isStorageTexture === true ) {
  9052. backend.createSampler( texture );
  9053. backend.createTexture( texture, options );
  9054. textureData.generation = texture.version;
  9055. } else {
  9056. const needsCreate = textureData.initialized !== true;
  9057. if ( needsCreate ) backend.createSampler( texture );
  9058. if ( texture.version > 0 ) {
  9059. const image = texture.image;
  9060. if ( image === undefined ) {
  9061. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  9062. } else if ( image.complete === false ) {
  9063. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  9064. } else {
  9065. if ( texture.images ) {
  9066. const images = [];
  9067. for ( const image of texture.images ) {
  9068. images.push( image );
  9069. }
  9070. options.images = images;
  9071. } else {
  9072. options.image = image;
  9073. }
  9074. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  9075. backend.createTexture( texture, options );
  9076. textureData.isDefaultTexture = false;
  9077. textureData.generation = texture.version;
  9078. }
  9079. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  9080. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  9081. }
  9082. } else {
  9083. // async update
  9084. backend.createDefaultTexture( texture );
  9085. textureData.isDefaultTexture = true;
  9086. textureData.generation = texture.version;
  9087. }
  9088. }
  9089. // dispose handler
  9090. if ( textureData.initialized !== true ) {
  9091. textureData.initialized = true;
  9092. textureData.generation = texture.version;
  9093. //
  9094. this.info.memory.textures ++;
  9095. // dispose
  9096. const onDispose = () => {
  9097. texture.removeEventListener( 'dispose', onDispose );
  9098. this._destroyTexture( texture );
  9099. this.info.memory.textures --;
  9100. };
  9101. texture.addEventListener( 'dispose', onDispose );
  9102. }
  9103. //
  9104. textureData.version = texture.version;
  9105. }
  9106. getSize( texture, target = _size$3 ) {
  9107. let image = texture.images ? texture.images[ 0 ] : texture.image;
  9108. if ( image ) {
  9109. if ( image.image !== undefined ) image = image.image;
  9110. target.width = image.width || 1;
  9111. target.height = image.height || 1;
  9112. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  9113. } else {
  9114. target.width = target.height = target.depth = 1;
  9115. }
  9116. return target;
  9117. }
  9118. getMipLevels( texture, width, height ) {
  9119. let mipLevelCount;
  9120. if ( texture.isCompressedTexture ) {
  9121. if ( texture.mipmaps ) {
  9122. mipLevelCount = texture.mipmaps.length;
  9123. } else {
  9124. mipLevelCount = 1;
  9125. }
  9126. } else {
  9127. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  9128. }
  9129. return mipLevelCount;
  9130. }
  9131. needsMipmaps( texture ) {
  9132. return this.isEnvironmentTexture( texture ) || texture.isCompressedTexture === true || texture.generateMipmaps;
  9133. }
  9134. isEnvironmentTexture( texture ) {
  9135. const mapping = texture.mapping;
  9136. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  9137. }
  9138. _destroyTexture( texture ) {
  9139. this.backend.destroySampler( texture );
  9140. this.backend.destroyTexture( texture );
  9141. this.delete( texture );
  9142. }
  9143. }
  9144. class Color4 extends Color {
  9145. constructor( r, g, b, a = 1 ) {
  9146. super( r, g, b );
  9147. this.a = a;
  9148. }
  9149. set( r, g, b, a = 1 ) {
  9150. this.a = a;
  9151. return super.set( r, g, b );
  9152. }
  9153. copy( color ) {
  9154. if ( color.a !== undefined ) this.a = color.a;
  9155. return super.copy( color );
  9156. }
  9157. clone() {
  9158. return new this.constructor( this.r, this.g, this.b, this.a );
  9159. }
  9160. }
  9161. class ParameterNode extends PropertyNode {
  9162. static get type() {
  9163. return 'ParameterNode';
  9164. }
  9165. constructor( nodeType, name = null ) {
  9166. super( nodeType, name );
  9167. this.isParameterNode = true;
  9168. }
  9169. getHash() {
  9170. return this.uuid;
  9171. }
  9172. generate() {
  9173. return this.name;
  9174. }
  9175. }
  9176. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  9177. class StackNode extends Node {
  9178. static get type() {
  9179. return 'StackNode';
  9180. }
  9181. constructor( parent = null ) {
  9182. super();
  9183. this.nodes = [];
  9184. this.outputNode = null;
  9185. this.parent = parent;
  9186. this._currentCond = null;
  9187. this.isStackNode = true;
  9188. }
  9189. getNodeType( builder ) {
  9190. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  9191. }
  9192. add( node ) {
  9193. this.nodes.push( node );
  9194. return this;
  9195. }
  9196. If( boolNode, method ) {
  9197. const methodNode = new ShaderNode( method );
  9198. this._currentCond = select( boolNode, methodNode );
  9199. return this.add( this._currentCond );
  9200. }
  9201. ElseIf( boolNode, method ) {
  9202. const methodNode = new ShaderNode( method );
  9203. const ifNode = select( boolNode, methodNode );
  9204. this._currentCond.elseNode = ifNode;
  9205. this._currentCond = ifNode;
  9206. return this;
  9207. }
  9208. Else( method ) {
  9209. this._currentCond.elseNode = new ShaderNode( method );
  9210. return this;
  9211. }
  9212. build( builder, ...params ) {
  9213. const previousStack = getCurrentStack();
  9214. setCurrentStack( this );
  9215. for ( const node of this.nodes ) {
  9216. node.build( builder, 'void' );
  9217. }
  9218. setCurrentStack( previousStack );
  9219. return this.outputNode ? this.outputNode.build( builder, ...params ) : super.build( builder, ...params );
  9220. }
  9221. //
  9222. else( ...params ) { // @deprecated, r168
  9223. console.warn( 'TSL.StackNode: .else() has been renamed to .Else().' );
  9224. return this.Else( ...params );
  9225. }
  9226. elseif( ...params ) { // @deprecated, r168
  9227. console.warn( 'TSL.StackNode: .elseif() has been renamed to .ElseIf().' );
  9228. return this.ElseIf( ...params );
  9229. }
  9230. }
  9231. const stack = /*@__PURE__*/ nodeProxy( StackNode );
  9232. class StructTypeNode extends Node {
  9233. static get type() {
  9234. return 'StructTypeNode';
  9235. }
  9236. constructor( types ) {
  9237. super();
  9238. this.types = types;
  9239. this.isStructTypeNode = true;
  9240. }
  9241. getMemberTypes() {
  9242. return this.types;
  9243. }
  9244. }
  9245. class OutputStructNode extends Node {
  9246. static get type() {
  9247. return 'OutputStructNode';
  9248. }
  9249. constructor( ...members ) {
  9250. super();
  9251. this.members = members;
  9252. this.isOutputStructNode = true;
  9253. }
  9254. setup( builder ) {
  9255. super.setup( builder );
  9256. const members = this.members;
  9257. const types = [];
  9258. for ( let i = 0; i < members.length; i ++ ) {
  9259. types.push( members[ i ].getNodeType( builder ) );
  9260. }
  9261. this.nodeType = builder.getStructTypeFromNode( new StructTypeNode( types ) ).name;
  9262. }
  9263. generate( builder, output ) {
  9264. const propertyName = builder.getOutputStructName();
  9265. const members = this.members;
  9266. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  9267. for ( let i = 0; i < members.length; i ++ ) {
  9268. const snippet = members[ i ].build( builder, output );
  9269. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  9270. }
  9271. return propertyName;
  9272. }
  9273. }
  9274. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  9275. function getTextureIndex( textures, name ) {
  9276. for ( let i = 0; i < textures.length; i ++ ) {
  9277. if ( textures[ i ].name === name ) {
  9278. return i;
  9279. }
  9280. }
  9281. return - 1;
  9282. }
  9283. class MRTNode extends OutputStructNode {
  9284. static get type() {
  9285. return 'MRTNode';
  9286. }
  9287. constructor( outputNodes ) {
  9288. super();
  9289. this.outputNodes = outputNodes;
  9290. this.isMRTNode = true;
  9291. }
  9292. has( name ) {
  9293. return this.outputNodes[ name ] !== undefined;
  9294. }
  9295. get( name ) {
  9296. return this.outputNodes[ name ];
  9297. }
  9298. merge( mrtNode ) {
  9299. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  9300. return mrt( outputs );
  9301. }
  9302. setup( builder ) {
  9303. const outputNodes = this.outputNodes;
  9304. const mrt = builder.renderer.getRenderTarget();
  9305. const members = [];
  9306. const textures = mrt.textures;
  9307. for ( const name in outputNodes ) {
  9308. const index = getTextureIndex( textures, name );
  9309. members[ index ] = vec4( outputNodes[ name ] );
  9310. }
  9311. this.members = members;
  9312. return super.setup( builder );
  9313. }
  9314. }
  9315. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  9316. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  9317. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  9318. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  9319. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  9320. const result = word.shiftRight( 22 ).bitXor( word );
  9321. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  9322. } );
  9323. // remapping functions https://iquilezles.org/articles/functions/
  9324. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  9325. 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 ) );
  9326. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  9327. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  9328. // https://github.com/cabbibo/glsl-tri-noise-3d
  9329. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  9330. return x.fract().sub( .5 ).abs();
  9331. } ).setLayout( {
  9332. name: 'tri',
  9333. type: 'float',
  9334. inputs: [
  9335. { name: 'x', type: 'float' }
  9336. ]
  9337. } );
  9338. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  9339. 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. ) ) ) ) );
  9340. } ).setLayout( {
  9341. name: 'tri3',
  9342. type: 'vec3',
  9343. inputs: [
  9344. { name: 'p', type: 'vec3' }
  9345. ]
  9346. } );
  9347. const triNoise3D = /*@__PURE__*/ Fn( ( [ p_immutable, spd, time ] ) => {
  9348. const p = vec3( p_immutable ).toVar();
  9349. const z = float( 1.4 ).toVar();
  9350. const rz = float( 0.0 ).toVar();
  9351. const bp = vec3( p ).toVar();
  9352. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  9353. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  9354. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( spd ) ) ) );
  9355. bp.mulAssign( 1.8 );
  9356. z.mulAssign( 1.5 );
  9357. p.mulAssign( 1.2 );
  9358. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  9359. rz.addAssign( t.div( z ) );
  9360. bp.addAssign( 0.14 );
  9361. } );
  9362. return rz;
  9363. } ).setLayout( {
  9364. name: 'triNoise3D',
  9365. type: 'float',
  9366. inputs: [
  9367. { name: 'p', type: 'vec3' },
  9368. { name: 'spd', type: 'float' },
  9369. { name: 'time', type: 'float' }
  9370. ]
  9371. } );
  9372. class FunctionOverloadingNode extends Node {
  9373. static get type() {
  9374. return 'FunctionOverloadingNode';
  9375. }
  9376. constructor( functionNodes = [], ...parametersNodes ) {
  9377. super();
  9378. this.functionNodes = functionNodes;
  9379. this.parametersNodes = parametersNodes;
  9380. this._candidateFnCall = null;
  9381. this.global = true;
  9382. }
  9383. getNodeType() {
  9384. return this.functionNodes[ 0 ].shaderNode.layout.type;
  9385. }
  9386. setup( builder ) {
  9387. const params = this.parametersNodes;
  9388. let candidateFnCall = this._candidateFnCall;
  9389. if ( candidateFnCall === null ) {
  9390. let candidateFn = null;
  9391. let candidateScore = - 1;
  9392. for ( const functionNode of this.functionNodes ) {
  9393. const shaderNode = functionNode.shaderNode;
  9394. const layout = shaderNode.layout;
  9395. if ( layout === null ) {
  9396. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  9397. }
  9398. const inputs = layout.inputs;
  9399. if ( params.length === inputs.length ) {
  9400. let score = 0;
  9401. for ( let i = 0; i < params.length; i ++ ) {
  9402. const param = params[ i ];
  9403. const input = inputs[ i ];
  9404. if ( param.getNodeType( builder ) === input.type ) {
  9405. score ++;
  9406. } else {
  9407. score = 0;
  9408. }
  9409. }
  9410. if ( score > candidateScore ) {
  9411. candidateFn = functionNode;
  9412. candidateScore = score;
  9413. }
  9414. }
  9415. }
  9416. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  9417. }
  9418. return candidateFnCall;
  9419. }
  9420. }
  9421. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  9422. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  9423. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  9424. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  9425. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  9426. // Deprecated
  9427. const timerLocal = ( timeScale = 1 ) => { // @deprecated, r170
  9428. console.warn( 'TSL: timerLocal() is deprecated. Use "time" instead.' );
  9429. return time.mul( timeScale );
  9430. };
  9431. const timerGlobal = ( timeScale = 1 ) => { // @deprecated, r170
  9432. console.warn( 'TSL: timerGlobal() is deprecated. Use "time" instead.' );
  9433. return time.mul( timeScale );
  9434. };
  9435. const timerDelta = ( timeScale = 1 ) => { // @deprecated, r170
  9436. console.warn( 'TSL: timerDelta() is deprecated. Use "deltaTime" instead.' );
  9437. return deltaTime.mul( timeScale );
  9438. };
  9439. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  9440. const oscSquare = ( t = time ) => t.fract().round();
  9441. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  9442. const oscSawtooth = ( t = time ) => t.fract();
  9443. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  9444. return rotate( uv.sub( center ), rotation ).add( center );
  9445. } );
  9446. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  9447. const delta = uv.sub( center );
  9448. const delta2 = delta.dot( delta );
  9449. const delta4 = delta2.mul( delta2 );
  9450. const deltaOffset = delta4.mul( strength );
  9451. return uv.add( delta.mul( deltaOffset ) );
  9452. } );
  9453. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  9454. let worldMatrix;
  9455. if ( position !== null ) {
  9456. worldMatrix = modelWorldMatrix.toVar();
  9457. worldMatrix[ 3 ][ 0 ] = position.x;
  9458. worldMatrix[ 3 ][ 1 ] = position.y;
  9459. worldMatrix[ 3 ][ 2 ] = position.z;
  9460. } else {
  9461. worldMatrix = modelWorldMatrix;
  9462. }
  9463. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  9464. if ( defined( horizontal ) ) {
  9465. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  9466. modelViewMatrix[ 0 ][ 1 ] = 0;
  9467. modelViewMatrix[ 0 ][ 2 ] = 0;
  9468. }
  9469. if ( defined( vertical ) ) {
  9470. modelViewMatrix[ 1 ][ 0 ] = 0;
  9471. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  9472. modelViewMatrix[ 1 ][ 2 ] = 0;
  9473. }
  9474. modelViewMatrix[ 2 ][ 0 ] = 0;
  9475. modelViewMatrix[ 2 ][ 1 ] = 0;
  9476. modelViewMatrix[ 2 ][ 2 ] = 1;
  9477. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  9478. } );
  9479. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  9480. const depth = linearDepth();
  9481. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  9482. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  9483. return finalUV;
  9484. } );
  9485. class SpriteSheetUVNode extends Node {
  9486. static get type() {
  9487. return 'SpriteSheetUVNode';
  9488. }
  9489. constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) {
  9490. super( 'vec2' );
  9491. this.countNode = countNode;
  9492. this.uvNode = uvNode;
  9493. this.frameNode = frameNode;
  9494. }
  9495. setup() {
  9496. const { frameNode, uvNode, countNode } = this;
  9497. const { width, height } = countNode;
  9498. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  9499. const column = frameNum.mod( width );
  9500. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  9501. const scale = countNode.reciprocal();
  9502. const uvFrameOffset = vec2( column, row );
  9503. return uvNode.add( uvFrameOffset ).mul( scale );
  9504. }
  9505. }
  9506. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode );
  9507. class TriplanarTexturesNode extends Node {
  9508. static get type() {
  9509. return 'TriplanarTexturesNode';
  9510. }
  9511. constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) {
  9512. super( 'vec4' );
  9513. this.textureXNode = textureXNode;
  9514. this.textureYNode = textureYNode;
  9515. this.textureZNode = textureZNode;
  9516. this.scaleNode = scaleNode;
  9517. this.positionNode = positionNode;
  9518. this.normalNode = normalNode;
  9519. }
  9520. setup() {
  9521. const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this;
  9522. // Ref: https://github.com/keijiro/StandardTriplanar
  9523. // Blending factor of triplanar mapping
  9524. let bf = normalNode.abs().normalize();
  9525. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  9526. // Triplanar mapping
  9527. const tx = positionNode.yz.mul( scaleNode );
  9528. const ty = positionNode.zx.mul( scaleNode );
  9529. const tz = positionNode.xy.mul( scaleNode );
  9530. // Base color
  9531. const textureX = textureXNode.value;
  9532. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  9533. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  9534. const cx = texture( textureX, tx ).mul( bf.x );
  9535. const cy = texture( textureY, ty ).mul( bf.y );
  9536. const cz = texture( textureZ, tz ).mul( bf.z );
  9537. return add( cx, cy, cz );
  9538. }
  9539. }
  9540. const triplanarTextures = /*@__PURE__*/ nodeProxy( TriplanarTexturesNode );
  9541. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  9542. const _reflectorPlane = new Plane();
  9543. const _normal = new Vector3();
  9544. const _reflectorWorldPosition = new Vector3();
  9545. const _cameraWorldPosition = new Vector3();
  9546. const _rotationMatrix = new Matrix4();
  9547. const _lookAtPosition = new Vector3( 0, 0, - 1 );
  9548. const clipPlane = new Vector4();
  9549. const _view = new Vector3();
  9550. const _target = new Vector3();
  9551. const _q = new Vector4();
  9552. const _size$2 = new Vector2();
  9553. const _defaultRT = new RenderTarget();
  9554. const _defaultUV = screenUV.flipX();
  9555. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  9556. let _inReflector = false;
  9557. class ReflectorNode extends TextureNode {
  9558. static get type() {
  9559. return 'ReflectorNode';
  9560. }
  9561. constructor( parameters = {} ) {
  9562. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  9563. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  9564. this._depthNode = null;
  9565. this.setUpdateMatrix( false );
  9566. }
  9567. get reflector() {
  9568. return this._reflectorBaseNode;
  9569. }
  9570. get target() {
  9571. return this._reflectorBaseNode.target;
  9572. }
  9573. getDepthNode() {
  9574. if ( this._depthNode === null ) {
  9575. if ( this._reflectorBaseNode.depth !== true ) {
  9576. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  9577. }
  9578. this._depthNode = nodeObject( new ReflectorNode( {
  9579. defaultTexture: _defaultRT.depthTexture,
  9580. reflector: this._reflectorBaseNode
  9581. } ) );
  9582. }
  9583. return this._depthNode;
  9584. }
  9585. setup( builder ) {
  9586. // ignore if used in post-processing
  9587. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  9588. return super.setup( builder );
  9589. }
  9590. clone() {
  9591. const texture = new this.constructor( this.reflectorNode );
  9592. texture._reflectorBaseNode = this._reflectorBaseNode;
  9593. return texture;
  9594. }
  9595. }
  9596. class ReflectorBaseNode extends Node {
  9597. static get type() {
  9598. return 'ReflectorBaseNode';
  9599. }
  9600. constructor( textureNode, parameters = {} ) {
  9601. super();
  9602. const {
  9603. target = new Object3D(),
  9604. resolution = 1,
  9605. generateMipmaps = false,
  9606. bounces = true,
  9607. depth = false
  9608. } = parameters;
  9609. //
  9610. this.textureNode = textureNode;
  9611. this.target = target;
  9612. this.resolution = resolution;
  9613. this.generateMipmaps = generateMipmaps;
  9614. this.bounces = bounces;
  9615. this.depth = depth;
  9616. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  9617. this.virtualCameras = new WeakMap();
  9618. this.renderTargets = new WeakMap();
  9619. }
  9620. _updateResolution( renderTarget, renderer ) {
  9621. const resolution = this.resolution;
  9622. renderer.getDrawingBufferSize( _size$2 );
  9623. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  9624. }
  9625. setup( builder ) {
  9626. this._updateResolution( _defaultRT, builder.renderer );
  9627. return super.setup( builder );
  9628. }
  9629. getVirtualCamera( camera ) {
  9630. let virtualCamera = this.virtualCameras.get( camera );
  9631. if ( virtualCamera === undefined ) {
  9632. virtualCamera = camera.clone();
  9633. this.virtualCameras.set( camera, virtualCamera );
  9634. }
  9635. return virtualCamera;
  9636. }
  9637. getRenderTarget( camera ) {
  9638. let renderTarget = this.renderTargets.get( camera );
  9639. if ( renderTarget === undefined ) {
  9640. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } );
  9641. if ( this.generateMipmaps === true ) {
  9642. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  9643. renderTarget.texture.generateMipmaps = true;
  9644. }
  9645. if ( this.depth === true ) {
  9646. renderTarget.depthTexture = new DepthTexture();
  9647. }
  9648. this.renderTargets.set( camera, renderTarget );
  9649. }
  9650. return renderTarget;
  9651. }
  9652. updateBefore( frame ) {
  9653. if ( this.bounces === false && _inReflector ) return;
  9654. _inReflector = true;
  9655. const { scene, camera, renderer, material } = frame;
  9656. const { target } = this;
  9657. const virtualCamera = this.getVirtualCamera( camera );
  9658. const renderTarget = this.getRenderTarget( virtualCamera );
  9659. renderer.getDrawingBufferSize( _size$2 );
  9660. this._updateResolution( renderTarget, renderer );
  9661. //
  9662. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  9663. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  9664. _rotationMatrix.extractRotation( target.matrixWorld );
  9665. _normal.set( 0, 0, 1 );
  9666. _normal.applyMatrix4( _rotationMatrix );
  9667. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  9668. // Avoid rendering when reflector is facing away
  9669. if ( _view.dot( _normal ) > 0 ) return;
  9670. _view.reflect( _normal ).negate();
  9671. _view.add( _reflectorWorldPosition );
  9672. _rotationMatrix.extractRotation( camera.matrixWorld );
  9673. _lookAtPosition.set( 0, 0, - 1 );
  9674. _lookAtPosition.applyMatrix4( _rotationMatrix );
  9675. _lookAtPosition.add( _cameraWorldPosition );
  9676. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  9677. _target.reflect( _normal ).negate();
  9678. _target.add( _reflectorWorldPosition );
  9679. //
  9680. virtualCamera.coordinateSystem = camera.coordinateSystem;
  9681. virtualCamera.position.copy( _view );
  9682. virtualCamera.up.set( 0, 1, 0 );
  9683. virtualCamera.up.applyMatrix4( _rotationMatrix );
  9684. virtualCamera.up.reflect( _normal );
  9685. virtualCamera.lookAt( _target );
  9686. virtualCamera.near = camera.near;
  9687. virtualCamera.far = camera.far;
  9688. virtualCamera.updateMatrixWorld();
  9689. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  9690. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  9691. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  9692. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  9693. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  9694. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  9695. const projectionMatrix = virtualCamera.projectionMatrix;
  9696. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  9697. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  9698. _q.z = - 1.0;
  9699. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  9700. // Calculate the scaled plane vector
  9701. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  9702. const clipBias = 0;
  9703. // Replacing the third row of the projection matrix
  9704. projectionMatrix.elements[ 2 ] = clipPlane.x;
  9705. projectionMatrix.elements[ 6 ] = clipPlane.y;
  9706. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  9707. projectionMatrix.elements[ 14 ] = clipPlane.w;
  9708. //
  9709. this.textureNode.value = renderTarget.texture;
  9710. if ( this.depth === true ) {
  9711. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  9712. }
  9713. material.visible = false;
  9714. const currentRenderTarget = renderer.getRenderTarget();
  9715. const currentMRT = renderer.getMRT();
  9716. renderer.setMRT( null );
  9717. renderer.setRenderTarget( renderTarget );
  9718. renderer.render( scene, virtualCamera );
  9719. renderer.setMRT( currentMRT );
  9720. renderer.setRenderTarget( currentRenderTarget );
  9721. material.visible = true;
  9722. _inReflector = false;
  9723. }
  9724. }
  9725. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  9726. // Helper for passes that need to fill the viewport with a single quad.
  9727. const _camera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  9728. // https://github.com/mrdoob/three.js/pull/21358
  9729. class QuadGeometry extends BufferGeometry {
  9730. constructor( flipY = false ) {
  9731. super();
  9732. const uv = flipY === false ? [ 0, - 1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  9733. this.setAttribute( 'position', new Float32BufferAttribute( [ - 1, 3, 0, - 1, - 1, 0, 3, - 1, 0 ], 3 ) );
  9734. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  9735. }
  9736. }
  9737. const _geometry = /*@__PURE__*/ new QuadGeometry();
  9738. class QuadMesh extends Mesh {
  9739. constructor( material = null ) {
  9740. super( _geometry, material );
  9741. this.camera = _camera;
  9742. this.isQuadMesh = true;
  9743. }
  9744. renderAsync( renderer ) {
  9745. return renderer.renderAsync( this, _camera );
  9746. }
  9747. render( renderer ) {
  9748. renderer.render( this, _camera );
  9749. }
  9750. }
  9751. const _size$1 = /*@__PURE__*/ new Vector2();
  9752. class RTTNode extends TextureNode {
  9753. static get type() {
  9754. return 'RTTNode';
  9755. }
  9756. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  9757. const renderTarget = new RenderTarget( width, height, options );
  9758. super( renderTarget.texture, uv() );
  9759. this.node = node;
  9760. this.width = width;
  9761. this.height = height;
  9762. this.renderTarget = renderTarget;
  9763. this.textureNeedsUpdate = true;
  9764. this.autoUpdate = true;
  9765. this.updateMap = new WeakMap();
  9766. this._rttNode = null;
  9767. this._quadMesh = new QuadMesh( new NodeMaterial() );
  9768. this.updateBeforeType = NodeUpdateType.RENDER;
  9769. }
  9770. get autoSize() {
  9771. return this.width === null;
  9772. }
  9773. setup( builder ) {
  9774. this._rttNode = this.node.context( builder.getSharedContext() );
  9775. this._quadMesh.material.name = 'RTT';
  9776. this._quadMesh.material.needsUpdate = true;
  9777. return super.setup( builder );
  9778. }
  9779. setSize( width, height ) {
  9780. this.width = width;
  9781. this.height = height;
  9782. const effectiveWidth = width * this.pixelRatio;
  9783. const effectiveHeight = height * this.pixelRatio;
  9784. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  9785. this.textureNeedsUpdate = true;
  9786. }
  9787. setPixelRatio( pixelRatio ) {
  9788. this.pixelRatio = pixelRatio;
  9789. this.setSize( this.width, this.height );
  9790. }
  9791. updateBefore( { renderer } ) {
  9792. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  9793. this.textureNeedsUpdate = false;
  9794. //
  9795. if ( this.autoSize === true ) {
  9796. this.pixelRatio = renderer.getPixelRatio();
  9797. const size = renderer.getSize( _size$1 );
  9798. this.setSize( size.width, size.height );
  9799. }
  9800. //
  9801. this._quadMesh.material.fragmentNode = this._rttNode;
  9802. //
  9803. const currentRenderTarget = renderer.getRenderTarget();
  9804. renderer.setRenderTarget( this.renderTarget );
  9805. this._quadMesh.render( renderer );
  9806. renderer.setRenderTarget( currentRenderTarget );
  9807. }
  9808. clone() {
  9809. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  9810. newNode.sampler = this.sampler;
  9811. newNode.referenceNode = this;
  9812. return newNode;
  9813. }
  9814. }
  9815. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  9816. const convertToTexture = ( node, ...params ) => node.isTextureNode ? node : rtt( node, ...params );
  9817. /**
  9818. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  9819. * depth value and the camera's inverse projection matrix.
  9820. *
  9821. * @param {vec2} screenPosition - The fragment's screen position expressed as uv coordinates.
  9822. * @param {float} depth - The fragment's depth value.
  9823. * @param {mat4} projectionMatrixInverse - The camera's inverse projection matrix.
  9824. * @return {vec3} The fragments position in view space.
  9825. */
  9826. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  9827. let clipSpacePosition;
  9828. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  9829. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  9830. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  9831. } else {
  9832. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  9833. }
  9834. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  9835. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  9836. } );
  9837. /**
  9838. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  9839. * and the camera's projection matrix
  9840. *
  9841. * @param {vec3} viewPosition - The fragments position in view space.
  9842. * @param {mat4} projectionMatrix - The camera's projection matrix.
  9843. * @return {vec2} The fragment's screen position expressed as uv coordinates.
  9844. */
  9845. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  9846. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  9847. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  9848. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  9849. } );
  9850. /**
  9851. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  9852. * target is available or if flat surface normals are required.
  9853. *
  9854. * @param {vec2} uv - The texture coordinate.
  9855. * @param {DepthTexture} depthTexture - The depth texture.
  9856. * @param {mat4} projectionMatrixInverse - The camera's inverse projection matrix.
  9857. * @return {vec3} The computed normal vector.
  9858. */
  9859. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  9860. const size = textureSize( textureLoad( depthTexture ) );
  9861. const p = ivec2( uv.mul( size ) ).toVar();
  9862. const c0 = textureLoad( depthTexture, p ).toVar();
  9863. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  9864. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  9865. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  9866. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  9867. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  9868. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  9869. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  9870. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  9871. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  9872. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  9873. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  9874. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  9875. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  9876. 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 ) ) );
  9877. 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 ) ) );
  9878. return normalize( cross( dpdx, dpdy ) );
  9879. } );
  9880. class VertexColorNode extends AttributeNode {
  9881. static get type() {
  9882. return 'VertexColorNode';
  9883. }
  9884. constructor( index = 0 ) {
  9885. super( null, 'vec4' );
  9886. this.isVertexColorNode = true;
  9887. this.index = index;
  9888. }
  9889. getAttributeName( /*builder*/ ) {
  9890. const index = this.index;
  9891. return 'color' + ( index > 0 ? index : '' );
  9892. }
  9893. generate( builder ) {
  9894. const attributeName = this.getAttributeName( builder );
  9895. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  9896. let result;
  9897. if ( geometryAttribute === true ) {
  9898. result = super.generate( builder );
  9899. } else {
  9900. // Vertex color fallback should be white
  9901. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  9902. }
  9903. return result;
  9904. }
  9905. serialize( data ) {
  9906. super.serialize( data );
  9907. data.index = this.index;
  9908. }
  9909. deserialize( data ) {
  9910. super.deserialize( data );
  9911. this.index = data.index;
  9912. }
  9913. }
  9914. const vertexColor = ( ...params ) => nodeObject( new VertexColorNode( ...params ) );
  9915. class PointUVNode extends Node {
  9916. static get type() {
  9917. return 'PointUVNode';
  9918. }
  9919. constructor() {
  9920. super( 'vec2' );
  9921. this.isPointUVNode = true;
  9922. }
  9923. generate( /*builder*/ ) {
  9924. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  9925. }
  9926. }
  9927. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  9928. const _e1 = /*@__PURE__*/ new Euler();
  9929. const _m1 = /*@__PURE__*/ new Matrix4();
  9930. class SceneNode extends Node {
  9931. static get type() {
  9932. return 'SceneNode';
  9933. }
  9934. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  9935. super();
  9936. this.scope = scope;
  9937. this.scene = scene;
  9938. }
  9939. setup( builder ) {
  9940. const scope = this.scope;
  9941. const scene = this.scene !== null ? this.scene : builder.scene;
  9942. let output;
  9943. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  9944. output = reference( 'backgroundBlurriness', 'float', scene );
  9945. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  9946. output = reference( 'backgroundIntensity', 'float', scene );
  9947. } else if ( scope === SceneNode.BACKGROUND_ROTATION ) {
  9948. output = uniform( 'mat4' ).label( 'backgroundRotation' ).setGroup( renderGroup ).onRenderUpdate( () => {
  9949. const background = scene.background;
  9950. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  9951. _e1.copy( scene.backgroundRotation );
  9952. // accommodate left-handed frame
  9953. _e1.x *= - 1; _e1.y *= - 1; _e1.z *= - 1;
  9954. _m1.makeRotationFromEuler( _e1 );
  9955. } else {
  9956. _m1.identity();
  9957. }
  9958. return _m1;
  9959. } );
  9960. } else {
  9961. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  9962. }
  9963. return output;
  9964. }
  9965. }
  9966. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  9967. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  9968. SceneNode.BACKGROUND_ROTATION = 'backgroundRotation';
  9969. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  9970. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  9971. const backgroundRotation = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_ROTATION );
  9972. class StorageArrayElementNode extends ArrayElementNode {
  9973. static get type() {
  9974. return 'StorageArrayElementNode';
  9975. }
  9976. constructor( storageBufferNode, indexNode ) {
  9977. super( storageBufferNode, indexNode );
  9978. this.isStorageArrayElementNode = true;
  9979. }
  9980. set storageBufferNode( value ) {
  9981. this.node = value;
  9982. }
  9983. get storageBufferNode() {
  9984. return this.node;
  9985. }
  9986. setup( builder ) {
  9987. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  9988. if ( this.node.bufferObject === true ) {
  9989. builder.setupPBO( this.node );
  9990. }
  9991. }
  9992. return super.setup( builder );
  9993. }
  9994. generate( builder, output ) {
  9995. let snippet;
  9996. const isAssignContext = builder.context.assign;
  9997. //
  9998. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  9999. if ( this.node.bufferObject === true && isAssignContext !== true ) {
  10000. snippet = builder.generatePBO( this );
  10001. } else {
  10002. snippet = this.node.build( builder );
  10003. }
  10004. } else {
  10005. snippet = super.generate( builder );
  10006. }
  10007. if ( isAssignContext !== true ) {
  10008. const type = this.getNodeType( builder );
  10009. snippet = builder.format( snippet, type, output );
  10010. }
  10011. return snippet;
  10012. }
  10013. }
  10014. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode );
  10015. const GPUPrimitiveTopology = {
  10016. PointList: 'point-list',
  10017. LineList: 'line-list',
  10018. LineStrip: 'line-strip',
  10019. TriangleList: 'triangle-list',
  10020. TriangleStrip: 'triangle-strip',
  10021. };
  10022. const GPUCompareFunction = {
  10023. Never: 'never',
  10024. Less: 'less',
  10025. Equal: 'equal',
  10026. LessEqual: 'less-equal',
  10027. Greater: 'greater',
  10028. NotEqual: 'not-equal',
  10029. GreaterEqual: 'greater-equal',
  10030. Always: 'always'
  10031. };
  10032. const GPUStoreOp = {
  10033. Store: 'store',
  10034. Discard: 'discard'
  10035. };
  10036. const GPULoadOp = {
  10037. Load: 'load',
  10038. Clear: 'clear'
  10039. };
  10040. const GPUFrontFace = {
  10041. CCW: 'ccw',
  10042. CW: 'cw'
  10043. };
  10044. const GPUCullMode = {
  10045. None: 'none',
  10046. Front: 'front',
  10047. Back: 'back'
  10048. };
  10049. const GPUIndexFormat = {
  10050. Uint16: 'uint16',
  10051. Uint32: 'uint32'
  10052. };
  10053. const GPUTextureFormat = {
  10054. // 8-bit formats
  10055. R8Unorm: 'r8unorm',
  10056. R8Snorm: 'r8snorm',
  10057. R8Uint: 'r8uint',
  10058. R8Sint: 'r8sint',
  10059. // 16-bit formats
  10060. R16Uint: 'r16uint',
  10061. R16Sint: 'r16sint',
  10062. R16Float: 'r16float',
  10063. RG8Unorm: 'rg8unorm',
  10064. RG8Snorm: 'rg8snorm',
  10065. RG8Uint: 'rg8uint',
  10066. RG8Sint: 'rg8sint',
  10067. // 32-bit formats
  10068. R32Uint: 'r32uint',
  10069. R32Sint: 'r32sint',
  10070. R32Float: 'r32float',
  10071. RG16Uint: 'rg16uint',
  10072. RG16Sint: 'rg16sint',
  10073. RG16Float: 'rg16float',
  10074. RGBA8Unorm: 'rgba8unorm',
  10075. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  10076. RGBA8Snorm: 'rgba8snorm',
  10077. RGBA8Uint: 'rgba8uint',
  10078. RGBA8Sint: 'rgba8sint',
  10079. BGRA8Unorm: 'bgra8unorm',
  10080. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  10081. // Packed 32-bit formats
  10082. RGB9E5UFloat: 'rgb9e5ufloat',
  10083. RGB10A2Unorm: 'rgb10a2unorm',
  10084. RG11B10uFloat: 'rgb10a2unorm',
  10085. // 64-bit formats
  10086. RG32Uint: 'rg32uint',
  10087. RG32Sint: 'rg32sint',
  10088. RG32Float: 'rg32float',
  10089. RGBA16Uint: 'rgba16uint',
  10090. RGBA16Sint: 'rgba16sint',
  10091. RGBA16Float: 'rgba16float',
  10092. // 128-bit formats
  10093. RGBA32Uint: 'rgba32uint',
  10094. RGBA32Sint: 'rgba32sint',
  10095. RGBA32Float: 'rgba32float',
  10096. // Depth and stencil formats
  10097. Stencil8: 'stencil8',
  10098. Depth16Unorm: 'depth16unorm',
  10099. Depth24Plus: 'depth24plus',
  10100. Depth24PlusStencil8: 'depth24plus-stencil8',
  10101. Depth32Float: 'depth32float',
  10102. // 'depth32float-stencil8' extension
  10103. Depth32FloatStencil8: 'depth32float-stencil8',
  10104. // BC compressed formats usable if 'texture-compression-bc' is both
  10105. // supported by the device/user agent and enabled in requestDevice.
  10106. BC1RGBAUnorm: 'bc1-rgba-unorm',
  10107. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  10108. BC2RGBAUnorm: 'bc2-rgba-unorm',
  10109. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  10110. BC3RGBAUnorm: 'bc3-rgba-unorm',
  10111. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  10112. BC4RUnorm: 'bc4-r-unorm',
  10113. BC4RSnorm: 'bc4-r-snorm',
  10114. BC5RGUnorm: 'bc5-rg-unorm',
  10115. BC5RGSnorm: 'bc5-rg-snorm',
  10116. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  10117. BC6HRGBFloat: 'bc6h-rgb-float',
  10118. BC7RGBAUnorm: 'bc7-rgba-unorm',
  10119. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  10120. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  10121. // supported by the device/user agent and enabled in requestDevice.
  10122. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  10123. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  10124. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  10125. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  10126. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  10127. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  10128. EACR11Unorm: 'eac-r11unorm',
  10129. EACR11Snorm: 'eac-r11snorm',
  10130. EACRG11Unorm: 'eac-rg11unorm',
  10131. EACRG11Snorm: 'eac-rg11snorm',
  10132. // ASTC compressed formats usable if 'texture-compression-astc' is both
  10133. // supported by the device/user agent and enabled in requestDevice.
  10134. ASTC4x4Unorm: 'astc-4x4-unorm',
  10135. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  10136. ASTC5x4Unorm: 'astc-5x4-unorm',
  10137. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  10138. ASTC5x5Unorm: 'astc-5x5-unorm',
  10139. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  10140. ASTC6x5Unorm: 'astc-6x5-unorm',
  10141. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  10142. ASTC6x6Unorm: 'astc-6x6-unorm',
  10143. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  10144. ASTC8x5Unorm: 'astc-8x5-unorm',
  10145. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  10146. ASTC8x6Unorm: 'astc-8x6-unorm',
  10147. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  10148. ASTC8x8Unorm: 'astc-8x8-unorm',
  10149. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  10150. ASTC10x5Unorm: 'astc-10x5-unorm',
  10151. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  10152. ASTC10x6Unorm: 'astc-10x6-unorm',
  10153. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  10154. ASTC10x8Unorm: 'astc-10x8-unorm',
  10155. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  10156. ASTC10x10Unorm: 'astc-10x10-unorm',
  10157. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  10158. ASTC12x10Unorm: 'astc-12x10-unorm',
  10159. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  10160. ASTC12x12Unorm: 'astc-12x12-unorm',
  10161. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  10162. };
  10163. const GPUAddressMode = {
  10164. ClampToEdge: 'clamp-to-edge',
  10165. Repeat: 'repeat',
  10166. MirrorRepeat: 'mirror-repeat'
  10167. };
  10168. const GPUFilterMode = {
  10169. Linear: 'linear',
  10170. Nearest: 'nearest'
  10171. };
  10172. const GPUBlendFactor = {
  10173. Zero: 'zero',
  10174. One: 'one',
  10175. Src: 'src',
  10176. OneMinusSrc: 'one-minus-src',
  10177. SrcAlpha: 'src-alpha',
  10178. OneMinusSrcAlpha: 'one-minus-src-alpha',
  10179. Dst: 'dst',
  10180. OneMinusDstColor: 'one-minus-dst',
  10181. DstAlpha: 'dst-alpha',
  10182. OneMinusDstAlpha: 'one-minus-dst-alpha',
  10183. SrcAlphaSaturated: 'src-alpha-saturated',
  10184. Constant: 'constant',
  10185. OneMinusConstant: 'one-minus-constant'
  10186. };
  10187. const GPUBlendOperation = {
  10188. Add: 'add',
  10189. Subtract: 'subtract',
  10190. ReverseSubtract: 'reverse-subtract',
  10191. Min: 'min',
  10192. Max: 'max'
  10193. };
  10194. const GPUColorWriteFlags = {
  10195. None: 0,
  10196. Red: 0x1,
  10197. Green: 0x2,
  10198. Blue: 0x4,
  10199. Alpha: 0x8,
  10200. All: 0xF
  10201. };
  10202. const GPUStencilOperation = {
  10203. Keep: 'keep',
  10204. Zero: 'zero',
  10205. Replace: 'replace',
  10206. Invert: 'invert',
  10207. IncrementClamp: 'increment-clamp',
  10208. DecrementClamp: 'decrement-clamp',
  10209. IncrementWrap: 'increment-wrap',
  10210. DecrementWrap: 'decrement-wrap'
  10211. };
  10212. const GPUBufferBindingType = {
  10213. Uniform: 'uniform',
  10214. Storage: 'storage',
  10215. ReadOnlyStorage: 'read-only-storage'
  10216. };
  10217. const GPUStorageTextureAccess = {
  10218. WriteOnly: 'write-only',
  10219. ReadOnly: 'read-only',
  10220. ReadWrite: 'read-write',
  10221. };
  10222. const GPUTextureSampleType = {
  10223. Float: 'float',
  10224. UnfilterableFloat: 'unfilterable-float',
  10225. Depth: 'depth',
  10226. SInt: 'sint',
  10227. UInt: 'uint'
  10228. };
  10229. const GPUTextureDimension = {
  10230. OneD: '1d',
  10231. TwoD: '2d',
  10232. ThreeD: '3d'
  10233. };
  10234. const GPUTextureViewDimension = {
  10235. OneD: '1d',
  10236. TwoD: '2d',
  10237. TwoDArray: '2d-array',
  10238. Cube: 'cube',
  10239. CubeArray: 'cube-array',
  10240. ThreeD: '3d'
  10241. };
  10242. const GPUTextureAspect = {
  10243. All: 'all',
  10244. StencilOnly: 'stencil-only',
  10245. DepthOnly: 'depth-only'
  10246. };
  10247. const GPUInputStepMode = {
  10248. Vertex: 'vertex',
  10249. Instance: 'instance'
  10250. };
  10251. const GPUFeatureName = {
  10252. DepthClipControl: 'depth-clip-control',
  10253. Depth32FloatStencil8: 'depth32float-stencil8',
  10254. TextureCompressionBC: 'texture-compression-bc',
  10255. TextureCompressionETC2: 'texture-compression-etc2',
  10256. TextureCompressionASTC: 'texture-compression-astc',
  10257. TimestampQuery: 'timestamp-query',
  10258. IndirectFirstInstance: 'indirect-first-instance',
  10259. ShaderF16: 'shader-f16',
  10260. RG11B10UFloat: 'rg11b10ufloat-renderable',
  10261. BGRA8UNormStorage: 'bgra8unorm-storage',
  10262. Float32Filterable: 'float32-filterable',
  10263. ClipDistances: 'clip-distances',
  10264. DualSourceBlending: 'dual-source-blending',
  10265. Subgroups: 'subgroups'
  10266. };
  10267. class StorageBufferNode extends BufferNode {
  10268. static get type() {
  10269. return 'StorageBufferNode';
  10270. }
  10271. constructor( value, bufferType, bufferCount = 0 ) {
  10272. super( value, bufferType, bufferCount );
  10273. this.isStorageBufferNode = true;
  10274. this.access = GPUBufferBindingType.Storage;
  10275. this.isAtomic = false;
  10276. this.bufferObject = false;
  10277. this.bufferCount = bufferCount;
  10278. this._attribute = null;
  10279. this._varying = null;
  10280. this.global = true;
  10281. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  10282. // TOOD: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  10283. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  10284. else value.isStorageBufferAttribute = true;
  10285. }
  10286. }
  10287. getHash( builder ) {
  10288. if ( this.bufferCount === 0 ) {
  10289. let bufferData = builder.globalCache.getData( this.value );
  10290. if ( bufferData === undefined ) {
  10291. bufferData = {
  10292. node: this
  10293. };
  10294. builder.globalCache.setData( this.value, bufferData );
  10295. }
  10296. return bufferData.node.uuid;
  10297. }
  10298. return this.uuid;
  10299. }
  10300. getInputType( /*builder*/ ) {
  10301. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  10302. }
  10303. element( indexNode ) {
  10304. return storageElement( this, indexNode );
  10305. }
  10306. setBufferObject( value ) {
  10307. this.bufferObject = value;
  10308. return this;
  10309. }
  10310. setAccess( value ) {
  10311. this.access = value;
  10312. return this;
  10313. }
  10314. toReadOnly() {
  10315. return this.setAccess( GPUBufferBindingType.ReadOnlyStorage );
  10316. }
  10317. setAtomic( value ) {
  10318. this.isAtomic = value;
  10319. return this;
  10320. }
  10321. toAtomic() {
  10322. return this.setAtomic( true );
  10323. }
  10324. getAttributeData() {
  10325. if ( this._attribute === null ) {
  10326. this._attribute = bufferAttribute( this.value );
  10327. this._varying = varying( this._attribute );
  10328. }
  10329. return {
  10330. attribute: this._attribute,
  10331. varying: this._varying
  10332. };
  10333. }
  10334. getNodeType( builder ) {
  10335. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  10336. return super.getNodeType( builder );
  10337. }
  10338. const { attribute } = this.getAttributeData();
  10339. return attribute.getNodeType( builder );
  10340. }
  10341. generate( builder ) {
  10342. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  10343. return super.generate( builder );
  10344. }
  10345. const { attribute, varying } = this.getAttributeData();
  10346. const output = varying.build( builder );
  10347. builder.registerTransform( output, attribute );
  10348. return output;
  10349. }
  10350. }
  10351. // Read-Write Storage
  10352. const storage = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ) );
  10353. const storageObject = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ).setBufferObject( true ) );
  10354. class StorageTextureNode extends TextureNode {
  10355. static get type() {
  10356. return 'StorageTextureNode';
  10357. }
  10358. constructor( value, uvNode, storeNode = null ) {
  10359. super( value, uvNode );
  10360. this.storeNode = storeNode;
  10361. this.isStorageTextureNode = true;
  10362. this.access = GPUStorageTextureAccess.WriteOnly;
  10363. }
  10364. getInputType( /*builder*/ ) {
  10365. return 'storageTexture';
  10366. }
  10367. setup( builder ) {
  10368. super.setup( builder );
  10369. const properties = builder.getNodeProperties( this );
  10370. properties.storeNode = this.storeNode;
  10371. }
  10372. setAccess( value ) {
  10373. this.access = value;
  10374. return this;
  10375. }
  10376. generate( builder, output ) {
  10377. let snippet;
  10378. if ( this.storeNode !== null ) {
  10379. snippet = this.generateStore( builder );
  10380. } else {
  10381. snippet = super.generate( builder, output );
  10382. }
  10383. return snippet;
  10384. }
  10385. toReadOnly() {
  10386. return this.setAccess( GPUStorageTextureAccess.ReadOnly );
  10387. }
  10388. toWriteOnly() {
  10389. return this.setAccess( GPUStorageTextureAccess.WriteOnly );
  10390. }
  10391. generateStore( builder ) {
  10392. const properties = builder.getNodeProperties( this );
  10393. const { uvNode, storeNode } = properties;
  10394. const textureProperty = super.generate( builder, 'property' );
  10395. const uvSnippet = uvNode.build( builder, 'uvec2' );
  10396. const storeSnippet = storeNode.build( builder, 'vec4' );
  10397. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, storeSnippet );
  10398. builder.addLineFlowCode( snippet, this );
  10399. }
  10400. }
  10401. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode );
  10402. const textureStore = ( value, uvNode, storeNode ) => {
  10403. const node = storageTexture( value, uvNode, storeNode );
  10404. if ( storeNode !== null ) node.append();
  10405. return node;
  10406. };
  10407. class UserDataNode extends ReferenceNode {
  10408. static get type() {
  10409. return 'UserDataNode';
  10410. }
  10411. constructor( property, inputType, userData = null ) {
  10412. super( property, inputType, userData );
  10413. this.userData = userData;
  10414. }
  10415. updateReference( state ) {
  10416. this.reference = this.userData !== null ? this.userData : state.object.userData;
  10417. return this.reference;
  10418. }
  10419. }
  10420. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  10421. const _objectData = new WeakMap();
  10422. class VelocityNode extends TempNode {
  10423. static get type() {
  10424. return 'VelocityNode';
  10425. }
  10426. constructor() {
  10427. super( 'vec2' );
  10428. this.projectionMatrix = null;
  10429. this.updateType = NodeUpdateType.OBJECT;
  10430. this.updateAfterType = NodeUpdateType.OBJECT;
  10431. this.previousModelWorldMatrix = uniform( new Matrix4() );
  10432. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  10433. this.previousCameraViewMatrix = uniform( new Matrix4() );
  10434. }
  10435. setProjectionMatrix( projectionMatrix ) {
  10436. this.projectionMatrix = projectionMatrix;
  10437. }
  10438. update( { frameId, camera, object } ) {
  10439. const previousModelMatrix = getPreviousMatrix( object );
  10440. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  10441. //
  10442. const cameraData = getData( camera );
  10443. if ( cameraData.frameId !== frameId ) {
  10444. cameraData.frameId = frameId;
  10445. if ( cameraData.previousProjectionMatrix === undefined ) {
  10446. cameraData.previousProjectionMatrix = new Matrix4();
  10447. cameraData.previousCameraViewMatrix = new Matrix4();
  10448. cameraData.currentProjectionMatrix = new Matrix4();
  10449. cameraData.currentCameraViewMatrix = new Matrix4();
  10450. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  10451. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  10452. } else {
  10453. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  10454. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  10455. }
  10456. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  10457. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  10458. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  10459. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  10460. }
  10461. }
  10462. updateAfter( { object } ) {
  10463. getPreviousMatrix( object ).copy( object.matrixWorld );
  10464. }
  10465. setup( /*builder*/ ) {
  10466. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  10467. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  10468. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  10469. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  10470. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  10471. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  10472. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  10473. return velocity;
  10474. }
  10475. }
  10476. function getData( object ) {
  10477. let objectData = _objectData.get( object );
  10478. if ( objectData === undefined ) {
  10479. objectData = {};
  10480. _objectData.set( object, objectData );
  10481. }
  10482. return objectData;
  10483. }
  10484. function getPreviousMatrix( object, index = 0 ) {
  10485. const objectData = getData( object );
  10486. let matrix = objectData[ index ];
  10487. if ( matrix === undefined ) {
  10488. objectData[ index ] = matrix = new Matrix4();
  10489. }
  10490. return matrix;
  10491. }
  10492. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  10493. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  10494. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  10495. } ).setLayout( {
  10496. name: 'blendBurn',
  10497. type: 'vec3',
  10498. inputs: [
  10499. { name: 'base', type: 'vec3' },
  10500. { name: 'blend', type: 'vec3' }
  10501. ]
  10502. } );
  10503. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  10504. return min$1( base.div( blend.oneMinus() ), 1.0 );
  10505. } ).setLayout( {
  10506. name: 'blendDodge',
  10507. type: 'vec3',
  10508. inputs: [
  10509. { name: 'base', type: 'vec3' },
  10510. { name: 'blend', type: 'vec3' }
  10511. ]
  10512. } );
  10513. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  10514. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  10515. } ).setLayout( {
  10516. name: 'blendScreen',
  10517. type: 'vec3',
  10518. inputs: [
  10519. { name: 'base', type: 'vec3' },
  10520. { name: 'blend', type: 'vec3' }
  10521. ]
  10522. } );
  10523. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  10524. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  10525. } ).setLayout( {
  10526. name: 'blendOverlay',
  10527. type: 'vec3',
  10528. inputs: [
  10529. { name: 'base', type: 'vec3' },
  10530. { name: 'blend', type: 'vec3' }
  10531. ]
  10532. } );
  10533. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  10534. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  10535. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  10536. } ).setLayout( {
  10537. name: 'blendColor',
  10538. type: 'vec4',
  10539. inputs: [
  10540. { name: 'base', type: 'vec4' },
  10541. { name: 'blend', type: 'vec4' }
  10542. ]
  10543. } );
  10544. // deprecated
  10545. const burn = ( ...params ) => { // @deprecated, r171
  10546. console.warn( 'THREE.TSL: "burn" has been renamed. Use "blendBurn" instead.' );
  10547. return blendBurn( params );
  10548. };
  10549. const dodge = ( ...params ) => { // @deprecated, r171
  10550. console.warn( 'THREE.TSL: "dodge" has been renamed. Use "blendDodge" instead.' );
  10551. return blendDodge( params );
  10552. };
  10553. const screen = ( ...params ) => { // @deprecated, r171
  10554. console.warn( 'THREE.TSL: "screen" has been renamed. Use "blendScreen" instead.' );
  10555. return blendScreen( params );
  10556. };
  10557. const overlay = ( ...params ) => { // @deprecated, r171
  10558. console.warn( 'THREE.TSL: "overlay" has been renamed. Use "blendOverlay" instead.' );
  10559. return blendOverlay( params );
  10560. };
  10561. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  10562. return luminance( color.rgb );
  10563. } );
  10564. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  10565. return adjustment.mix( luminance( color.rgb ), color.rgb );
  10566. } );
  10567. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  10568. const average = add( color.r, color.g, color.b ).div( 3.0 );
  10569. const mx = color.r.max( color.g.max( color.b ) );
  10570. const amt = mx.sub( average ).mul( adjustment ).mul( - 3.0 );
  10571. return mix( color.rgb, mx, amt );
  10572. } );
  10573. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  10574. const k = vec3( 0.57735, 0.57735, 0.57735 );
  10575. const cosAngle = adjustment.cos();
  10576. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  10577. } );
  10578. const luminance = (
  10579. color,
  10580. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  10581. ) => dot( color, luminanceCoefficients );
  10582. const threshold = ( color, threshold ) => mix( vec3( 0.0 ), color, luminance( color ).sub( threshold ).max( 0 ) );
  10583. /**
  10584. * Color Decision List (CDL) v1.2
  10585. *
  10586. * Compact representation of color grading information, defined by slope, offset, power, and
  10587. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  10588. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  10589. *
  10590. * @param {vec4} color Input (-Infinity < input < +Infinity)
  10591. * @param {number | vec3} slope Slope (0 ≤ slope < +Infinity)
  10592. * @param {number | vec3} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  10593. * @param {number | vec3} power Power (0 < power < +Infinity)
  10594. * @param {number} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  10595. * @param {vec3} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  10596. * @return Output, -Infinity < output < +Infinity
  10597. *
  10598. * References:
  10599. * - ASC CDL v1.2
  10600. * - https://blender.stackexchange.com/a/55239/43930
  10601. * - https://docs.acescentral.com/specifications/acescc/
  10602. */
  10603. const cdl = /*@__PURE__*/ Fn( ( [
  10604. color,
  10605. slope = vec3( 1 ),
  10606. offset = vec3( 0 ),
  10607. power = vec3( 1 ),
  10608. saturation = float( 1 ),
  10609. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  10610. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  10611. ] ) => {
  10612. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  10613. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  10614. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  10615. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  10616. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  10617. const pv = v.pow( power ).toVar();
  10618. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  10619. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  10620. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  10621. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  10622. return vec4( v.rgb, color.a );
  10623. } );
  10624. class PosterizeNode extends TempNode {
  10625. static get type() {
  10626. return 'PosterizeNode';
  10627. }
  10628. constructor( sourceNode, stepsNode ) {
  10629. super();
  10630. this.sourceNode = sourceNode;
  10631. this.stepsNode = stepsNode;
  10632. }
  10633. setup() {
  10634. const { sourceNode, stepsNode } = this;
  10635. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  10636. }
  10637. }
  10638. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode );
  10639. let _sharedFramebuffer = null;
  10640. class ViewportSharedTextureNode extends ViewportTextureNode {
  10641. static get type() {
  10642. return 'ViewportSharedTextureNode';
  10643. }
  10644. constructor( uvNode = screenUV, levelNode = null ) {
  10645. if ( _sharedFramebuffer === null ) {
  10646. _sharedFramebuffer = new FramebufferTexture();
  10647. }
  10648. super( uvNode, levelNode, _sharedFramebuffer );
  10649. }
  10650. updateReference() {
  10651. return this;
  10652. }
  10653. }
  10654. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode );
  10655. const _size = /*@__PURE__*/ new Vector2();
  10656. class PassTextureNode extends TextureNode {
  10657. static get type() {
  10658. return 'PassTextureNode';
  10659. }
  10660. constructor( passNode, texture ) {
  10661. super( texture );
  10662. this.passNode = passNode;
  10663. this.setUpdateMatrix( false );
  10664. }
  10665. setup( builder ) {
  10666. if ( builder.object.isQuadMesh ) this.passNode.build( builder );
  10667. return super.setup( builder );
  10668. }
  10669. clone() {
  10670. return new this.constructor( this.passNode, this.value );
  10671. }
  10672. }
  10673. class PassMultipleTextureNode extends PassTextureNode {
  10674. static get type() {
  10675. return 'PassMultipleTextureNode';
  10676. }
  10677. constructor( passNode, textureName, previousTexture = false ) {
  10678. super( passNode, null );
  10679. this.textureName = textureName;
  10680. this.previousTexture = previousTexture;
  10681. }
  10682. updateTexture() {
  10683. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  10684. }
  10685. setup( builder ) {
  10686. this.updateTexture();
  10687. return super.setup( builder );
  10688. }
  10689. clone() {
  10690. return new this.constructor( this.passNode, this.textureName, this.previousTexture );
  10691. }
  10692. }
  10693. class PassNode extends TempNode {
  10694. static get type() {
  10695. return 'PassNode';
  10696. }
  10697. constructor( scope, scene, camera, options = {} ) {
  10698. super( 'vec4' );
  10699. this.scope = scope;
  10700. this.scene = scene;
  10701. this.camera = camera;
  10702. this.options = options;
  10703. this._pixelRatio = 1;
  10704. this._width = 1;
  10705. this._height = 1;
  10706. const depthTexture = new DepthTexture();
  10707. depthTexture.isRenderTargetTexture = true;
  10708. //depthTexture.type = FloatType;
  10709. depthTexture.name = 'depth';
  10710. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  10711. renderTarget.texture.name = 'output';
  10712. renderTarget.depthTexture = depthTexture;
  10713. this.renderTarget = renderTarget;
  10714. this.updateBeforeType = NodeUpdateType.FRAME;
  10715. this._textures = {
  10716. output: renderTarget.texture,
  10717. depth: depthTexture
  10718. };
  10719. this._textureNodes = {};
  10720. this._linearDepthNodes = {};
  10721. this._viewZNodes = {};
  10722. this._previousTextures = {};
  10723. this._previousTextureNodes = {};
  10724. this._cameraNear = uniform( 0 );
  10725. this._cameraFar = uniform( 0 );
  10726. this._mrt = null;
  10727. this.isPassNode = true;
  10728. }
  10729. setMRT( mrt ) {
  10730. this._mrt = mrt;
  10731. return this;
  10732. }
  10733. getMRT() {
  10734. return this._mrt;
  10735. }
  10736. isGlobal() {
  10737. return true;
  10738. }
  10739. getTexture( name ) {
  10740. let texture = this._textures[ name ];
  10741. if ( texture === undefined ) {
  10742. const refTexture = this.renderTarget.texture;
  10743. texture = refTexture.clone();
  10744. texture.isRenderTargetTexture = true;
  10745. texture.name = name;
  10746. this._textures[ name ] = texture;
  10747. this.renderTarget.textures.push( texture );
  10748. }
  10749. return texture;
  10750. }
  10751. getPreviousTexture( name ) {
  10752. let texture = this._previousTextures[ name ];
  10753. if ( texture === undefined ) {
  10754. texture = this.getTexture( name ).clone();
  10755. texture.isRenderTargetTexture = true;
  10756. this._previousTextures[ name ] = texture;
  10757. }
  10758. return texture;
  10759. }
  10760. toggleTexture( name ) {
  10761. const prevTexture = this._previousTextures[ name ];
  10762. if ( prevTexture !== undefined ) {
  10763. const texture = this._textures[ name ];
  10764. const index = this.renderTarget.textures.indexOf( texture );
  10765. this.renderTarget.textures[ index ] = prevTexture;
  10766. this._textures[ name ] = prevTexture;
  10767. this._previousTextures[ name ] = texture;
  10768. this._textureNodes[ name ].updateTexture();
  10769. this._previousTextureNodes[ name ].updateTexture();
  10770. }
  10771. }
  10772. getTextureNode( name = 'output' ) {
  10773. let textureNode = this._textureNodes[ name ];
  10774. if ( textureNode === undefined ) {
  10775. textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  10776. textureNode.updateTexture();
  10777. this._textureNodes[ name ] = textureNode;
  10778. }
  10779. return textureNode;
  10780. }
  10781. getPreviousTextureNode( name = 'output' ) {
  10782. let textureNode = this._previousTextureNodes[ name ];
  10783. if ( textureNode === undefined ) {
  10784. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  10785. textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  10786. textureNode.updateTexture();
  10787. this._previousTextureNodes[ name ] = textureNode;
  10788. }
  10789. return textureNode;
  10790. }
  10791. getViewZNode( name = 'depth' ) {
  10792. let viewZNode = this._viewZNodes[ name ];
  10793. if ( viewZNode === undefined ) {
  10794. const cameraNear = this._cameraNear;
  10795. const cameraFar = this._cameraFar;
  10796. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  10797. }
  10798. return viewZNode;
  10799. }
  10800. getLinearDepthNode( name = 'depth' ) {
  10801. let linearDepthNode = this._linearDepthNodes[ name ];
  10802. if ( linearDepthNode === undefined ) {
  10803. const cameraNear = this._cameraNear;
  10804. const cameraFar = this._cameraFar;
  10805. const viewZNode = this.getViewZNode( name );
  10806. // TODO: just if ( builder.camera.isPerspectiveCamera )
  10807. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  10808. }
  10809. return linearDepthNode;
  10810. }
  10811. setup( { renderer } ) {
  10812. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  10813. // Disable MSAA for WebGL backend for now
  10814. if ( renderer.backend.isWebGLBackend === true ) {
  10815. this.renderTarget.samples = 0;
  10816. }
  10817. this.renderTarget.depthTexture.isMultisampleRenderTargetTexture = this.renderTarget.samples > 1;
  10818. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  10819. }
  10820. updateBefore( frame ) {
  10821. const { renderer } = frame;
  10822. const { scene, camera } = this;
  10823. this._pixelRatio = renderer.getPixelRatio();
  10824. const size = renderer.getSize( _size );
  10825. this.setSize( size.width, size.height );
  10826. const currentRenderTarget = renderer.getRenderTarget();
  10827. const currentMRT = renderer.getMRT();
  10828. this._cameraNear.value = camera.near;
  10829. this._cameraFar.value = camera.far;
  10830. for ( const name in this._previousTextures ) {
  10831. this.toggleTexture( name );
  10832. }
  10833. renderer.setRenderTarget( this.renderTarget );
  10834. renderer.setMRT( this._mrt );
  10835. renderer.render( scene, camera );
  10836. renderer.setRenderTarget( currentRenderTarget );
  10837. renderer.setMRT( currentMRT );
  10838. }
  10839. setSize( width, height ) {
  10840. this._width = width;
  10841. this._height = height;
  10842. const effectiveWidth = this._width * this._pixelRatio;
  10843. const effectiveHeight = this._height * this._pixelRatio;
  10844. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  10845. }
  10846. setPixelRatio( pixelRatio ) {
  10847. this._pixelRatio = pixelRatio;
  10848. this.setSize( this._width, this._height );
  10849. }
  10850. dispose() {
  10851. this.renderTarget.dispose();
  10852. }
  10853. }
  10854. PassNode.COLOR = 'color';
  10855. PassNode.DEPTH = 'depth';
  10856. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  10857. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  10858. const depthPass = ( scene, camera ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera ) );
  10859. class ToonOutlinePassNode extends PassNode {
  10860. static get type() {
  10861. return 'ToonOutlinePassNode';
  10862. }
  10863. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  10864. super( PassNode.COLOR, scene, camera );
  10865. this.colorNode = colorNode;
  10866. this.thicknessNode = thicknessNode;
  10867. this.alphaNode = alphaNode;
  10868. this._materialCache = new WeakMap();
  10869. }
  10870. updateBefore( frame ) {
  10871. const { renderer } = frame;
  10872. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  10873. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  10874. // only render outline for supported materials
  10875. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  10876. if ( material.wireframe === false ) {
  10877. const outlineMaterial = this._getOutlineMaterial( material );
  10878. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  10879. }
  10880. }
  10881. // default
  10882. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  10883. } );
  10884. super.updateBefore( frame );
  10885. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  10886. }
  10887. _createMaterial() {
  10888. const material = new NodeMaterial();
  10889. material.isMeshToonOutlineMaterial = true;
  10890. material.name = 'Toon_Outline';
  10891. material.side = BackSide;
  10892. // vertex node
  10893. const outlineNormal = normalLocal.negate();
  10894. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  10895. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  10896. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  10897. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  10898. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  10899. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  10900. // color node
  10901. material.colorNode = vec4( this.colorNode, this.alphaNode );
  10902. return material;
  10903. }
  10904. _getOutlineMaterial( originalMaterial ) {
  10905. let outlineMaterial = this._materialCache.get( originalMaterial );
  10906. if ( outlineMaterial === undefined ) {
  10907. outlineMaterial = this._createMaterial();
  10908. this._materialCache.set( originalMaterial, outlineMaterial );
  10909. }
  10910. return outlineMaterial;
  10911. }
  10912. }
  10913. 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 ) ) );
  10914. // exposure only
  10915. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  10916. return color.mul( exposure ).clamp();
  10917. } ).setLayout( {
  10918. name: 'linearToneMapping',
  10919. type: 'vec3',
  10920. inputs: [
  10921. { name: 'color', type: 'vec3' },
  10922. { name: 'exposure', type: 'float' }
  10923. ]
  10924. } );
  10925. // source: https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf
  10926. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  10927. color = color.mul( exposure );
  10928. return color.div( color.add( 1.0 ) ).clamp();
  10929. } ).setLayout( {
  10930. name: 'reinhardToneMapping',
  10931. type: 'vec3',
  10932. inputs: [
  10933. { name: 'color', type: 'vec3' },
  10934. { name: 'exposure', type: 'float' }
  10935. ]
  10936. } );
  10937. // source: http://filmicworlds.com/blog/filmic-tonemapping-operators/
  10938. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  10939. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  10940. color = color.mul( exposure );
  10941. color = color.sub( 0.004 ).max( 0.0 );
  10942. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  10943. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  10944. return a.div( b ).pow( 2.2 );
  10945. } ).setLayout( {
  10946. name: 'cineonToneMapping',
  10947. type: 'vec3',
  10948. inputs: [
  10949. { name: 'color', type: 'vec3' },
  10950. { name: 'exposure', type: 'float' }
  10951. ]
  10952. } );
  10953. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  10954. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  10955. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  10956. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  10957. return a.div( b );
  10958. } );
  10959. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  10960. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  10961. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  10962. const ACESInputMat = mat3(
  10963. 0.59719, 0.35458, 0.04823,
  10964. 0.07600, 0.90834, 0.01566,
  10965. 0.02840, 0.13383, 0.83777
  10966. );
  10967. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  10968. const ACESOutputMat = mat3(
  10969. 1.60475, - 0.53108, - 0.07367,
  10970. - 0.10208, 1.10813, - 0.00605,
  10971. - 0.00327, - 0.07276, 1.07602
  10972. );
  10973. color = color.mul( exposure ).div( 0.6 );
  10974. color = ACESInputMat.mul( color );
  10975. // Apply RRT and ODT
  10976. color = RRTAndODTFit( color );
  10977. color = ACESOutputMat.mul( color );
  10978. // Clamp to [0, 1]
  10979. return color.clamp();
  10980. } ).setLayout( {
  10981. name: 'acesFilmicToneMapping',
  10982. type: 'vec3',
  10983. inputs: [
  10984. { name: 'color', type: 'vec3' },
  10985. { name: 'exposure', type: 'float' }
  10986. ]
  10987. } );
  10988. 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 ) );
  10989. 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 ) );
  10990. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  10991. const x = vec3( x_immutable ).toVar();
  10992. const x2 = vec3( x.mul( x ) ).toVar();
  10993. const x4 = vec3( x2.mul( x2 ) ).toVar();
  10994. 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 ) ) ) );
  10995. } );
  10996. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  10997. const colortone = vec3( color ).toVar();
  10998. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  10999. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) );
  11000. const AgxMinEv = float( - 12.47393 );
  11001. const AgxMaxEv = float( 4.026069 );
  11002. colortone.mulAssign( exposure );
  11003. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  11004. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  11005. colortone.assign( max$1( colortone, 1e-10 ) );
  11006. colortone.assign( log2( colortone ) );
  11007. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  11008. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  11009. colortone.assign( agxDefaultContrastApprox( colortone ) );
  11010. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  11011. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  11012. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  11013. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  11014. return colortone;
  11015. } ).setLayout( {
  11016. name: 'agxToneMapping',
  11017. type: 'vec3',
  11018. inputs: [
  11019. { name: 'color', type: 'vec3' },
  11020. { name: 'exposure', type: 'float' }
  11021. ]
  11022. } );
  11023. // https://modelviewer.dev/examples/tone-mapping
  11024. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  11025. const StartCompression = float( 0.8 - 0.04 );
  11026. const Desaturation = float( 0.15 );
  11027. color = color.mul( exposure );
  11028. const x = min$1( color.r, min$1( color.g, color.b ) );
  11029. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  11030. color.subAssign( offset );
  11031. const peak = max$1( color.r, max$1( color.g, color.b ) );
  11032. If( peak.lessThan( StartCompression ), () => {
  11033. return color;
  11034. } );
  11035. const d = sub( 1, StartCompression );
  11036. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  11037. color.mulAssign( newPeak.div( peak ) );
  11038. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  11039. return mix( color, vec3( newPeak ), g );
  11040. } ).setLayout( {
  11041. name: 'neutralToneMapping',
  11042. type: 'vec3',
  11043. inputs: [
  11044. { name: 'color', type: 'vec3' },
  11045. { name: 'exposure', type: 'float' }
  11046. ]
  11047. } );
  11048. class CodeNode extends Node {
  11049. static get type() {
  11050. return 'CodeNode';
  11051. }
  11052. constructor( code = '', includes = [], language = '' ) {
  11053. super( 'code' );
  11054. this.isCodeNode = true;
  11055. this.code = code;
  11056. this.language = language;
  11057. this.includes = includes;
  11058. }
  11059. isGlobal() {
  11060. return true;
  11061. }
  11062. setIncludes( includes ) {
  11063. this.includes = includes;
  11064. return this;
  11065. }
  11066. getIncludes( /*builder*/ ) {
  11067. return this.includes;
  11068. }
  11069. generate( builder ) {
  11070. const includes = this.getIncludes( builder );
  11071. for ( const include of includes ) {
  11072. include.build( builder );
  11073. }
  11074. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  11075. nodeCode.code = this.code;
  11076. return nodeCode.code;
  11077. }
  11078. serialize( data ) {
  11079. super.serialize( data );
  11080. data.code = this.code;
  11081. data.language = this.language;
  11082. }
  11083. deserialize( data ) {
  11084. super.deserialize( data );
  11085. this.code = data.code;
  11086. this.language = data.language;
  11087. }
  11088. }
  11089. const code = /*@__PURE__*/ nodeProxy( CodeNode );
  11090. const js = ( src, includes ) => code( src, includes, 'js' );
  11091. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  11092. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  11093. class FunctionNode extends CodeNode {
  11094. static get type() {
  11095. return 'FunctionNode';
  11096. }
  11097. constructor( code = '', includes = [], language = '' ) {
  11098. super( code, includes, language );
  11099. }
  11100. getNodeType( builder ) {
  11101. return this.getNodeFunction( builder ).type;
  11102. }
  11103. getInputs( builder ) {
  11104. return this.getNodeFunction( builder ).inputs;
  11105. }
  11106. getNodeFunction( builder ) {
  11107. const nodeData = builder.getDataFromNode( this );
  11108. let nodeFunction = nodeData.nodeFunction;
  11109. if ( nodeFunction === undefined ) {
  11110. nodeFunction = builder.parser.parseFunction( this.code );
  11111. nodeData.nodeFunction = nodeFunction;
  11112. }
  11113. return nodeFunction;
  11114. }
  11115. generate( builder, output ) {
  11116. super.generate( builder );
  11117. const nodeFunction = this.getNodeFunction( builder );
  11118. const name = nodeFunction.name;
  11119. const type = nodeFunction.type;
  11120. const nodeCode = builder.getCodeFromNode( this, type );
  11121. if ( name !== '' ) {
  11122. // use a custom property name
  11123. nodeCode.name = name;
  11124. }
  11125. const propertyName = builder.getPropertyName( nodeCode );
  11126. const code = this.getNodeFunction( builder ).getCode( propertyName );
  11127. nodeCode.code = code + '\n';
  11128. if ( output === 'property' ) {
  11129. return propertyName;
  11130. } else {
  11131. return builder.format( `${ propertyName }()`, type, output );
  11132. }
  11133. }
  11134. }
  11135. const nativeFn = ( code, includes = [], language = '' ) => {
  11136. for ( let i = 0; i < includes.length; i ++ ) {
  11137. const include = includes[ i ];
  11138. // TSL Function: glslFn, wgslFn
  11139. if ( typeof include === 'function' ) {
  11140. includes[ i ] = include.functionNode;
  11141. }
  11142. }
  11143. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  11144. const fn = ( ...params ) => functionNode.call( ...params );
  11145. fn.functionNode = functionNode;
  11146. return fn;
  11147. };
  11148. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  11149. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  11150. class ScriptableValueNode extends Node {
  11151. static get type() {
  11152. return 'ScriptableValueNode';
  11153. }
  11154. constructor( value = null ) {
  11155. super();
  11156. this._value = value;
  11157. this._cache = null;
  11158. this.inputType = null;
  11159. this.outpuType = null;
  11160. this.events = new EventDispatcher();
  11161. this.isScriptableValueNode = true;
  11162. }
  11163. get isScriptableOutputNode() {
  11164. return this.outputType !== null;
  11165. }
  11166. set value( val ) {
  11167. if ( this._value === val ) return;
  11168. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  11169. URL.revokeObjectURL( this._cache );
  11170. this._cache = null;
  11171. }
  11172. this._value = val;
  11173. this.events.dispatchEvent( { type: 'change' } );
  11174. this.refresh();
  11175. }
  11176. get value() {
  11177. return this._value;
  11178. }
  11179. refresh() {
  11180. this.events.dispatchEvent( { type: 'refresh' } );
  11181. }
  11182. getValue() {
  11183. const value = this.value;
  11184. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  11185. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  11186. } else if ( value && value.value !== null && value.value !== undefined && (
  11187. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  11188. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  11189. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  11190. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  11191. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  11192. ( this.inputType === 'Color' && value.value.isColor ) ||
  11193. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  11194. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  11195. ) ) {
  11196. return value.value;
  11197. }
  11198. return this._cache || value;
  11199. }
  11200. getNodeType( builder ) {
  11201. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  11202. }
  11203. setup() {
  11204. return this.value && this.value.isNode ? this.value : float();
  11205. }
  11206. serialize( data ) {
  11207. super.serialize( data );
  11208. if ( this.value !== null ) {
  11209. if ( this.inputType === 'ArrayBuffer' ) {
  11210. data.value = arrayBufferToBase64( this.value );
  11211. } else {
  11212. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  11213. }
  11214. } else {
  11215. data.value = null;
  11216. }
  11217. data.inputType = this.inputType;
  11218. data.outputType = this.outputType;
  11219. }
  11220. deserialize( data ) {
  11221. super.deserialize( data );
  11222. let value = null;
  11223. if ( data.value !== null ) {
  11224. if ( data.inputType === 'ArrayBuffer' ) {
  11225. value = base64ToArrayBuffer( data.value );
  11226. } else if ( data.inputType === 'Texture' ) {
  11227. value = data.meta.textures[ data.value ];
  11228. } else {
  11229. value = data.meta.nodes[ data.value ] || null;
  11230. }
  11231. }
  11232. this.value = value;
  11233. this.inputType = data.inputType;
  11234. this.outputType = data.outputType;
  11235. }
  11236. }
  11237. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode );
  11238. class Resources extends Map {
  11239. get( key, callback = null, ...params ) {
  11240. if ( this.has( key ) ) return super.get( key );
  11241. if ( callback !== null ) {
  11242. const value = callback( ...params );
  11243. this.set( key, value );
  11244. return value;
  11245. }
  11246. }
  11247. }
  11248. class Parameters {
  11249. constructor( scriptableNode ) {
  11250. this.scriptableNode = scriptableNode;
  11251. }
  11252. get parameters() {
  11253. return this.scriptableNode.parameters;
  11254. }
  11255. get layout() {
  11256. return this.scriptableNode.getLayout();
  11257. }
  11258. getInputLayout( id ) {
  11259. return this.scriptableNode.getInputLayout( id );
  11260. }
  11261. get( name ) {
  11262. const param = this.parameters[ name ];
  11263. const value = param ? param.getValue() : null;
  11264. return value;
  11265. }
  11266. }
  11267. const ScriptableNodeResources = new Resources();
  11268. class ScriptableNode extends Node {
  11269. static get type() {
  11270. return 'ScriptableNode';
  11271. }
  11272. constructor( codeNode = null, parameters = {} ) {
  11273. super();
  11274. this.codeNode = codeNode;
  11275. this.parameters = parameters;
  11276. this._local = new Resources();
  11277. this._output = scriptableValue();
  11278. this._outputs = {};
  11279. this._source = this.source;
  11280. this._method = null;
  11281. this._object = null;
  11282. this._value = null;
  11283. this._needsOutputUpdate = true;
  11284. this.onRefresh = this.onRefresh.bind( this );
  11285. this.isScriptableNode = true;
  11286. }
  11287. get source() {
  11288. return this.codeNode ? this.codeNode.code : '';
  11289. }
  11290. setLocal( name, value ) {
  11291. return this._local.set( name, value );
  11292. }
  11293. getLocal( name ) {
  11294. return this._local.get( name );
  11295. }
  11296. onRefresh() {
  11297. this._refresh();
  11298. }
  11299. getInputLayout( id ) {
  11300. for ( const element of this.getLayout() ) {
  11301. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  11302. return element;
  11303. }
  11304. }
  11305. }
  11306. getOutputLayout( id ) {
  11307. for ( const element of this.getLayout() ) {
  11308. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  11309. return element;
  11310. }
  11311. }
  11312. }
  11313. setOutput( name, value ) {
  11314. const outputs = this._outputs;
  11315. if ( outputs[ name ] === undefined ) {
  11316. outputs[ name ] = scriptableValue( value );
  11317. } else {
  11318. outputs[ name ].value = value;
  11319. }
  11320. return this;
  11321. }
  11322. getOutput( name ) {
  11323. return this._outputs[ name ];
  11324. }
  11325. getParameter( name ) {
  11326. return this.parameters[ name ];
  11327. }
  11328. setParameter( name, value ) {
  11329. const parameters = this.parameters;
  11330. if ( value && value.isScriptableNode ) {
  11331. this.deleteParameter( name );
  11332. parameters[ name ] = value;
  11333. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  11334. } else if ( value && value.isScriptableValueNode ) {
  11335. this.deleteParameter( name );
  11336. parameters[ name ] = value;
  11337. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  11338. } else if ( parameters[ name ] === undefined ) {
  11339. parameters[ name ] = scriptableValue( value );
  11340. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  11341. } else {
  11342. parameters[ name ].value = value;
  11343. }
  11344. return this;
  11345. }
  11346. getValue() {
  11347. return this.getDefaultOutput().getValue();
  11348. }
  11349. deleteParameter( name ) {
  11350. let valueNode = this.parameters[ name ];
  11351. if ( valueNode ) {
  11352. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  11353. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  11354. }
  11355. return this;
  11356. }
  11357. clearParameters() {
  11358. for ( const name of Object.keys( this.parameters ) ) {
  11359. this.deleteParameter( name );
  11360. }
  11361. this.needsUpdate = true;
  11362. return this;
  11363. }
  11364. call( name, ...params ) {
  11365. const object = this.getObject();
  11366. const method = object[ name ];
  11367. if ( typeof method === 'function' ) {
  11368. return method( ...params );
  11369. }
  11370. }
  11371. async callAsync( name, ...params ) {
  11372. const object = this.getObject();
  11373. const method = object[ name ];
  11374. if ( typeof method === 'function' ) {
  11375. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  11376. }
  11377. }
  11378. getNodeType( builder ) {
  11379. return this.getDefaultOutputNode().getNodeType( builder );
  11380. }
  11381. refresh( output = null ) {
  11382. if ( output !== null ) {
  11383. this.getOutput( output ).refresh();
  11384. } else {
  11385. this._refresh();
  11386. }
  11387. }
  11388. getObject() {
  11389. if ( this.needsUpdate ) this.dispose();
  11390. if ( this._object !== null ) return this._object;
  11391. //
  11392. const refresh = () => this.refresh();
  11393. const setOutput = ( id, value ) => this.setOutput( id, value );
  11394. const parameters = new Parameters( this );
  11395. const THREE = ScriptableNodeResources.get( 'THREE' );
  11396. const TSL = ScriptableNodeResources.get( 'TSL' );
  11397. const method = this.getMethod( this.codeNode );
  11398. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  11399. this._object = method( ...params );
  11400. const layout = this._object.layout;
  11401. if ( layout ) {
  11402. if ( layout.cache === false ) {
  11403. this._local.clear();
  11404. }
  11405. // default output
  11406. this._output.outputType = layout.outputType || null;
  11407. if ( Array.isArray( layout.elements ) ) {
  11408. for ( const element of layout.elements ) {
  11409. const id = element.id || element.name;
  11410. if ( element.inputType ) {
  11411. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  11412. this.getParameter( id ).inputType = element.inputType;
  11413. }
  11414. if ( element.outputType ) {
  11415. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  11416. this.getOutput( id ).outputType = element.outputType;
  11417. }
  11418. }
  11419. }
  11420. }
  11421. return this._object;
  11422. }
  11423. deserialize( data ) {
  11424. super.deserialize( data );
  11425. for ( const name in this.parameters ) {
  11426. let valueNode = this.parameters[ name ];
  11427. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  11428. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  11429. }
  11430. }
  11431. getLayout() {
  11432. return this.getObject().layout;
  11433. }
  11434. getDefaultOutputNode() {
  11435. const output = this.getDefaultOutput().value;
  11436. if ( output && output.isNode ) {
  11437. return output;
  11438. }
  11439. return float();
  11440. }
  11441. getDefaultOutput() {
  11442. return this._exec()._output;
  11443. }
  11444. getMethod() {
  11445. if ( this.needsUpdate ) this.dispose();
  11446. if ( this._method !== null ) return this._method;
  11447. //
  11448. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  11449. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  11450. const properties = interfaceProps.join( ', ' );
  11451. const declarations = 'var ' + properties + '; var output = {};\n';
  11452. const returns = '\nreturn { ...output, ' + properties + ' };';
  11453. const code = declarations + this.codeNode.code + returns;
  11454. //
  11455. this._method = new Function( ...parametersProps, code );
  11456. return this._method;
  11457. }
  11458. dispose() {
  11459. if ( this._method === null ) return;
  11460. if ( this._object && typeof this._object.dispose === 'function' ) {
  11461. this._object.dispose();
  11462. }
  11463. this._method = null;
  11464. this._object = null;
  11465. this._source = null;
  11466. this._value = null;
  11467. this._needsOutputUpdate = true;
  11468. this._output.value = null;
  11469. this._outputs = {};
  11470. }
  11471. setup() {
  11472. return this.getDefaultOutputNode();
  11473. }
  11474. getCacheKey( force ) {
  11475. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  11476. for ( const param in this.parameters ) {
  11477. values.push( this.parameters[ param ].getCacheKey( force ) );
  11478. }
  11479. return hashArray( values );
  11480. }
  11481. set needsUpdate( value ) {
  11482. if ( value === true ) this.dispose();
  11483. }
  11484. get needsUpdate() {
  11485. return this.source !== this._source;
  11486. }
  11487. _exec() {
  11488. if ( this.codeNode === null ) return this;
  11489. if ( this._needsOutputUpdate === true ) {
  11490. this._value = this.call( 'main' );
  11491. this._needsOutputUpdate = false;
  11492. }
  11493. this._output.value = this._value;
  11494. return this;
  11495. }
  11496. _refresh() {
  11497. this.needsUpdate = true;
  11498. this._exec();
  11499. this._output.refresh();
  11500. }
  11501. }
  11502. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode );
  11503. class FogNode extends Node {
  11504. static get type() {
  11505. return 'FogNode';
  11506. }
  11507. constructor( colorNode, factorNode ) {
  11508. super( 'float' );
  11509. this.isFogNode = true;
  11510. this.colorNode = colorNode;
  11511. this.factorNode = factorNode;
  11512. }
  11513. getViewZNode( builder ) {
  11514. let viewZ;
  11515. const getViewZ = builder.context.getViewZ;
  11516. if ( getViewZ !== undefined ) {
  11517. viewZ = getViewZ( this );
  11518. }
  11519. return ( viewZ || positionView.z ).negate();
  11520. }
  11521. setup() {
  11522. return this.factorNode;
  11523. }
  11524. }
  11525. const fog = /*@__PURE__*/ nodeProxy( FogNode );
  11526. class FogRangeNode extends FogNode {
  11527. static get type() {
  11528. return 'FogRangeNode';
  11529. }
  11530. constructor( colorNode, nearNode, farNode ) {
  11531. super( colorNode );
  11532. this.isFogRangeNode = true;
  11533. this.nearNode = nearNode;
  11534. this.farNode = farNode;
  11535. }
  11536. setup( builder ) {
  11537. const viewZ = this.getViewZNode( builder );
  11538. return smoothstep( this.nearNode, this.farNode, viewZ );
  11539. }
  11540. }
  11541. const rangeFog = /*@__PURE__*/ nodeProxy( FogRangeNode );
  11542. class FogExp2Node extends FogNode {
  11543. static get type() {
  11544. return 'FogExp2Node';
  11545. }
  11546. constructor( colorNode, densityNode ) {
  11547. super( colorNode );
  11548. this.isFogExp2Node = true;
  11549. this.densityNode = densityNode;
  11550. }
  11551. setup( builder ) {
  11552. const viewZ = this.getViewZNode( builder );
  11553. const density = this.densityNode;
  11554. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  11555. }
  11556. }
  11557. const densityFog = /*@__PURE__*/ nodeProxy( FogExp2Node );
  11558. let min = null;
  11559. let max = null;
  11560. class RangeNode extends Node {
  11561. static get type() {
  11562. return 'RangeNode';
  11563. }
  11564. constructor( minNode = float(), maxNode = float() ) {
  11565. super();
  11566. this.minNode = minNode;
  11567. this.maxNode = maxNode;
  11568. }
  11569. getVectorLength( builder ) {
  11570. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  11571. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  11572. return minLength > maxLength ? minLength : maxLength;
  11573. }
  11574. getNodeType( builder ) {
  11575. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  11576. }
  11577. setup( builder ) {
  11578. const object = builder.object;
  11579. let output = null;
  11580. if ( object.count > 1 ) {
  11581. const minValue = this.minNode.value;
  11582. const maxValue = this.maxNode.value;
  11583. const minLength = builder.getTypeLength( getValueType( minValue ) );
  11584. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  11585. min = min || new Vector4();
  11586. max = max || new Vector4();
  11587. min.setScalar( 0 );
  11588. max.setScalar( 0 );
  11589. if ( minLength === 1 ) min.setScalar( minValue );
  11590. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b );
  11591. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  11592. if ( maxLength === 1 ) max.setScalar( maxValue );
  11593. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b );
  11594. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  11595. const stride = 4;
  11596. const length = stride * object.count;
  11597. const array = new Float32Array( length );
  11598. for ( let i = 0; i < length; i ++ ) {
  11599. const index = i % stride;
  11600. const minElementValue = min.getComponent( index );
  11601. const maxElementValue = max.getComponent( index );
  11602. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  11603. }
  11604. const nodeType = this.getNodeType( builder );
  11605. if ( object.count <= 4096 ) {
  11606. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  11607. } else {
  11608. // TODO: Improve anonymous buffer attribute creation removing this part
  11609. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  11610. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  11611. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  11612. }
  11613. } else {
  11614. output = float( 0 );
  11615. }
  11616. return output;
  11617. }
  11618. }
  11619. const range = /*@__PURE__*/ nodeProxy( RangeNode );
  11620. class ComputeBuiltinNode extends Node {
  11621. static get type() {
  11622. return 'ComputeBuiltinNode';
  11623. }
  11624. constructor( builtinName, nodeType ) {
  11625. super( nodeType );
  11626. this._builtinName = builtinName;
  11627. }
  11628. getHash( builder ) {
  11629. return this.getBuiltinName( builder );
  11630. }
  11631. getNodeType( /*builder*/ ) {
  11632. return this.nodeType;
  11633. }
  11634. setBuiltinName( builtinName ) {
  11635. this._builtinName = builtinName;
  11636. return this;
  11637. }
  11638. getBuiltinName( /*builder*/ ) {
  11639. return this._builtinName;
  11640. }
  11641. hasBuiltin( builder ) {
  11642. builder.hasBuiltin( this._builtinName );
  11643. }
  11644. generate( builder, output ) {
  11645. const builtinName = this.getBuiltinName( builder );
  11646. const nodeType = this.getNodeType( builder );
  11647. if ( builder.shaderStage === 'compute' ) {
  11648. return builder.format( builtinName, nodeType, output );
  11649. } else {
  11650. console.warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  11651. return builder.generateConst( nodeType );
  11652. }
  11653. }
  11654. serialize( data ) {
  11655. super.serialize( data );
  11656. data.global = this.global;
  11657. data._builtinName = this._builtinName;
  11658. }
  11659. deserialize( data ) {
  11660. super.deserialize( data );
  11661. this.global = data.global;
  11662. this._builtinName = data._builtinName;
  11663. }
  11664. }
  11665. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  11666. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  11667. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  11668. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  11669. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  11670. class BarrierNode extends Node {
  11671. constructor( scope ) {
  11672. super();
  11673. this.scope = scope;
  11674. }
  11675. generate( builder ) {
  11676. const { scope } = this;
  11677. const { renderer } = builder;
  11678. if ( renderer.backend.isWebGLBackend === true ) {
  11679. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  11680. } else {
  11681. builder.addLineFlowCode( `${scope}Barrier()`, this );
  11682. }
  11683. }
  11684. }
  11685. const barrier = nodeProxy( BarrierNode );
  11686. const workgroupBarrier = () => barrier( 'workgroup' ).append();
  11687. const storageBarrier = () => barrier( 'storage' ).append();
  11688. const textureBarrier = () => barrier( 'texture' ).append();
  11689. class WorkgroupInfoElementNode extends ArrayElementNode {
  11690. constructor( workgroupInfoNode, indexNode ) {
  11691. super( workgroupInfoNode, indexNode );
  11692. this.isWorkgroupInfoElementNode = true;
  11693. }
  11694. generate( builder, output ) {
  11695. let snippet;
  11696. const isAssignContext = builder.context.assign;
  11697. snippet = super.generate( builder );
  11698. if ( isAssignContext !== true ) {
  11699. const type = this.getNodeType( builder );
  11700. snippet = builder.format( snippet, type, output );
  11701. }
  11702. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  11703. return snippet;
  11704. }
  11705. }
  11706. class WorkgroupInfoNode extends Node {
  11707. constructor( scope, bufferType, bufferCount = 0 ) {
  11708. super( bufferType );
  11709. this.bufferType = bufferType;
  11710. this.bufferCount = bufferCount;
  11711. this.isWorkgroupInfoNode = true;
  11712. this.scope = scope;
  11713. }
  11714. label( name ) {
  11715. this.name = name;
  11716. return this;
  11717. }
  11718. getHash() {
  11719. return this.uuid;
  11720. }
  11721. setScope( scope ) {
  11722. this.scope = scope;
  11723. return this;
  11724. }
  11725. getInputType( /*builder*/ ) {
  11726. return `${this.scope}Array`;
  11727. }
  11728. element( indexNode ) {
  11729. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  11730. }
  11731. generate( builder ) {
  11732. return builder.getScopedArray( this.name || `${this.scope}Array_${this.id}`, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  11733. }
  11734. }
  11735. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  11736. class AtomicFunctionNode extends TempNode {
  11737. static get type() {
  11738. return 'AtomicFunctionNode';
  11739. }
  11740. constructor( method, pointerNode, valueNode, storeNode = null ) {
  11741. super( 'uint' );
  11742. this.method = method;
  11743. this.pointerNode = pointerNode;
  11744. this.valueNode = valueNode;
  11745. this.storeNode = storeNode;
  11746. }
  11747. getInputType( builder ) {
  11748. return this.pointerNode.getNodeType( builder );
  11749. }
  11750. getNodeType( builder ) {
  11751. return this.getInputType( builder );
  11752. }
  11753. generate( builder ) {
  11754. const method = this.method;
  11755. const type = this.getNodeType( builder );
  11756. const inputType = this.getInputType( builder );
  11757. const a = this.pointerNode;
  11758. const b = this.valueNode;
  11759. const params = [];
  11760. params.push( `&${ a.build( builder, inputType ) }` );
  11761. params.push( b.build( builder, inputType ) );
  11762. const methodSnippet = `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`;
  11763. if ( this.storeNode !== null ) {
  11764. const varSnippet = this.storeNode.build( builder, inputType );
  11765. builder.addLineFlowCode( `${varSnippet} = ${methodSnippet}`, this );
  11766. } else {
  11767. builder.addLineFlowCode( methodSnippet, this );
  11768. }
  11769. }
  11770. }
  11771. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  11772. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  11773. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  11774. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  11775. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  11776. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  11777. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  11778. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  11779. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  11780. const atomicNode = nodeProxy( AtomicFunctionNode );
  11781. const atomicFunc = ( method, pointerNode, valueNode, storeNode ) => {
  11782. const node = atomicNode( method, pointerNode, valueNode, storeNode );
  11783. node.append();
  11784. return node;
  11785. };
  11786. const atomicStore = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode, storeNode );
  11787. const atomicAdd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode, storeNode );
  11788. const atomicSub = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode, storeNode );
  11789. const atomicMax = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode, storeNode );
  11790. const atomicMin = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode, storeNode );
  11791. const atomicAnd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode, storeNode );
  11792. const atomicOr = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode, storeNode );
  11793. const atomicXor = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode, storeNode );
  11794. let uniformsLib;
  11795. function getLightData( light ) {
  11796. uniformsLib = uniformsLib || new WeakMap();
  11797. let uniforms = uniformsLib.get( light );
  11798. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  11799. return uniforms;
  11800. }
  11801. function lightPosition( light ) {
  11802. const data = getLightData( light );
  11803. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  11804. }
  11805. function lightTargetPosition( light ) {
  11806. const data = getLightData( light );
  11807. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  11808. }
  11809. function lightViewPosition( light ) {
  11810. const data = getLightData( light );
  11811. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  11812. self.value = self.value || new Vector3();
  11813. self.value.setFromMatrixPosition( light.matrixWorld );
  11814. self.value.applyMatrix4( camera.matrixWorldInverse );
  11815. } ) );
  11816. }
  11817. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  11818. const sortLights = ( lights ) => {
  11819. return lights.sort( ( a, b ) => a.id - b.id );
  11820. };
  11821. const getLightNodeById = ( id, lightNodes ) => {
  11822. for ( const lightNode of lightNodes ) {
  11823. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  11824. return lightNode;
  11825. }
  11826. }
  11827. return null;
  11828. };
  11829. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  11830. class LightsNode extends Node {
  11831. static get type() {
  11832. return 'LightsNode';
  11833. }
  11834. constructor() {
  11835. super( 'vec3' );
  11836. this.totalDiffuseNode = vec3().toVar( 'totalDiffuse' );
  11837. this.totalSpecularNode = vec3().toVar( 'totalSpecular' );
  11838. this.outgoingLightNode = vec3().toVar( 'outgoingLight' );
  11839. this._lights = [];
  11840. this._lightNodes = null;
  11841. this._lightNodesHash = null;
  11842. this.global = true;
  11843. }
  11844. getHash( builder ) {
  11845. if ( this._lightNodesHash === null ) {
  11846. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  11847. const hash = [];
  11848. for ( const lightNode of this._lightNodes ) {
  11849. hash.push( lightNode.getSelf().getHash() );
  11850. }
  11851. this._lightNodesHash = 'lights-' + hash.join( ',' );
  11852. }
  11853. return this._lightNodesHash;
  11854. }
  11855. analyze( builder ) {
  11856. const properties = builder.getDataFromNode( this );
  11857. for ( const node of properties.nodes ) {
  11858. node.build( builder );
  11859. }
  11860. }
  11861. setupLightsNode( builder ) {
  11862. const lightNodes = [];
  11863. const previousLightNodes = this._lightNodes;
  11864. const lights = sortLights( this._lights );
  11865. const nodeLibrary = builder.renderer.library;
  11866. for ( const light of lights ) {
  11867. if ( light.isNode ) {
  11868. lightNodes.push( nodeObject( light ) );
  11869. } else {
  11870. let lightNode = null;
  11871. if ( previousLightNodes !== null ) {
  11872. lightNode = getLightNodeById( light.id, previousLightNodes ); // resuse existing light node
  11873. }
  11874. if ( lightNode === null ) {
  11875. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  11876. if ( lightNodeClass === null ) {
  11877. console.warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  11878. continue;
  11879. }
  11880. let lightNode = null;
  11881. if ( ! _lightsNodeRef.has( light ) ) {
  11882. lightNode = nodeObject( new lightNodeClass( light ) );
  11883. _lightsNodeRef.set( light, lightNode );
  11884. } else {
  11885. lightNode = _lightsNodeRef.get( light );
  11886. }
  11887. lightNodes.push( lightNode );
  11888. }
  11889. }
  11890. }
  11891. this._lightNodes = lightNodes;
  11892. }
  11893. setupLights( builder, lightNodes ) {
  11894. for ( const lightNode of lightNodes ) {
  11895. lightNode.build( builder );
  11896. }
  11897. }
  11898. setup( builder ) {
  11899. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  11900. const context = builder.context;
  11901. const lightingModel = context.lightingModel;
  11902. let outgoingLightNode = this.outgoingLightNode;
  11903. if ( lightingModel ) {
  11904. const { _lightNodes, totalDiffuseNode, totalSpecularNode } = this;
  11905. context.outgoingLight = outgoingLightNode;
  11906. const stack = builder.addStack();
  11907. //
  11908. const properties = builder.getDataFromNode( this );
  11909. properties.nodes = stack.nodes;
  11910. //
  11911. lightingModel.start( context, stack, builder );
  11912. // lights
  11913. this.setupLights( builder, _lightNodes );
  11914. //
  11915. lightingModel.indirect( context, stack, builder );
  11916. //
  11917. const { backdrop, backdropAlpha } = context;
  11918. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  11919. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  11920. if ( backdrop !== null ) {
  11921. if ( backdropAlpha !== null ) {
  11922. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  11923. } else {
  11924. totalDiffuse = vec3( backdrop );
  11925. }
  11926. context.material.transparent = true;
  11927. }
  11928. totalDiffuseNode.assign( totalDiffuse );
  11929. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  11930. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  11931. //
  11932. lightingModel.finish( context, stack, builder );
  11933. //
  11934. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  11935. }
  11936. return outgoingLightNode;
  11937. }
  11938. setLights( lights ) {
  11939. this._lights = lights;
  11940. this._lightNodes = null;
  11941. this._lightNodesHash = null;
  11942. return this;
  11943. }
  11944. getLights() {
  11945. return this._lights;
  11946. }
  11947. get hasLights() {
  11948. return this._lights.length > 0;
  11949. }
  11950. }
  11951. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  11952. const shadowWorldPosition = /*@__PURE__*/ vec3().toVar( 'shadowWorldPosition' );
  11953. const linearDistance = /*@__PURE__*/ Fn( ( [ position, cameraNear, cameraFar ] ) => {
  11954. let dist = positionWorld.sub( position ).length();
  11955. dist = dist.sub( cameraNear ).div( cameraFar.sub( cameraNear ) );
  11956. dist = dist.saturate(); // clamp to [ 0, 1 ]
  11957. return dist;
  11958. } );
  11959. const linearShadowDistance = ( light ) => {
  11960. const camera = light.shadow.camera;
  11961. const nearDistance = reference( 'near', 'float', camera ).setGroup( renderGroup );
  11962. const farDistance = reference( 'far', 'float', camera ).setGroup( renderGroup );
  11963. const referencePosition = objectPosition( light );
  11964. return linearDistance( referencePosition, nearDistance, farDistance );
  11965. };
  11966. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord } ) => {
  11967. return texture( depthTexture, shadowCoord.xy ).compare( shadowCoord.z );
  11968. } );
  11969. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  11970. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  11971. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  11972. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  11973. const texelSize = vec2( 1 ).div( mapSize );
  11974. const dx0 = texelSize.x.negate().mul( radius );
  11975. const dy0 = texelSize.y.negate().mul( radius );
  11976. const dx1 = texelSize.x.mul( radius );
  11977. const dy1 = texelSize.y.mul( radius );
  11978. const dx2 = dx0.div( 2 );
  11979. const dy2 = dy0.div( 2 );
  11980. const dx3 = dx1.div( 2 );
  11981. const dy3 = dy1.div( 2 );
  11982. return add(
  11983. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  11984. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  11985. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  11986. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  11987. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  11988. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  11989. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  11990. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  11991. depthCompare( shadowCoord.xy, shadowCoord.z ),
  11992. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  11993. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  11994. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  11995. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  11996. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  11997. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  11998. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  11999. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  12000. ).mul( 1 / 17 );
  12001. } );
  12002. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  12003. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  12004. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  12005. const texelSize = vec2( 1 ).div( mapSize );
  12006. const dx = texelSize.x;
  12007. const dy = texelSize.y;
  12008. const uv = shadowCoord.xy;
  12009. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  12010. uv.subAssign( f.mul( texelSize ) );
  12011. return add(
  12012. depthCompare( uv, shadowCoord.z ),
  12013. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  12014. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  12015. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  12016. mix(
  12017. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  12018. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  12019. f.x
  12020. ),
  12021. mix(
  12022. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  12023. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  12024. f.x
  12025. ),
  12026. mix(
  12027. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  12028. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  12029. f.y
  12030. ),
  12031. mix(
  12032. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  12033. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  12034. f.y
  12035. ),
  12036. mix(
  12037. mix(
  12038. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  12039. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  12040. f.x
  12041. ),
  12042. mix(
  12043. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  12044. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  12045. f.x
  12046. ),
  12047. f.y
  12048. )
  12049. ).mul( 1 / 9 );
  12050. } );
  12051. // VSM
  12052. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord } ) => {
  12053. const occlusion = float( 1 ).toVar();
  12054. const distribution = texture( depthTexture ).uv( shadowCoord.xy ).rg;
  12055. const hardShadow = step( shadowCoord.z, distribution.x );
  12056. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  12057. const distance = shadowCoord.z.sub( distribution.x );
  12058. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  12059. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  12060. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  12061. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  12062. } );
  12063. return occlusion;
  12064. } );
  12065. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass } ) => {
  12066. const mean = float( 0 ).toVar();
  12067. const squaredMean = float( 0 ).toVar();
  12068. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  12069. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  12070. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  12071. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  12072. const depth = shadowPass.uv( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) ).x;
  12073. mean.addAssign( depth );
  12074. squaredMean.addAssign( depth.mul( depth ) );
  12075. } );
  12076. mean.divAssign( samples );
  12077. squaredMean.divAssign( samples );
  12078. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  12079. return vec2( mean, std_dev );
  12080. } );
  12081. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass } ) => {
  12082. const mean = float( 0 ).toVar();
  12083. const squaredMean = float( 0 ).toVar();
  12084. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  12085. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  12086. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  12087. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  12088. const distribution = shadowPass.uv( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  12089. mean.addAssign( distribution.x );
  12090. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  12091. } );
  12092. mean.divAssign( samples );
  12093. squaredMean.divAssign( samples );
  12094. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  12095. return vec2( mean, std_dev );
  12096. } );
  12097. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  12098. //
  12099. let _overrideMaterial = null;
  12100. const _quadMesh$1 = /*@__PURE__*/ new QuadMesh();
  12101. class ShadowNode extends Node {
  12102. static get type() {
  12103. return 'ShadowNode';
  12104. }
  12105. constructor( light, shadow = null ) {
  12106. super();
  12107. this.light = light;
  12108. this.shadow = shadow || light.shadow;
  12109. this.shadowMap = null;
  12110. this.vsmShadowMapVertical = null;
  12111. this.vsmShadowMapHorizontal = null;
  12112. this.vsmMaterialVertical = null;
  12113. this.vsmMaterialHorizontal = null;
  12114. this.updateBeforeType = NodeUpdateType.RENDER;
  12115. this._node = null;
  12116. this.isShadowNode = true;
  12117. }
  12118. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow } ) {
  12119. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  12120. .and( shadowCoord.x.lessThanEqual( 1 ) )
  12121. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  12122. .and( shadowCoord.y.lessThanEqual( 1 ) )
  12123. .and( shadowCoord.z.lessThanEqual( 1 ) );
  12124. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow } );
  12125. return frustumTest.select( shadowNode, float( 1 ) );
  12126. }
  12127. setupShadowCoord( builder, shadowPosition ) {
  12128. const { shadow } = this;
  12129. const { renderer } = builder;
  12130. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  12131. let shadowCoord = shadowPosition;
  12132. let coordZ;
  12133. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  12134. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  12135. coordZ = shadowCoord.z;
  12136. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  12137. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  12138. }
  12139. } else {
  12140. const w = shadowCoord.w;
  12141. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  12142. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  12143. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  12144. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  12145. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  12146. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  12147. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  12148. }
  12149. shadowCoord = vec3(
  12150. shadowCoord.x,
  12151. shadowCoord.y.oneMinus(), // follow webgpu standards
  12152. coordZ.add( bias )
  12153. );
  12154. return shadowCoord;
  12155. }
  12156. getShadowFilterFn( type ) {
  12157. return _shadowFilterLib[ type ];
  12158. }
  12159. setupShadow( builder ) {
  12160. const { renderer } = builder;
  12161. const { light, shadow } = this;
  12162. const shadowMapType = renderer.shadowMap.type;
  12163. if ( _overrideMaterial === null ) {
  12164. const depthNode = light.isPointLight ? linearShadowDistance( light ) : null;
  12165. _overrideMaterial = new NodeMaterial();
  12166. _overrideMaterial.fragmentNode = vec4( 0, 0, 0, 1 );
  12167. _overrideMaterial.depthNode = depthNode;
  12168. _overrideMaterial.isShadowNodeMaterial = true; // Use to avoid other overrideMaterial override material.fragmentNode unintentionally when using material.shadowNode
  12169. _overrideMaterial.name = 'ShadowMaterial';
  12170. }
  12171. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  12172. depthTexture.compareFunction = LessCompare;
  12173. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  12174. shadowMap.depthTexture = depthTexture;
  12175. shadow.camera.updateProjectionMatrix();
  12176. // VSM
  12177. if ( shadowMapType === VSMShadowMap ) {
  12178. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  12179. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  12180. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  12181. const shadowPassVertical = texture( depthTexture );
  12182. const shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  12183. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  12184. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  12185. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  12186. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  12187. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical } ).context( builder.getSharedContext() );
  12188. material.name = 'VSMVertical';
  12189. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  12190. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal } ).context( builder.getSharedContext() );
  12191. material.name = 'VSMHorizontal';
  12192. }
  12193. //
  12194. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  12195. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  12196. const shadowPosition = uniform( shadow.matrix ).setGroup( renderGroup ).mul( shadowWorldPosition.add( transformedNormalWorld.mul( normalBias ) ) );
  12197. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  12198. //
  12199. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  12200. if ( filterFn === null ) {
  12201. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  12202. }
  12203. const shadowDepthTexture = ( shadowMapType === VSMShadowMap ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  12204. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow } );
  12205. const shadowColor = texture( shadowMap.texture, shadowCoord );
  12206. const shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  12207. this.shadowMap = shadowMap;
  12208. this.shadow.map = shadowMap;
  12209. return shadowOutput;
  12210. }
  12211. setup( builder ) {
  12212. if ( builder.renderer.shadowMap.enabled === false ) return;
  12213. return Fn( ( { material } ) => {
  12214. shadowWorldPosition.assign( material.shadowPositionNode || positionWorld );
  12215. let node = this._node;
  12216. if ( node === null ) {
  12217. this._node = node = this.setupShadow( builder );
  12218. }
  12219. if ( builder.material.shadowNode ) { // @deprecated, r171
  12220. console.warn( 'THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.' );
  12221. }
  12222. if ( builder.material.receivedShadowNode ) {
  12223. node = builder.material.receivedShadowNode( node );
  12224. }
  12225. return node;
  12226. } )();
  12227. }
  12228. renderShadow( frame ) {
  12229. const { shadow, shadowMap, light } = this;
  12230. const { renderer, scene } = frame;
  12231. shadow.updateMatrices( light );
  12232. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height );
  12233. renderer.render( scene, shadow.camera );
  12234. }
  12235. updateShadow( frame ) {
  12236. const { shadowMap, light, shadow } = this;
  12237. const { renderer, scene, camera } = frame;
  12238. const shadowType = renderer.shadowMap.type;
  12239. const depthVersion = shadowMap.depthTexture.version;
  12240. this._depthVersionCached = depthVersion;
  12241. const currentOverrideMaterial = scene.overrideMaterial;
  12242. scene.overrideMaterial = _overrideMaterial;
  12243. shadow.camera.layers.mask = camera.layers.mask;
  12244. const currentRenderTarget = renderer.getRenderTarget();
  12245. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  12246. renderer.setRenderObjectFunction( ( object, ...params ) => {
  12247. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  12248. renderer.renderObject( object, ...params );
  12249. }
  12250. } );
  12251. renderer.setRenderTarget( shadowMap );
  12252. this.renderShadow( frame );
  12253. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  12254. // vsm blur pass
  12255. if ( light.isPointLight !== true && shadowType === VSMShadowMap ) {
  12256. this.vsmPass( renderer );
  12257. }
  12258. renderer.setRenderTarget( currentRenderTarget );
  12259. scene.overrideMaterial = currentOverrideMaterial;
  12260. }
  12261. vsmPass( renderer ) {
  12262. const { shadow } = this;
  12263. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height );
  12264. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height );
  12265. renderer.setRenderTarget( this.vsmShadowMapVertical );
  12266. _quadMesh$1.material = this.vsmMaterialVertical;
  12267. _quadMesh$1.render( renderer );
  12268. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  12269. _quadMesh$1.material = this.vsmMaterialHorizontal;
  12270. _quadMesh$1.render( renderer );
  12271. }
  12272. dispose() {
  12273. this.shadowMap.dispose();
  12274. this.shadowMap = null;
  12275. if ( this.vsmShadowMapVertical !== null ) {
  12276. this.vsmShadowMapVertical.dispose();
  12277. this.vsmShadowMapVertical = null;
  12278. this.vsmMaterialVertical.dispose();
  12279. this.vsmMaterialVertical = null;
  12280. }
  12281. if ( this.vsmShadowMapHorizontal !== null ) {
  12282. this.vsmShadowMapHorizontal.dispose();
  12283. this.vsmShadowMapHorizontal = null;
  12284. this.vsmMaterialHorizontal.dispose();
  12285. this.vsmMaterialHorizontal = null;
  12286. }
  12287. this.updateBeforeType = NodeUpdateType.NONE;
  12288. }
  12289. updateBefore( frame ) {
  12290. const { shadow } = this;
  12291. const needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  12292. if ( needsUpdate ) {
  12293. this.updateShadow( frame );
  12294. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  12295. shadow.needsUpdate = false;
  12296. }
  12297. }
  12298. }
  12299. }
  12300. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  12301. class AnalyticLightNode extends LightingNode {
  12302. static get type() {
  12303. return 'AnalyticLightNode';
  12304. }
  12305. constructor( light = null ) {
  12306. super();
  12307. this.updateType = NodeUpdateType.FRAME;
  12308. this.light = light;
  12309. this.color = new Color();
  12310. this.colorNode = uniform( this.color ).setGroup( renderGroup );
  12311. this.baseColorNode = null;
  12312. this.shadowNode = null;
  12313. this.shadowColorNode = null;
  12314. this.isAnalyticLightNode = true;
  12315. }
  12316. getCacheKey() {
  12317. return hash$1( super.getCacheKey(), this.light.id, this.light.castShadow ? 1 : 0 );
  12318. }
  12319. getHash() {
  12320. return this.light.uuid;
  12321. }
  12322. setupShadowNode() {
  12323. return shadow( this.light );
  12324. }
  12325. setupShadow( builder ) {
  12326. const { renderer } = builder;
  12327. if ( renderer.shadowMap.enabled === false ) return;
  12328. let shadowColorNode = this.shadowColorNode;
  12329. if ( shadowColorNode === null ) {
  12330. const customShadowNode = this.light.shadow.shadowNode;
  12331. let shadowNode;
  12332. if ( customShadowNode !== undefined ) {
  12333. shadowNode = nodeObject( customShadowNode );
  12334. } else {
  12335. shadowNode = this.setupShadowNode( builder );
  12336. }
  12337. this.shadowNode = shadowNode;
  12338. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  12339. this.baseColorNode = this.colorNode;
  12340. }
  12341. //
  12342. this.colorNode = shadowColorNode;
  12343. }
  12344. setup( builder ) {
  12345. this.colorNode = this.baseColorNode || this.colorNode;
  12346. if ( this.light.castShadow ) {
  12347. if ( builder.object.receiveShadow ) {
  12348. this.setupShadow( builder );
  12349. }
  12350. } else if ( this.shadowNode !== null ) {
  12351. this.shadowNode.dispose();
  12352. this.shadowNode = null;
  12353. this.shadowColorNode = null;
  12354. }
  12355. }
  12356. update( /*frame*/ ) {
  12357. const { light } = this;
  12358. this.color.copy( light.color ).multiplyScalar( light.intensity );
  12359. }
  12360. }
  12361. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( inputs ) => {
  12362. const { lightDistance, cutoffDistance, decayExponent } = inputs;
  12363. // based upon Frostbite 3 Moving to Physically-based Rendering
  12364. // page 32, equation 26: E[window1]
  12365. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  12366. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  12367. return cutoffDistance.greaterThan( 0 ).select(
  12368. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  12369. distanceFalloff
  12370. );
  12371. } ); // validated
  12372. const _clearColor$2 = /*@__PURE__*/ new Color();
  12373. // cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D
  12374. // vector suitable for 2D texture mapping. This code uses the following layout for the
  12375. // 2D texture:
  12376. //
  12377. // xzXZ
  12378. // y Y
  12379. //
  12380. // Y - Positive y direction
  12381. // y - Negative y direction
  12382. // X - Positive x direction
  12383. // x - Negative x direction
  12384. // Z - Positive z direction
  12385. // z - Negative z direction
  12386. //
  12387. // Source and test bed:
  12388. // https://gist.github.com/tschw/da10c43c467ce8afd0c4
  12389. const cubeToUV = /*@__PURE__*/ Fn( ( [ pos, texelSizeY ] ) => {
  12390. const v = pos.toVar();
  12391. // Number of texels to avoid at the edge of each square
  12392. const absV = abs( v );
  12393. // Intersect unit cube
  12394. const scaleToCube = div( 1.0, max$1( absV.x, max$1( absV.y, absV.z ) ) );
  12395. absV.mulAssign( scaleToCube );
  12396. // Apply scale to avoid seams
  12397. // two texels less per square (one texel will do for NEAREST)
  12398. v.mulAssign( scaleToCube.mul( texelSizeY.mul( 2 ).oneMinus() ) );
  12399. // Unwrap
  12400. // space: -1 ... 1 range for each square
  12401. //
  12402. // #X## dim := ( 4 , 2 )
  12403. // # # center := ( 1 , 1 )
  12404. const planar = vec2( v.xy ).toVar();
  12405. const almostATexel = texelSizeY.mul( 1.5 );
  12406. const almostOne = almostATexel.oneMinus();
  12407. If( absV.z.greaterThanEqual( almostOne ), () => {
  12408. If( v.z.greaterThan( 0.0 ), () => {
  12409. planar.x.assign( sub( 4.0, v.x ) );
  12410. } );
  12411. } ).ElseIf( absV.x.greaterThanEqual( almostOne ), () => {
  12412. const signX = sign( v.x );
  12413. planar.x.assign( v.z.mul( signX ).add( signX.mul( 2.0 ) ) );
  12414. } ).ElseIf( absV.y.greaterThanEqual( almostOne ), () => {
  12415. const signY = sign( v.y );
  12416. planar.x.assign( v.x.add( signY.mul( 2.0 ) ).add( 2.0 ) );
  12417. planar.y.assign( v.z.mul( signY ).sub( 2.0 ) );
  12418. } );
  12419. // Transform to UV space
  12420. // scale := 0.5 / dim
  12421. // translate := ( center + 0.5 ) / dim
  12422. return vec2( 0.125, 0.25 ).mul( planar ).add( vec2( 0.375, 0.75 ) ).flipY();
  12423. } ).setLayout( {
  12424. name: 'cubeToUV',
  12425. type: 'vec2',
  12426. inputs: [
  12427. { name: 'pos', type: 'vec3' },
  12428. { name: 'texelSizeY', type: 'float' }
  12429. ]
  12430. } );
  12431. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize } ) => {
  12432. return texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp );
  12433. } );
  12434. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize, shadow } ) => {
  12435. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  12436. const offset = vec2( - 1.0, 1.0 ).mul( radius ).mul( texelSize.y );
  12437. return texture( depthTexture, cubeToUV( bd3D.add( offset.xyy ), texelSize.y ) ).compare( dp )
  12438. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyy ), texelSize.y ) ).compare( dp ) )
  12439. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xyx ), texelSize.y ) ).compare( dp ) )
  12440. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyx ), texelSize.y ) ).compare( dp ) )
  12441. .add( texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp ) )
  12442. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxy ), texelSize.y ) ).compare( dp ) )
  12443. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxy ), texelSize.y ) ).compare( dp ) )
  12444. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxx ), texelSize.y ) ).compare( dp ) )
  12445. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxx ), texelSize.y ) ).compare( dp ) )
  12446. .mul( 1.0 / 9.0 );
  12447. } );
  12448. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow } ) => {
  12449. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  12450. // the vector from the light to the world-space position of the fragment.
  12451. const lightToPosition = shadowCoord.xyz.toVar();
  12452. const lightToPositionLength = lightToPosition.length();
  12453. const cameraNearLocal = uniform( 'float' ).onRenderUpdate( () => shadow.camera.near );
  12454. const cameraFarLocal = uniform( 'float' ).onRenderUpdate( () => shadow.camera.far );
  12455. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  12456. const mapSize = uniform( shadow.mapSize ).setGroup( renderGroup );
  12457. const result = float( 1.0 ).toVar();
  12458. If( lightToPositionLength.sub( cameraFarLocal ).lessThanEqual( 0.0 ).and( lightToPositionLength.sub( cameraNearLocal ).greaterThanEqual( 0.0 ) ), () => {
  12459. // dp = normalized distance from light to fragment position
  12460. const dp = lightToPositionLength.sub( cameraNearLocal ).div( cameraFarLocal.sub( cameraNearLocal ) ).toVar(); // need to clamp?
  12461. dp.addAssign( bias );
  12462. // bd3D = base direction 3D
  12463. const bd3D = lightToPosition.normalize();
  12464. const texelSize = vec2( 1.0 ).div( mapSize.mul( vec2( 4.0, 2.0 ) ) );
  12465. // percentage-closer filtering
  12466. result.assign( filterFn( { depthTexture, bd3D, dp, texelSize, shadow } ) );
  12467. } );
  12468. return result;
  12469. } );
  12470. const _viewport = /*@__PURE__*/ new Vector4();
  12471. const _viewportSize = /*@__PURE__*/ new Vector2();
  12472. const _shadowMapSize = /*@__PURE__*/ new Vector2();
  12473. //
  12474. class PointShadowNode extends ShadowNode {
  12475. static get type() {
  12476. return 'PointShadowNode';
  12477. }
  12478. constructor( light, shadow = null ) {
  12479. super( light, shadow );
  12480. }
  12481. getShadowFilterFn( type ) {
  12482. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  12483. }
  12484. setupShadowCoord( builder, shadowPosition ) {
  12485. return shadowPosition;
  12486. }
  12487. setupShadowFilter( builder, { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } ) {
  12488. return pointShadowFilter( { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } );
  12489. }
  12490. renderShadow( frame ) {
  12491. const { shadow, shadowMap, light } = this;
  12492. const { renderer, scene } = frame;
  12493. const shadowFrameExtents = shadow.getFrameExtents();
  12494. _shadowMapSize.copy( shadow.mapSize );
  12495. _shadowMapSize.multiply( shadowFrameExtents );
  12496. shadowMap.setSize( _shadowMapSize.width, _shadowMapSize.height );
  12497. _viewportSize.copy( shadow.mapSize );
  12498. //
  12499. const previousAutoClear = renderer.autoClear;
  12500. const previousClearColor = renderer.getClearColor( _clearColor$2 );
  12501. const previousClearAlpha = renderer.getClearAlpha();
  12502. renderer.autoClear = false;
  12503. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  12504. renderer.clear();
  12505. const viewportCount = shadow.getViewportCount();
  12506. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  12507. const viewport = shadow.getViewport( vp );
  12508. const x = _viewportSize.x * viewport.x;
  12509. const y = _shadowMapSize.y - _viewportSize.y - ( _viewportSize.y * viewport.y );
  12510. _viewport.set(
  12511. x,
  12512. y,
  12513. _viewportSize.x * viewport.z,
  12514. _viewportSize.y * viewport.w
  12515. );
  12516. shadowMap.viewport.copy( _viewport );
  12517. shadow.updateMatrices( light, vp );
  12518. renderer.render( scene, shadow.camera );
  12519. }
  12520. //
  12521. renderer.autoClear = previousAutoClear;
  12522. renderer.setClearColor( previousClearColor, previousClearAlpha );
  12523. }
  12524. }
  12525. const pointShadow = ( light, shadow ) => nodeObject( new PointShadowNode( light, shadow ) );
  12526. const directPointLight = Fn( ( { color, lightViewPosition, cutoffDistance, decayExponent }, builder ) => {
  12527. const lightingModel = builder.context.lightingModel;
  12528. const lVector = lightViewPosition.sub( positionView ); // @TODO: Add it into LightNode
  12529. const lightDirection = lVector.normalize();
  12530. const lightDistance = lVector.length();
  12531. const lightAttenuation = getDistanceAttenuation( {
  12532. lightDistance,
  12533. cutoffDistance,
  12534. decayExponent
  12535. } );
  12536. const lightColor = color.mul( lightAttenuation );
  12537. const reflectedLight = builder.context.reflectedLight;
  12538. lightingModel.direct( {
  12539. lightDirection,
  12540. lightColor,
  12541. reflectedLight
  12542. }, builder.stack, builder );
  12543. } );
  12544. class PointLightNode extends AnalyticLightNode {
  12545. static get type() {
  12546. return 'PointLightNode';
  12547. }
  12548. constructor( light = null ) {
  12549. super( light );
  12550. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  12551. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  12552. }
  12553. update( frame ) {
  12554. const { light } = this;
  12555. super.update( frame );
  12556. this.cutoffDistanceNode.value = light.distance;
  12557. this.decayExponentNode.value = light.decay;
  12558. }
  12559. setupShadowNode() {
  12560. return pointShadow( this.light );
  12561. }
  12562. setup( builder ) {
  12563. super.setup( builder );
  12564. directPointLight( {
  12565. color: this.colorNode,
  12566. lightViewPosition: lightViewPosition( this.light ),
  12567. cutoffDistance: this.cutoffDistanceNode,
  12568. decayExponent: this.decayExponentNode
  12569. } ).append();
  12570. }
  12571. }
  12572. const checker = /*@__PURE__*/ Fn( ( [ coord = uv() ] ) => {
  12573. const uv = coord.mul( 2.0 );
  12574. const cx = uv.x.floor();
  12575. const cy = uv.y.floor();
  12576. const result = cx.add( cy ).mod( 2.0 );
  12577. return result.sign();
  12578. } );
  12579. // Three.js Transpiler
  12580. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  12581. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  12582. const f = float( f_immutable ).toVar();
  12583. const t = float( t_immutable ).toVar();
  12584. const b = bool( b_immutable ).toVar();
  12585. return select( b, t, f );
  12586. } ).setLayout( {
  12587. name: 'mx_select',
  12588. type: 'float',
  12589. inputs: [
  12590. { name: 'b', type: 'bool' },
  12591. { name: 't', type: 'float' },
  12592. { name: 'f', type: 'float' }
  12593. ]
  12594. } );
  12595. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  12596. const b = bool( b_immutable ).toVar();
  12597. const val = float( val_immutable ).toVar();
  12598. return select( b, val.negate(), val );
  12599. } ).setLayout( {
  12600. name: 'mx_negate_if',
  12601. type: 'float',
  12602. inputs: [
  12603. { name: 'val', type: 'float' },
  12604. { name: 'b', type: 'bool' }
  12605. ]
  12606. } );
  12607. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  12608. const x = float( x_immutable ).toVar();
  12609. return int( floor( x ) );
  12610. } ).setLayout( {
  12611. name: 'mx_floor',
  12612. type: 'int',
  12613. inputs: [
  12614. { name: 'x', type: 'float' }
  12615. ]
  12616. } );
  12617. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  12618. const x = float( x_immutable ).toVar();
  12619. i.assign( mx_floor( x ) );
  12620. return x.sub( float( i ) );
  12621. } );
  12622. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  12623. const t = float( t_immutable ).toVar();
  12624. const s = float( s_immutable ).toVar();
  12625. const v3 = float( v3_immutable ).toVar();
  12626. const v2 = float( v2_immutable ).toVar();
  12627. const v1 = float( v1_immutable ).toVar();
  12628. const v0 = float( v0_immutable ).toVar();
  12629. const s1 = float( sub( 1.0, s ) ).toVar();
  12630. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  12631. } ).setLayout( {
  12632. name: 'mx_bilerp_0',
  12633. type: 'float',
  12634. inputs: [
  12635. { name: 'v0', type: 'float' },
  12636. { name: 'v1', type: 'float' },
  12637. { name: 'v2', type: 'float' },
  12638. { name: 'v3', type: 'float' },
  12639. { name: 's', type: 'float' },
  12640. { name: 't', type: 'float' }
  12641. ]
  12642. } );
  12643. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  12644. const t = float( t_immutable ).toVar();
  12645. const s = float( s_immutable ).toVar();
  12646. const v3 = vec3( v3_immutable ).toVar();
  12647. const v2 = vec3( v2_immutable ).toVar();
  12648. const v1 = vec3( v1_immutable ).toVar();
  12649. const v0 = vec3( v0_immutable ).toVar();
  12650. const s1 = float( sub( 1.0, s ) ).toVar();
  12651. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  12652. } ).setLayout( {
  12653. name: 'mx_bilerp_1',
  12654. type: 'vec3',
  12655. inputs: [
  12656. { name: 'v0', type: 'vec3' },
  12657. { name: 'v1', type: 'vec3' },
  12658. { name: 'v2', type: 'vec3' },
  12659. { name: 'v3', type: 'vec3' },
  12660. { name: 's', type: 'float' },
  12661. { name: 't', type: 'float' }
  12662. ]
  12663. } );
  12664. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  12665. 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 ] ) => {
  12666. const r = float( r_immutable ).toVar();
  12667. const t = float( t_immutable ).toVar();
  12668. const s = float( s_immutable ).toVar();
  12669. const v7 = float( v7_immutable ).toVar();
  12670. const v6 = float( v6_immutable ).toVar();
  12671. const v5 = float( v5_immutable ).toVar();
  12672. const v4 = float( v4_immutable ).toVar();
  12673. const v3 = float( v3_immutable ).toVar();
  12674. const v2 = float( v2_immutable ).toVar();
  12675. const v1 = float( v1_immutable ).toVar();
  12676. const v0 = float( v0_immutable ).toVar();
  12677. const s1 = float( sub( 1.0, s ) ).toVar();
  12678. const t1 = float( sub( 1.0, t ) ).toVar();
  12679. const r1 = float( sub( 1.0, r ) ).toVar();
  12680. 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 ) ) ) ) ) );
  12681. } ).setLayout( {
  12682. name: 'mx_trilerp_0',
  12683. type: 'float',
  12684. inputs: [
  12685. { name: 'v0', type: 'float' },
  12686. { name: 'v1', type: 'float' },
  12687. { name: 'v2', type: 'float' },
  12688. { name: 'v3', type: 'float' },
  12689. { name: 'v4', type: 'float' },
  12690. { name: 'v5', type: 'float' },
  12691. { name: 'v6', type: 'float' },
  12692. { name: 'v7', type: 'float' },
  12693. { name: 's', type: 'float' },
  12694. { name: 't', type: 'float' },
  12695. { name: 'r', type: 'float' }
  12696. ]
  12697. } );
  12698. 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 ] ) => {
  12699. const r = float( r_immutable ).toVar();
  12700. const t = float( t_immutable ).toVar();
  12701. const s = float( s_immutable ).toVar();
  12702. const v7 = vec3( v7_immutable ).toVar();
  12703. const v6 = vec3( v6_immutable ).toVar();
  12704. const v5 = vec3( v5_immutable ).toVar();
  12705. const v4 = vec3( v4_immutable ).toVar();
  12706. const v3 = vec3( v3_immutable ).toVar();
  12707. const v2 = vec3( v2_immutable ).toVar();
  12708. const v1 = vec3( v1_immutable ).toVar();
  12709. const v0 = vec3( v0_immutable ).toVar();
  12710. const s1 = float( sub( 1.0, s ) ).toVar();
  12711. const t1 = float( sub( 1.0, t ) ).toVar();
  12712. const r1 = float( sub( 1.0, r ) ).toVar();
  12713. 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 ) ) ) ) ) );
  12714. } ).setLayout( {
  12715. name: 'mx_trilerp_1',
  12716. type: 'vec3',
  12717. inputs: [
  12718. { name: 'v0', type: 'vec3' },
  12719. { name: 'v1', type: 'vec3' },
  12720. { name: 'v2', type: 'vec3' },
  12721. { name: 'v3', type: 'vec3' },
  12722. { name: 'v4', type: 'vec3' },
  12723. { name: 'v5', type: 'vec3' },
  12724. { name: 'v6', type: 'vec3' },
  12725. { name: 'v7', type: 'vec3' },
  12726. { name: 's', type: 'float' },
  12727. { name: 't', type: 'float' },
  12728. { name: 'r', type: 'float' }
  12729. ]
  12730. } );
  12731. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  12732. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  12733. const y = float( y_immutable ).toVar();
  12734. const x = float( x_immutable ).toVar();
  12735. const hash = uint( hash_immutable ).toVar();
  12736. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  12737. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  12738. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  12739. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  12740. } ).setLayout( {
  12741. name: 'mx_gradient_float_0',
  12742. type: 'float',
  12743. inputs: [
  12744. { name: 'hash', type: 'uint' },
  12745. { name: 'x', type: 'float' },
  12746. { name: 'y', type: 'float' }
  12747. ]
  12748. } );
  12749. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  12750. const z = float( z_immutable ).toVar();
  12751. const y = float( y_immutable ).toVar();
  12752. const x = float( x_immutable ).toVar();
  12753. const hash = uint( hash_immutable ).toVar();
  12754. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  12755. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  12756. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  12757. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  12758. } ).setLayout( {
  12759. name: 'mx_gradient_float_1',
  12760. type: 'float',
  12761. inputs: [
  12762. { name: 'hash', type: 'uint' },
  12763. { name: 'x', type: 'float' },
  12764. { name: 'y', type: 'float' },
  12765. { name: 'z', type: 'float' }
  12766. ]
  12767. } );
  12768. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  12769. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  12770. const y = float( y_immutable ).toVar();
  12771. const x = float( x_immutable ).toVar();
  12772. const hash = uvec3( hash_immutable ).toVar();
  12773. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  12774. } ).setLayout( {
  12775. name: 'mx_gradient_vec3_0',
  12776. type: 'vec3',
  12777. inputs: [
  12778. { name: 'hash', type: 'uvec3' },
  12779. { name: 'x', type: 'float' },
  12780. { name: 'y', type: 'float' }
  12781. ]
  12782. } );
  12783. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  12784. const z = float( z_immutable ).toVar();
  12785. const y = float( y_immutable ).toVar();
  12786. const x = float( x_immutable ).toVar();
  12787. const hash = uvec3( hash_immutable ).toVar();
  12788. 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 ) );
  12789. } ).setLayout( {
  12790. name: 'mx_gradient_vec3_1',
  12791. type: 'vec3',
  12792. inputs: [
  12793. { name: 'hash', type: 'uvec3' },
  12794. { name: 'x', type: 'float' },
  12795. { name: 'y', type: 'float' },
  12796. { name: 'z', type: 'float' }
  12797. ]
  12798. } );
  12799. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  12800. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  12801. const v = float( v_immutable ).toVar();
  12802. return mul( 0.6616, v );
  12803. } ).setLayout( {
  12804. name: 'mx_gradient_scale2d_0',
  12805. type: 'float',
  12806. inputs: [
  12807. { name: 'v', type: 'float' }
  12808. ]
  12809. } );
  12810. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  12811. const v = float( v_immutable ).toVar();
  12812. return mul( 0.9820, v );
  12813. } ).setLayout( {
  12814. name: 'mx_gradient_scale3d_0',
  12815. type: 'float',
  12816. inputs: [
  12817. { name: 'v', type: 'float' }
  12818. ]
  12819. } );
  12820. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  12821. const v = vec3( v_immutable ).toVar();
  12822. return mul( 0.6616, v );
  12823. } ).setLayout( {
  12824. name: 'mx_gradient_scale2d_1',
  12825. type: 'vec3',
  12826. inputs: [
  12827. { name: 'v', type: 'vec3' }
  12828. ]
  12829. } );
  12830. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  12831. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  12832. const v = vec3( v_immutable ).toVar();
  12833. return mul( 0.9820, v );
  12834. } ).setLayout( {
  12835. name: 'mx_gradient_scale3d_1',
  12836. type: 'vec3',
  12837. inputs: [
  12838. { name: 'v', type: 'vec3' }
  12839. ]
  12840. } );
  12841. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  12842. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  12843. const k = int( k_immutable ).toVar();
  12844. const x = uint( x_immutable ).toVar();
  12845. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  12846. } ).setLayout( {
  12847. name: 'mx_rotl32',
  12848. type: 'uint',
  12849. inputs: [
  12850. { name: 'x', type: 'uint' },
  12851. { name: 'k', type: 'int' }
  12852. ]
  12853. } );
  12854. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  12855. a.subAssign( c );
  12856. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  12857. c.addAssign( b );
  12858. b.subAssign( a );
  12859. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  12860. a.addAssign( c );
  12861. c.subAssign( b );
  12862. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  12863. b.addAssign( a );
  12864. a.subAssign( c );
  12865. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  12866. c.addAssign( b );
  12867. b.subAssign( a );
  12868. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  12869. a.addAssign( c );
  12870. c.subAssign( b );
  12871. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  12872. b.addAssign( a );
  12873. } );
  12874. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  12875. const c = uint( c_immutable ).toVar();
  12876. const b = uint( b_immutable ).toVar();
  12877. const a = uint( a_immutable ).toVar();
  12878. c.bitXorAssign( b );
  12879. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  12880. a.bitXorAssign( c );
  12881. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  12882. b.bitXorAssign( a );
  12883. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  12884. c.bitXorAssign( b );
  12885. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  12886. a.bitXorAssign( c );
  12887. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  12888. b.bitXorAssign( a );
  12889. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  12890. c.bitXorAssign( b );
  12891. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  12892. return c;
  12893. } ).setLayout( {
  12894. name: 'mx_bjfinal',
  12895. type: 'uint',
  12896. inputs: [
  12897. { name: 'a', type: 'uint' },
  12898. { name: 'b', type: 'uint' },
  12899. { name: 'c', type: 'uint' }
  12900. ]
  12901. } );
  12902. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  12903. const bits = uint( bits_immutable ).toVar();
  12904. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  12905. } ).setLayout( {
  12906. name: 'mx_bits_to_01',
  12907. type: 'float',
  12908. inputs: [
  12909. { name: 'bits', type: 'uint' }
  12910. ]
  12911. } );
  12912. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  12913. const t = float( t_immutable ).toVar();
  12914. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  12915. } ).setLayout( {
  12916. name: 'mx_fade',
  12917. type: 'float',
  12918. inputs: [
  12919. { name: 't', type: 'float' }
  12920. ]
  12921. } );
  12922. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  12923. const x = int( x_immutable ).toVar();
  12924. const len = uint( uint( 1 ) ).toVar();
  12925. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  12926. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  12927. } ).setLayout( {
  12928. name: 'mx_hash_int_0',
  12929. type: 'uint',
  12930. inputs: [
  12931. { name: 'x', type: 'int' }
  12932. ]
  12933. } );
  12934. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  12935. const y = int( y_immutable ).toVar();
  12936. const x = int( x_immutable ).toVar();
  12937. const len = uint( uint( 2 ) ).toVar();
  12938. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  12939. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  12940. a.addAssign( uint( x ) );
  12941. b.addAssign( uint( y ) );
  12942. return mx_bjfinal( a, b, c );
  12943. } ).setLayout( {
  12944. name: 'mx_hash_int_1',
  12945. type: 'uint',
  12946. inputs: [
  12947. { name: 'x', type: 'int' },
  12948. { name: 'y', type: 'int' }
  12949. ]
  12950. } );
  12951. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  12952. const z = int( z_immutable ).toVar();
  12953. const y = int( y_immutable ).toVar();
  12954. const x = int( x_immutable ).toVar();
  12955. const len = uint( uint( 3 ) ).toVar();
  12956. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  12957. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  12958. a.addAssign( uint( x ) );
  12959. b.addAssign( uint( y ) );
  12960. c.addAssign( uint( z ) );
  12961. return mx_bjfinal( a, b, c );
  12962. } ).setLayout( {
  12963. name: 'mx_hash_int_2',
  12964. type: 'uint',
  12965. inputs: [
  12966. { name: 'x', type: 'int' },
  12967. { name: 'y', type: 'int' },
  12968. { name: 'z', type: 'int' }
  12969. ]
  12970. } );
  12971. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  12972. const xx = int( xx_immutable ).toVar();
  12973. const z = int( z_immutable ).toVar();
  12974. const y = int( y_immutable ).toVar();
  12975. const x = int( x_immutable ).toVar();
  12976. const len = uint( uint( 4 ) ).toVar();
  12977. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  12978. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  12979. a.addAssign( uint( x ) );
  12980. b.addAssign( uint( y ) );
  12981. c.addAssign( uint( z ) );
  12982. mx_bjmix( a, b, c );
  12983. a.addAssign( uint( xx ) );
  12984. return mx_bjfinal( a, b, c );
  12985. } ).setLayout( {
  12986. name: 'mx_hash_int_3',
  12987. type: 'uint',
  12988. inputs: [
  12989. { name: 'x', type: 'int' },
  12990. { name: 'y', type: 'int' },
  12991. { name: 'z', type: 'int' },
  12992. { name: 'xx', type: 'int' }
  12993. ]
  12994. } );
  12995. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  12996. const yy = int( yy_immutable ).toVar();
  12997. const xx = int( xx_immutable ).toVar();
  12998. const z = int( z_immutable ).toVar();
  12999. const y = int( y_immutable ).toVar();
  13000. const x = int( x_immutable ).toVar();
  13001. const len = uint( uint( 5 ) ).toVar();
  13002. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  13003. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  13004. a.addAssign( uint( x ) );
  13005. b.addAssign( uint( y ) );
  13006. c.addAssign( uint( z ) );
  13007. mx_bjmix( a, b, c );
  13008. a.addAssign( uint( xx ) );
  13009. b.addAssign( uint( yy ) );
  13010. return mx_bjfinal( a, b, c );
  13011. } ).setLayout( {
  13012. name: 'mx_hash_int_4',
  13013. type: 'uint',
  13014. inputs: [
  13015. { name: 'x', type: 'int' },
  13016. { name: 'y', type: 'int' },
  13017. { name: 'z', type: 'int' },
  13018. { name: 'xx', type: 'int' },
  13019. { name: 'yy', type: 'int' }
  13020. ]
  13021. } );
  13022. 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 ] );
  13023. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  13024. const y = int( y_immutable ).toVar();
  13025. const x = int( x_immutable ).toVar();
  13026. const h = uint( mx_hash_int( x, y ) ).toVar();
  13027. const result = uvec3().toVar();
  13028. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  13029. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  13030. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  13031. return result;
  13032. } ).setLayout( {
  13033. name: 'mx_hash_vec3_0',
  13034. type: 'uvec3',
  13035. inputs: [
  13036. { name: 'x', type: 'int' },
  13037. { name: 'y', type: 'int' }
  13038. ]
  13039. } );
  13040. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  13041. const z = int( z_immutable ).toVar();
  13042. const y = int( y_immutable ).toVar();
  13043. const x = int( x_immutable ).toVar();
  13044. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  13045. const result = uvec3().toVar();
  13046. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  13047. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  13048. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  13049. return result;
  13050. } ).setLayout( {
  13051. name: 'mx_hash_vec3_1',
  13052. type: 'uvec3',
  13053. inputs: [
  13054. { name: 'x', type: 'int' },
  13055. { name: 'y', type: 'int' },
  13056. { name: 'z', type: 'int' }
  13057. ]
  13058. } );
  13059. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  13060. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  13061. const p = vec2( p_immutable ).toVar();
  13062. const X = int().toVar(), Y = int().toVar();
  13063. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  13064. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  13065. const u = float( mx_fade( fx ) ).toVar();
  13066. const v = float( mx_fade( fy ) ).toVar();
  13067. 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();
  13068. return mx_gradient_scale2d( result );
  13069. } ).setLayout( {
  13070. name: 'mx_perlin_noise_float_0',
  13071. type: 'float',
  13072. inputs: [
  13073. { name: 'p', type: 'vec2' }
  13074. ]
  13075. } );
  13076. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  13077. const p = vec3( p_immutable ).toVar();
  13078. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  13079. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  13080. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  13081. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  13082. const u = float( mx_fade( fx ) ).toVar();
  13083. const v = float( mx_fade( fy ) ).toVar();
  13084. const w = float( mx_fade( fz ) ).toVar();
  13085. 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();
  13086. return mx_gradient_scale3d( result );
  13087. } ).setLayout( {
  13088. name: 'mx_perlin_noise_float_1',
  13089. type: 'float',
  13090. inputs: [
  13091. { name: 'p', type: 'vec3' }
  13092. ]
  13093. } );
  13094. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  13095. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  13096. const p = vec2( p_immutable ).toVar();
  13097. const X = int().toVar(), Y = int().toVar();
  13098. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  13099. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  13100. const u = float( mx_fade( fx ) ).toVar();
  13101. const v = float( mx_fade( fy ) ).toVar();
  13102. 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();
  13103. return mx_gradient_scale2d( result );
  13104. } ).setLayout( {
  13105. name: 'mx_perlin_noise_vec3_0',
  13106. type: 'vec3',
  13107. inputs: [
  13108. { name: 'p', type: 'vec2' }
  13109. ]
  13110. } );
  13111. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  13112. const p = vec3( p_immutable ).toVar();
  13113. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  13114. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  13115. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  13116. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  13117. const u = float( mx_fade( fx ) ).toVar();
  13118. const v = float( mx_fade( fy ) ).toVar();
  13119. const w = float( mx_fade( fz ) ).toVar();
  13120. 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();
  13121. return mx_gradient_scale3d( result );
  13122. } ).setLayout( {
  13123. name: 'mx_perlin_noise_vec3_1',
  13124. type: 'vec3',
  13125. inputs: [
  13126. { name: 'p', type: 'vec3' }
  13127. ]
  13128. } );
  13129. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  13130. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  13131. const p = float( p_immutable ).toVar();
  13132. const ix = int( mx_floor( p ) ).toVar();
  13133. return mx_bits_to_01( mx_hash_int( ix ) );
  13134. } ).setLayout( {
  13135. name: 'mx_cell_noise_float_0',
  13136. type: 'float',
  13137. inputs: [
  13138. { name: 'p', type: 'float' }
  13139. ]
  13140. } );
  13141. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  13142. const p = vec2( p_immutable ).toVar();
  13143. const ix = int( mx_floor( p.x ) ).toVar();
  13144. const iy = int( mx_floor( p.y ) ).toVar();
  13145. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  13146. } ).setLayout( {
  13147. name: 'mx_cell_noise_float_1',
  13148. type: 'float',
  13149. inputs: [
  13150. { name: 'p', type: 'vec2' }
  13151. ]
  13152. } );
  13153. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  13154. const p = vec3( p_immutable ).toVar();
  13155. const ix = int( mx_floor( p.x ) ).toVar();
  13156. const iy = int( mx_floor( p.y ) ).toVar();
  13157. const iz = int( mx_floor( p.z ) ).toVar();
  13158. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  13159. } ).setLayout( {
  13160. name: 'mx_cell_noise_float_2',
  13161. type: 'float',
  13162. inputs: [
  13163. { name: 'p', type: 'vec3' }
  13164. ]
  13165. } );
  13166. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  13167. const p = vec4( p_immutable ).toVar();
  13168. const ix = int( mx_floor( p.x ) ).toVar();
  13169. const iy = int( mx_floor( p.y ) ).toVar();
  13170. const iz = int( mx_floor( p.z ) ).toVar();
  13171. const iw = int( mx_floor( p.w ) ).toVar();
  13172. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  13173. } ).setLayout( {
  13174. name: 'mx_cell_noise_float_3',
  13175. type: 'float',
  13176. inputs: [
  13177. { name: 'p', type: 'vec4' }
  13178. ]
  13179. } );
  13180. 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 ] );
  13181. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  13182. const p = float( p_immutable ).toVar();
  13183. const ix = int( mx_floor( p ) ).toVar();
  13184. 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 ) ) ) );
  13185. } ).setLayout( {
  13186. name: 'mx_cell_noise_vec3_0',
  13187. type: 'vec3',
  13188. inputs: [
  13189. { name: 'p', type: 'float' }
  13190. ]
  13191. } );
  13192. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  13193. const p = vec2( p_immutable ).toVar();
  13194. const ix = int( mx_floor( p.x ) ).toVar();
  13195. const iy = int( mx_floor( p.y ) ).toVar();
  13196. 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 ) ) ) );
  13197. } ).setLayout( {
  13198. name: 'mx_cell_noise_vec3_1',
  13199. type: 'vec3',
  13200. inputs: [
  13201. { name: 'p', type: 'vec2' }
  13202. ]
  13203. } );
  13204. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  13205. const p = vec3( p_immutable ).toVar();
  13206. const ix = int( mx_floor( p.x ) ).toVar();
  13207. const iy = int( mx_floor( p.y ) ).toVar();
  13208. const iz = int( mx_floor( p.z ) ).toVar();
  13209. 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 ) ) ) );
  13210. } ).setLayout( {
  13211. name: 'mx_cell_noise_vec3_2',
  13212. type: 'vec3',
  13213. inputs: [
  13214. { name: 'p', type: 'vec3' }
  13215. ]
  13216. } );
  13217. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  13218. const p = vec4( p_immutable ).toVar();
  13219. const ix = int( mx_floor( p.x ) ).toVar();
  13220. const iy = int( mx_floor( p.y ) ).toVar();
  13221. const iz = int( mx_floor( p.z ) ).toVar();
  13222. const iw = int( mx_floor( p.w ) ).toVar();
  13223. 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 ) ) ) );
  13224. } ).setLayout( {
  13225. name: 'mx_cell_noise_vec3_3',
  13226. type: 'vec3',
  13227. inputs: [
  13228. { name: 'p', type: 'vec4' }
  13229. ]
  13230. } );
  13231. 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 ] );
  13232. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  13233. const diminish = float( diminish_immutable ).toVar();
  13234. const lacunarity = float( lacunarity_immutable ).toVar();
  13235. const octaves = int( octaves_immutable ).toVar();
  13236. const p = vec3( p_immutable ).toVar();
  13237. const result = float( 0.0 ).toVar();
  13238. const amplitude = float( 1.0 ).toVar();
  13239. Loop( octaves, () => {
  13240. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  13241. amplitude.mulAssign( diminish );
  13242. p.mulAssign( lacunarity );
  13243. } );
  13244. return result;
  13245. } ).setLayout( {
  13246. name: 'mx_fractal_noise_float',
  13247. type: 'float',
  13248. inputs: [
  13249. { name: 'p', type: 'vec3' },
  13250. { name: 'octaves', type: 'int' },
  13251. { name: 'lacunarity', type: 'float' },
  13252. { name: 'diminish', type: 'float' }
  13253. ]
  13254. } );
  13255. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  13256. const diminish = float( diminish_immutable ).toVar();
  13257. const lacunarity = float( lacunarity_immutable ).toVar();
  13258. const octaves = int( octaves_immutable ).toVar();
  13259. const p = vec3( p_immutable ).toVar();
  13260. const result = vec3( 0.0 ).toVar();
  13261. const amplitude = float( 1.0 ).toVar();
  13262. Loop( octaves, () => {
  13263. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  13264. amplitude.mulAssign( diminish );
  13265. p.mulAssign( lacunarity );
  13266. } );
  13267. return result;
  13268. } ).setLayout( {
  13269. name: 'mx_fractal_noise_vec3',
  13270. type: 'vec3',
  13271. inputs: [
  13272. { name: 'p', type: 'vec3' },
  13273. { name: 'octaves', type: 'int' },
  13274. { name: 'lacunarity', type: 'float' },
  13275. { name: 'diminish', type: 'float' }
  13276. ]
  13277. } );
  13278. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  13279. const diminish = float( diminish_immutable ).toVar();
  13280. const lacunarity = float( lacunarity_immutable ).toVar();
  13281. const octaves = int( octaves_immutable ).toVar();
  13282. const p = vec3( p_immutable ).toVar();
  13283. 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 ) );
  13284. } ).setLayout( {
  13285. name: 'mx_fractal_noise_vec2',
  13286. type: 'vec2',
  13287. inputs: [
  13288. { name: 'p', type: 'vec3' },
  13289. { name: 'octaves', type: 'int' },
  13290. { name: 'lacunarity', type: 'float' },
  13291. { name: 'diminish', type: 'float' }
  13292. ]
  13293. } );
  13294. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  13295. const diminish = float( diminish_immutable ).toVar();
  13296. const lacunarity = float( lacunarity_immutable ).toVar();
  13297. const octaves = int( octaves_immutable ).toVar();
  13298. const p = vec3( p_immutable ).toVar();
  13299. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  13300. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  13301. return vec4( c, f );
  13302. } ).setLayout( {
  13303. name: 'mx_fractal_noise_vec4',
  13304. type: 'vec4',
  13305. inputs: [
  13306. { name: 'p', type: 'vec3' },
  13307. { name: 'octaves', type: 'int' },
  13308. { name: 'lacunarity', type: 'float' },
  13309. { name: 'diminish', type: 'float' }
  13310. ]
  13311. } );
  13312. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  13313. const metric = int( metric_immutable ).toVar();
  13314. const jitter = float( jitter_immutable ).toVar();
  13315. const yoff = int( yoff_immutable ).toVar();
  13316. const xoff = int( xoff_immutable ).toVar();
  13317. const y = int( y_immutable ).toVar();
  13318. const x = int( x_immutable ).toVar();
  13319. const p = vec2( p_immutable ).toVar();
  13320. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  13321. const off = vec2( tmp.x, tmp.y ).toVar();
  13322. off.subAssign( 0.5 );
  13323. off.mulAssign( jitter );
  13324. off.addAssign( 0.5 );
  13325. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  13326. const diff = vec2( cellpos.sub( p ) ).toVar();
  13327. If( metric.equal( int( 2 ) ), () => {
  13328. return abs( diff.x ).add( abs( diff.y ) );
  13329. } );
  13330. If( metric.equal( int( 3 ) ), () => {
  13331. return max$1( abs( diff.x ), abs( diff.y ) );
  13332. } );
  13333. return dot( diff, diff );
  13334. } ).setLayout( {
  13335. name: 'mx_worley_distance_0',
  13336. type: 'float',
  13337. inputs: [
  13338. { name: 'p', type: 'vec2' },
  13339. { name: 'x', type: 'int' },
  13340. { name: 'y', type: 'int' },
  13341. { name: 'xoff', type: 'int' },
  13342. { name: 'yoff', type: 'int' },
  13343. { name: 'jitter', type: 'float' },
  13344. { name: 'metric', type: 'int' }
  13345. ]
  13346. } );
  13347. 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 ] ) => {
  13348. const metric = int( metric_immutable ).toVar();
  13349. const jitter = float( jitter_immutable ).toVar();
  13350. const zoff = int( zoff_immutable ).toVar();
  13351. const yoff = int( yoff_immutable ).toVar();
  13352. const xoff = int( xoff_immutable ).toVar();
  13353. const z = int( z_immutable ).toVar();
  13354. const y = int( y_immutable ).toVar();
  13355. const x = int( x_immutable ).toVar();
  13356. const p = vec3( p_immutable ).toVar();
  13357. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  13358. off.subAssign( 0.5 );
  13359. off.mulAssign( jitter );
  13360. off.addAssign( 0.5 );
  13361. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  13362. const diff = vec3( cellpos.sub( p ) ).toVar();
  13363. If( metric.equal( int( 2 ) ), () => {
  13364. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  13365. } );
  13366. If( metric.equal( int( 3 ) ), () => {
  13367. return max$1( max$1( abs( diff.x ), abs( diff.y ) ), abs( diff.z ) );
  13368. } );
  13369. return dot( diff, diff );
  13370. } ).setLayout( {
  13371. name: 'mx_worley_distance_1',
  13372. type: 'float',
  13373. inputs: [
  13374. { name: 'p', type: 'vec3' },
  13375. { name: 'x', type: 'int' },
  13376. { name: 'y', type: 'int' },
  13377. { name: 'z', type: 'int' },
  13378. { name: 'xoff', type: 'int' },
  13379. { name: 'yoff', type: 'int' },
  13380. { name: 'zoff', type: 'int' },
  13381. { name: 'jitter', type: 'float' },
  13382. { name: 'metric', type: 'int' }
  13383. ]
  13384. } );
  13385. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  13386. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  13387. const metric = int( metric_immutable ).toVar();
  13388. const jitter = float( jitter_immutable ).toVar();
  13389. const p = vec2( p_immutable ).toVar();
  13390. const X = int().toVar(), Y = int().toVar();
  13391. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  13392. const sqdist = float( 1e6 ).toVar();
  13393. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  13394. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  13395. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  13396. sqdist.assign( min$1( sqdist, dist ) );
  13397. } );
  13398. } );
  13399. If( metric.equal( int( 0 ) ), () => {
  13400. sqdist.assign( sqrt( sqdist ) );
  13401. } );
  13402. return sqdist;
  13403. } ).setLayout( {
  13404. name: 'mx_worley_noise_float_0',
  13405. type: 'float',
  13406. inputs: [
  13407. { name: 'p', type: 'vec2' },
  13408. { name: 'jitter', type: 'float' },
  13409. { name: 'metric', type: 'int' }
  13410. ]
  13411. } );
  13412. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  13413. const metric = int( metric_immutable ).toVar();
  13414. const jitter = float( jitter_immutable ).toVar();
  13415. const p = vec2( p_immutable ).toVar();
  13416. const X = int().toVar(), Y = int().toVar();
  13417. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  13418. const sqdist = vec2( 1e6, 1e6 ).toVar();
  13419. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  13420. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  13421. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  13422. If( dist.lessThan( sqdist.x ), () => {
  13423. sqdist.y.assign( sqdist.x );
  13424. sqdist.x.assign( dist );
  13425. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  13426. sqdist.y.assign( dist );
  13427. } );
  13428. } );
  13429. } );
  13430. If( metric.equal( int( 0 ) ), () => {
  13431. sqdist.assign( sqrt( sqdist ) );
  13432. } );
  13433. return sqdist;
  13434. } ).setLayout( {
  13435. name: 'mx_worley_noise_vec2_0',
  13436. type: 'vec2',
  13437. inputs: [
  13438. { name: 'p', type: 'vec2' },
  13439. { name: 'jitter', type: 'float' },
  13440. { name: 'metric', type: 'int' }
  13441. ]
  13442. } );
  13443. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  13444. const metric = int( metric_immutable ).toVar();
  13445. const jitter = float( jitter_immutable ).toVar();
  13446. const p = vec2( p_immutable ).toVar();
  13447. const X = int().toVar(), Y = int().toVar();
  13448. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  13449. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  13450. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  13451. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  13452. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  13453. If( dist.lessThan( sqdist.x ), () => {
  13454. sqdist.z.assign( sqdist.y );
  13455. sqdist.y.assign( sqdist.x );
  13456. sqdist.x.assign( dist );
  13457. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  13458. sqdist.z.assign( sqdist.y );
  13459. sqdist.y.assign( dist );
  13460. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  13461. sqdist.z.assign( dist );
  13462. } );
  13463. } );
  13464. } );
  13465. If( metric.equal( int( 0 ) ), () => {
  13466. sqdist.assign( sqrt( sqdist ) );
  13467. } );
  13468. return sqdist;
  13469. } ).setLayout( {
  13470. name: 'mx_worley_noise_vec3_0',
  13471. type: 'vec3',
  13472. inputs: [
  13473. { name: 'p', type: 'vec2' },
  13474. { name: 'jitter', type: 'float' },
  13475. { name: 'metric', type: 'int' }
  13476. ]
  13477. } );
  13478. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  13479. const metric = int( metric_immutable ).toVar();
  13480. const jitter = float( jitter_immutable ).toVar();
  13481. const p = vec3( p_immutable ).toVar();
  13482. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  13483. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  13484. const sqdist = float( 1e6 ).toVar();
  13485. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  13486. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  13487. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  13488. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  13489. sqdist.assign( min$1( sqdist, dist ) );
  13490. } );
  13491. } );
  13492. } );
  13493. If( metric.equal( int( 0 ) ), () => {
  13494. sqdist.assign( sqrt( sqdist ) );
  13495. } );
  13496. return sqdist;
  13497. } ).setLayout( {
  13498. name: 'mx_worley_noise_float_1',
  13499. type: 'float',
  13500. inputs: [
  13501. { name: 'p', type: 'vec3' },
  13502. { name: 'jitter', type: 'float' },
  13503. { name: 'metric', type: 'int' }
  13504. ]
  13505. } );
  13506. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  13507. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  13508. const metric = int( metric_immutable ).toVar();
  13509. const jitter = float( jitter_immutable ).toVar();
  13510. const p = vec3( p_immutable ).toVar();
  13511. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  13512. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  13513. const sqdist = vec2( 1e6, 1e6 ).toVar();
  13514. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  13515. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  13516. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  13517. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  13518. If( dist.lessThan( sqdist.x ), () => {
  13519. sqdist.y.assign( sqdist.x );
  13520. sqdist.x.assign( dist );
  13521. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  13522. sqdist.y.assign( dist );
  13523. } );
  13524. } );
  13525. } );
  13526. } );
  13527. If( metric.equal( int( 0 ) ), () => {
  13528. sqdist.assign( sqrt( sqdist ) );
  13529. } );
  13530. return sqdist;
  13531. } ).setLayout( {
  13532. name: 'mx_worley_noise_vec2_1',
  13533. type: 'vec2',
  13534. inputs: [
  13535. { name: 'p', type: 'vec3' },
  13536. { name: 'jitter', type: 'float' },
  13537. { name: 'metric', type: 'int' }
  13538. ]
  13539. } );
  13540. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  13541. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  13542. const metric = int( metric_immutable ).toVar();
  13543. const jitter = float( jitter_immutable ).toVar();
  13544. const p = vec3( p_immutable ).toVar();
  13545. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  13546. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  13547. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  13548. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  13549. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  13550. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  13551. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  13552. If( dist.lessThan( sqdist.x ), () => {
  13553. sqdist.z.assign( sqdist.y );
  13554. sqdist.y.assign( sqdist.x );
  13555. sqdist.x.assign( dist );
  13556. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  13557. sqdist.z.assign( sqdist.y );
  13558. sqdist.y.assign( dist );
  13559. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  13560. sqdist.z.assign( dist );
  13561. } );
  13562. } );
  13563. } );
  13564. } );
  13565. If( metric.equal( int( 0 ) ), () => {
  13566. sqdist.assign( sqrt( sqdist ) );
  13567. } );
  13568. return sqdist;
  13569. } ).setLayout( {
  13570. name: 'mx_worley_noise_vec3_1',
  13571. type: 'vec3',
  13572. inputs: [
  13573. { name: 'p', type: 'vec3' },
  13574. { name: 'jitter', type: 'float' },
  13575. { name: 'metric', type: 'int' }
  13576. ]
  13577. } );
  13578. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  13579. // Three.js Transpiler
  13580. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  13581. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  13582. const s = hsv.y;
  13583. const v = hsv.z;
  13584. const result = vec3().toVar();
  13585. If( s.lessThan( 0.0001 ), () => {
  13586. result.assign( vec3( v, v, v ) );
  13587. } ).Else( () => {
  13588. let h = hsv.x;
  13589. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  13590. const hi = int( trunc( h ) );
  13591. const f = h.sub( float( hi ) );
  13592. const p = v.mul( s.oneMinus() );
  13593. const q = v.mul( s.mul( f ).oneMinus() );
  13594. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  13595. If( hi.equal( int( 0 ) ), () => {
  13596. result.assign( vec3( v, t, p ) );
  13597. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  13598. result.assign( vec3( q, v, p ) );
  13599. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  13600. result.assign( vec3( p, v, t ) );
  13601. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  13602. result.assign( vec3( p, q, v ) );
  13603. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  13604. result.assign( vec3( t, p, v ) );
  13605. } ).Else( () => {
  13606. result.assign( vec3( v, p, q ) );
  13607. } );
  13608. } );
  13609. return result;
  13610. } ).setLayout( {
  13611. name: 'mx_hsvtorgb',
  13612. type: 'vec3',
  13613. inputs: [
  13614. { name: 'hsv', type: 'vec3' }
  13615. ]
  13616. } );
  13617. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  13618. const c = vec3( c_immutable ).toVar();
  13619. const r = float( c.x ).toVar();
  13620. const g = float( c.y ).toVar();
  13621. const b = float( c.z ).toVar();
  13622. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  13623. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  13624. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  13625. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  13626. v.assign( maxcomp );
  13627. If( maxcomp.greaterThan( 0.0 ), () => {
  13628. s.assign( delta.div( maxcomp ) );
  13629. } ).Else( () => {
  13630. s.assign( 0.0 );
  13631. } );
  13632. If( s.lessThanEqual( 0.0 ), () => {
  13633. h.assign( 0.0 );
  13634. } ).Else( () => {
  13635. If( r.greaterThanEqual( maxcomp ), () => {
  13636. h.assign( g.sub( b ).div( delta ) );
  13637. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  13638. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  13639. } ).Else( () => {
  13640. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  13641. } );
  13642. h.mulAssign( 1.0 / 6.0 );
  13643. If( h.lessThan( 0.0 ), () => {
  13644. h.addAssign( 1.0 );
  13645. } );
  13646. } );
  13647. return vec3( h, s, v );
  13648. } ).setLayout( {
  13649. name: 'mx_rgbtohsv',
  13650. type: 'vec3',
  13651. inputs: [
  13652. { name: 'c', type: 'vec3' }
  13653. ]
  13654. } );
  13655. // Three.js Transpiler
  13656. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  13657. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  13658. const color = vec3( color_immutable ).toVar();
  13659. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  13660. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  13661. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  13662. return mix( linSeg, powSeg, isAbove );
  13663. } ).setLayout( {
  13664. name: 'mx_srgb_texture_to_lin_rec709',
  13665. type: 'vec3',
  13666. inputs: [
  13667. { name: 'color', type: 'vec3' }
  13668. ]
  13669. } );
  13670. const mx_aastep = ( threshold, value ) => {
  13671. threshold = float( threshold );
  13672. value = float( value );
  13673. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  13674. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  13675. };
  13676. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  13677. const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' );
  13678. const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' );
  13679. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  13680. const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' );
  13681. const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' );
  13682. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  13683. const mx_safepower = ( in1, in2 = 1 ) => {
  13684. in1 = float( in1 );
  13685. return in1.abs().pow( in2 ).mul( in1.sign() );
  13686. };
  13687. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  13688. const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  13689. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  13690. const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  13691. const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => {
  13692. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  13693. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  13694. return noise_vec4.mul( amplitude ).add( pivot );
  13695. };
  13696. const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  13697. const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  13698. const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  13699. const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  13700. 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 );
  13701. 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 );
  13702. 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 );
  13703. 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 );
  13704. // https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html
  13705. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  13706. const nDir = normalize( normal ).toVar( 'nDir' );
  13707. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmax' );
  13708. const rbmin = sub( float( - 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmin' );
  13709. const rbminmax = vec3().toVar( 'rbminmax' );
  13710. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  13711. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  13712. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  13713. const correction = min$1( min$1( rbminmax.x, rbminmax.y ), rbminmax.z ).toVar( 'correction' );
  13714. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar( 'boxIntersection' );
  13715. return boxIntersection.sub( cubePos );
  13716. } );
  13717. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  13718. // normal is assumed to have unit length
  13719. const x = normal.x, y = normal.y, z = normal.z;
  13720. // band 0
  13721. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  13722. // band 1
  13723. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  13724. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  13725. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  13726. // band 2
  13727. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  13728. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  13729. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  13730. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  13731. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  13732. return result;
  13733. } );
  13734. const _clearColor$1 = /*@__PURE__*/ new Color4();
  13735. class Background extends DataMap {
  13736. constructor( renderer, nodes ) {
  13737. super();
  13738. this.renderer = renderer;
  13739. this.nodes = nodes;
  13740. }
  13741. update( scene, renderList, renderContext ) {
  13742. const renderer = this.renderer;
  13743. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  13744. let forceClear = false;
  13745. if ( background === null ) {
  13746. // no background settings, use clear color configuration from the renderer
  13747. renderer._clearColor.getRGB( _clearColor$1, LinearSRGBColorSpace );
  13748. _clearColor$1.a = renderer._clearColor.a;
  13749. } else if ( background.isColor === true ) {
  13750. // background is an opaque color
  13751. background.getRGB( _clearColor$1, LinearSRGBColorSpace );
  13752. _clearColor$1.a = 1;
  13753. forceClear = true;
  13754. } else if ( background.isNode === true ) {
  13755. const sceneData = this.get( scene );
  13756. const backgroundNode = background;
  13757. _clearColor$1.copy( renderer._clearColor );
  13758. let backgroundMesh = sceneData.backgroundMesh;
  13759. if ( backgroundMesh === undefined ) {
  13760. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  13761. // @TODO: Add Texture2D support using node context
  13762. getUV: () => backgroundRotation.mul( normalWorld ),
  13763. getTextureLevel: () => backgroundBlurriness
  13764. } );
  13765. let viewProj = modelViewProjection();
  13766. viewProj = viewProj.setZ( viewProj.w );
  13767. const nodeMaterial = new NodeMaterial();
  13768. nodeMaterial.name = 'Background.material';
  13769. nodeMaterial.side = BackSide;
  13770. nodeMaterial.depthTest = false;
  13771. nodeMaterial.depthWrite = false;
  13772. nodeMaterial.fog = false;
  13773. nodeMaterial.lights = false;
  13774. nodeMaterial.vertexNode = viewProj;
  13775. nodeMaterial.colorNode = backgroundMeshNode;
  13776. sceneData.backgroundMeshNode = backgroundMeshNode;
  13777. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  13778. backgroundMesh.frustumCulled = false;
  13779. backgroundMesh.name = 'Background.mesh';
  13780. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  13781. this.matrixWorld.copyPosition( camera.matrixWorld );
  13782. };
  13783. }
  13784. const backgroundCacheKey = backgroundNode.getCacheKey();
  13785. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  13786. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  13787. sceneData.backgroundMeshNode.needsUpdate = true;
  13788. backgroundMesh.material.needsUpdate = true;
  13789. sceneData.backgroundCacheKey = backgroundCacheKey;
  13790. }
  13791. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  13792. } else {
  13793. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  13794. }
  13795. //
  13796. if ( renderer.autoClear === true || forceClear === true ) {
  13797. const clearColorValue = renderContext.clearColorValue;
  13798. clearColorValue.r = _clearColor$1.r;
  13799. clearColorValue.g = _clearColor$1.g;
  13800. clearColorValue.b = _clearColor$1.b;
  13801. clearColorValue.a = _clearColor$1.a;
  13802. // premultiply alpha
  13803. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  13804. clearColorValue.r *= clearColorValue.a;
  13805. clearColorValue.g *= clearColorValue.a;
  13806. clearColorValue.b *= clearColorValue.a;
  13807. }
  13808. //
  13809. renderContext.depthClearValue = renderer._clearDepth;
  13810. renderContext.stencilClearValue = renderer._clearStencil;
  13811. renderContext.clearColor = renderer.autoClearColor === true;
  13812. renderContext.clearDepth = renderer.autoClearDepth === true;
  13813. renderContext.clearStencil = renderer.autoClearStencil === true;
  13814. } else {
  13815. renderContext.clearColor = false;
  13816. renderContext.clearDepth = false;
  13817. renderContext.clearStencil = false;
  13818. }
  13819. }
  13820. }
  13821. let _id$5 = 0;
  13822. class BindGroup {
  13823. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  13824. this.name = name;
  13825. this.bindings = bindings;
  13826. this.index = index;
  13827. this.bindingsReference = bindingsReference;
  13828. this.id = _id$5 ++;
  13829. }
  13830. }
  13831. class NodeBuilderState {
  13832. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, monitor, transforms = [] ) {
  13833. this.vertexShader = vertexShader;
  13834. this.fragmentShader = fragmentShader;
  13835. this.computeShader = computeShader;
  13836. this.transforms = transforms;
  13837. this.nodeAttributes = nodeAttributes;
  13838. this.bindings = bindings;
  13839. this.updateNodes = updateNodes;
  13840. this.updateBeforeNodes = updateBeforeNodes;
  13841. this.updateAfterNodes = updateAfterNodes;
  13842. this.monitor = monitor;
  13843. this.usedTimes = 0;
  13844. }
  13845. createBindings() {
  13846. const bindings = [];
  13847. for ( const instanceGroup of this.bindings ) {
  13848. const shared = instanceGroup.bindings[ 0 ].groupNode.shared;
  13849. if ( shared !== true ) {
  13850. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup );
  13851. bindings.push( bindingsGroup );
  13852. for ( const instanceBinding of instanceGroup.bindings ) {
  13853. bindingsGroup.bindings.push( instanceBinding.clone() );
  13854. }
  13855. } else {
  13856. bindings.push( instanceGroup );
  13857. }
  13858. }
  13859. return bindings;
  13860. }
  13861. }
  13862. class NodeAttribute {
  13863. constructor( name, type, node = null ) {
  13864. this.isNodeAttribute = true;
  13865. this.name = name;
  13866. this.type = type;
  13867. this.node = node;
  13868. }
  13869. }
  13870. class NodeUniform {
  13871. constructor( name, type, node ) {
  13872. this.isNodeUniform = true;
  13873. this.name = name;
  13874. this.type = type;
  13875. this.node = node.getSelf();
  13876. }
  13877. get value() {
  13878. return this.node.value;
  13879. }
  13880. set value( val ) {
  13881. this.node.value = val;
  13882. }
  13883. get id() {
  13884. return this.node.id;
  13885. }
  13886. get groupNode() {
  13887. return this.node.groupNode;
  13888. }
  13889. }
  13890. class NodeVar {
  13891. constructor( name, type ) {
  13892. this.isNodeVar = true;
  13893. this.name = name;
  13894. this.type = type;
  13895. }
  13896. }
  13897. class NodeVarying extends NodeVar {
  13898. constructor( name, type ) {
  13899. super( name, type );
  13900. this.needsInterpolation = false;
  13901. this.isNodeVarying = true;
  13902. }
  13903. }
  13904. class NodeCode {
  13905. constructor( name, type, code = '' ) {
  13906. this.name = name;
  13907. this.type = type;
  13908. this.code = code;
  13909. Object.defineProperty( this, 'isNodeCode', { value: true } );
  13910. }
  13911. }
  13912. let id = 0;
  13913. class NodeCache {
  13914. constructor( parent = null ) {
  13915. this.id = id ++;
  13916. this.nodesData = new WeakMap();
  13917. this.parent = parent;
  13918. }
  13919. getData( node ) {
  13920. let data = this.nodesData.get( node );
  13921. if ( data === undefined && this.parent !== null ) {
  13922. data = this.parent.getData( node );
  13923. }
  13924. return data;
  13925. }
  13926. setData( node, data ) {
  13927. this.nodesData.set( node, data );
  13928. }
  13929. }
  13930. class Uniform {
  13931. constructor( name, value ) {
  13932. this.name = name;
  13933. this.value = value;
  13934. this.boundary = 0; // used to build the uniform buffer according to the STD140 layout
  13935. this.itemSize = 0;
  13936. this.offset = 0; // this property is set by WebGPUUniformsGroup and marks the start position in the uniform buffer
  13937. }
  13938. setValue( value ) {
  13939. this.value = value;
  13940. }
  13941. getValue() {
  13942. return this.value;
  13943. }
  13944. }
  13945. class NumberUniform extends Uniform {
  13946. constructor( name, value = 0 ) {
  13947. super( name, value );
  13948. this.isNumberUniform = true;
  13949. this.boundary = 4;
  13950. this.itemSize = 1;
  13951. }
  13952. }
  13953. class Vector2Uniform extends Uniform {
  13954. constructor( name, value = new Vector2() ) {
  13955. super( name, value );
  13956. this.isVector2Uniform = true;
  13957. this.boundary = 8;
  13958. this.itemSize = 2;
  13959. }
  13960. }
  13961. class Vector3Uniform extends Uniform {
  13962. constructor( name, value = new Vector3() ) {
  13963. super( name, value );
  13964. this.isVector3Uniform = true;
  13965. this.boundary = 16;
  13966. this.itemSize = 3;
  13967. }
  13968. }
  13969. class Vector4Uniform extends Uniform {
  13970. constructor( name, value = new Vector4() ) {
  13971. super( name, value );
  13972. this.isVector4Uniform = true;
  13973. this.boundary = 16;
  13974. this.itemSize = 4;
  13975. }
  13976. }
  13977. class ColorUniform extends Uniform {
  13978. constructor( name, value = new Color() ) {
  13979. super( name, value );
  13980. this.isColorUniform = true;
  13981. this.boundary = 16;
  13982. this.itemSize = 3;
  13983. }
  13984. }
  13985. class Matrix3Uniform extends Uniform {
  13986. constructor( name, value = new Matrix3() ) {
  13987. super( name, value );
  13988. this.isMatrix3Uniform = true;
  13989. this.boundary = 48;
  13990. this.itemSize = 12;
  13991. }
  13992. }
  13993. class Matrix4Uniform extends Uniform {
  13994. constructor( name, value = new Matrix4() ) {
  13995. super( name, value );
  13996. this.isMatrix4Uniform = true;
  13997. this.boundary = 64;
  13998. this.itemSize = 16;
  13999. }
  14000. }
  14001. class NumberNodeUniform extends NumberUniform {
  14002. constructor( nodeUniform ) {
  14003. super( nodeUniform.name, nodeUniform.value );
  14004. this.nodeUniform = nodeUniform;
  14005. }
  14006. getValue() {
  14007. return this.nodeUniform.value;
  14008. }
  14009. }
  14010. class Vector2NodeUniform extends Vector2Uniform {
  14011. constructor( nodeUniform ) {
  14012. super( nodeUniform.name, nodeUniform.value );
  14013. this.nodeUniform = nodeUniform;
  14014. }
  14015. getValue() {
  14016. return this.nodeUniform.value;
  14017. }
  14018. }
  14019. class Vector3NodeUniform extends Vector3Uniform {
  14020. constructor( nodeUniform ) {
  14021. super( nodeUniform.name, nodeUniform.value );
  14022. this.nodeUniform = nodeUniform;
  14023. }
  14024. getValue() {
  14025. return this.nodeUniform.value;
  14026. }
  14027. }
  14028. class Vector4NodeUniform extends Vector4Uniform {
  14029. constructor( nodeUniform ) {
  14030. super( nodeUniform.name, nodeUniform.value );
  14031. this.nodeUniform = nodeUniform;
  14032. }
  14033. getValue() {
  14034. return this.nodeUniform.value;
  14035. }
  14036. }
  14037. class ColorNodeUniform extends ColorUniform {
  14038. constructor( nodeUniform ) {
  14039. super( nodeUniform.name, nodeUniform.value );
  14040. this.nodeUniform = nodeUniform;
  14041. }
  14042. getValue() {
  14043. return this.nodeUniform.value;
  14044. }
  14045. }
  14046. class Matrix3NodeUniform extends Matrix3Uniform {
  14047. constructor( nodeUniform ) {
  14048. super( nodeUniform.name, nodeUniform.value );
  14049. this.nodeUniform = nodeUniform;
  14050. }
  14051. getValue() {
  14052. return this.nodeUniform.value;
  14053. }
  14054. }
  14055. class Matrix4NodeUniform extends Matrix4Uniform {
  14056. constructor( nodeUniform ) {
  14057. super( nodeUniform.name, nodeUniform.value );
  14058. this.nodeUniform = nodeUniform;
  14059. }
  14060. getValue() {
  14061. return this.nodeUniform.value;
  14062. }
  14063. }
  14064. const LOD_MIN = 4;
  14065. // The standard deviations (radians) associated with the extra mips. These are
  14066. // chosen to approximate a Trowbridge-Reitz distribution function times the
  14067. // geometric shadowing function. These sigma values squared must match the
  14068. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  14069. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  14070. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  14071. // samples and exit early, but not recompile the shader.
  14072. const MAX_SAMPLES = 20;
  14073. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  14074. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  14075. const _clearColor = /*@__PURE__*/ new Color();
  14076. let _oldTarget = null;
  14077. let _oldActiveCubeFace = 0;
  14078. let _oldActiveMipmapLevel = 0;
  14079. // Golden Ratio
  14080. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  14081. const INV_PHI = 1 / PHI;
  14082. // Vertices of a dodecahedron (except the opposites, which represent the
  14083. // same axis), used as axis directions evenly spread on a sphere.
  14084. const _axisDirections = [
  14085. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  14086. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  14087. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  14088. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  14089. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  14090. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  14091. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  14092. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  14093. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  14094. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  14095. ];
  14096. //
  14097. // WebGPU Face indices
  14098. const _faceLib = [
  14099. 3, 1, 5,
  14100. 0, 4, 2
  14101. ];
  14102. const direction = getDirection( uv(), attribute( 'faceIndex' ) ).normalize();
  14103. const outputDirection = vec3( direction.x, direction.y.negate(), direction.z );
  14104. /**
  14105. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  14106. * (PMREM) from a cubeMap environment texture. This allows different levels of
  14107. * blur to be quickly accessed based on material roughness. It is packed into a
  14108. * special CubeUV format that allows us to perform custom interpolation so that
  14109. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  14110. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  14111. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  14112. * higher roughness levels. In this way we maintain resolution to smoothly
  14113. * interpolate diffuse lighting while limiting sampling computation.
  14114. *
  14115. * Paper: Fast, Accurate Image-Based Lighting
  14116. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  14117. */
  14118. class PMREMGenerator {
  14119. constructor( renderer ) {
  14120. this._renderer = renderer;
  14121. this._pingPongRenderTarget = null;
  14122. this._lodMax = 0;
  14123. this._cubeSize = 0;
  14124. this._lodPlanes = [];
  14125. this._sizeLods = [];
  14126. this._sigmas = [];
  14127. this._lodMeshes = [];
  14128. this._blurMaterial = null;
  14129. this._cubemapMaterial = null;
  14130. this._equirectMaterial = null;
  14131. this._backgroundBox = null;
  14132. }
  14133. /**
  14134. * Generates a PMREM from a supplied Scene, which can be faster than using an
  14135. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  14136. * in radians to be applied to the scene before PMREM generation. Optional near
  14137. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  14138. * is placed at the origin).
  14139. */
  14140. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  14141. _oldTarget = this._renderer.getRenderTarget();
  14142. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  14143. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  14144. this._setSize( 256 );
  14145. const cubeUVRenderTarget = this._allocateTargets();
  14146. cubeUVRenderTarget.depthBuffer = true;
  14147. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  14148. if ( sigma > 0 ) {
  14149. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  14150. }
  14151. this._applyPMREM( cubeUVRenderTarget );
  14152. this._cleanup( cubeUVRenderTarget );
  14153. return cubeUVRenderTarget;
  14154. }
  14155. /**
  14156. * Generates a PMREM from an equirectangular texture, which can be either LDR
  14157. * or HDR. The ideal input image size is 1k (1024 x 512),
  14158. * as this matches best with the 256 x 256 cubemap output.
  14159. */
  14160. fromEquirectangular( equirectangular, renderTarget = null ) {
  14161. return this._fromTexture( equirectangular, renderTarget );
  14162. }
  14163. /**
  14164. * Generates a PMREM from an cubemap texture, which can be either LDR
  14165. * or HDR. The ideal input cube size is 256 x 256,
  14166. * as this matches best with the 256 x 256 cubemap output.
  14167. */
  14168. fromCubemap( cubemap, renderTarget = null ) {
  14169. return this._fromTexture( cubemap, renderTarget );
  14170. }
  14171. /**
  14172. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  14173. * your texture's network fetch for increased concurrency.
  14174. */
  14175. async compileCubemapShader() {
  14176. if ( this._cubemapMaterial === null ) {
  14177. this._cubemapMaterial = _getCubemapMaterial();
  14178. await this._compileMaterial( this._cubemapMaterial );
  14179. }
  14180. }
  14181. /**
  14182. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  14183. * your texture's network fetch for increased concurrency.
  14184. */
  14185. async compileEquirectangularShader() {
  14186. if ( this._equirectMaterial === null ) {
  14187. this._equirectMaterial = _getEquirectMaterial();
  14188. await this._compileMaterial( this._equirectMaterial );
  14189. }
  14190. }
  14191. /**
  14192. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  14193. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  14194. * one of them will cause any others to also become unusable.
  14195. */
  14196. dispose() {
  14197. this._dispose();
  14198. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  14199. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  14200. if ( this._backgroundBox !== null ) {
  14201. this._backgroundBox.geometry.dispose();
  14202. this._backgroundBox.material.dispose();
  14203. }
  14204. }
  14205. // private interface
  14206. _setSize( cubeSize ) {
  14207. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  14208. this._cubeSize = Math.pow( 2, this._lodMax );
  14209. }
  14210. _dispose() {
  14211. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  14212. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  14213. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  14214. this._lodPlanes[ i ].dispose();
  14215. }
  14216. }
  14217. _cleanup( outputTarget ) {
  14218. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  14219. outputTarget.scissorTest = false;
  14220. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  14221. }
  14222. _fromTexture( texture, renderTarget ) {
  14223. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  14224. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  14225. } else { // Equirectangular
  14226. this._setSize( texture.image.width / 4 );
  14227. }
  14228. _oldTarget = this._renderer.getRenderTarget();
  14229. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  14230. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  14231. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  14232. this._textureToCubeUV( texture, cubeUVRenderTarget );
  14233. this._applyPMREM( cubeUVRenderTarget );
  14234. this._cleanup( cubeUVRenderTarget );
  14235. return cubeUVRenderTarget;
  14236. }
  14237. _allocateTargets() {
  14238. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  14239. const height = 4 * this._cubeSize;
  14240. const params = {
  14241. magFilter: LinearFilter,
  14242. minFilter: LinearFilter,
  14243. generateMipmaps: false,
  14244. type: HalfFloatType,
  14245. format: RGBAFormat,
  14246. colorSpace: LinearSRGBColorSpace,
  14247. //depthBuffer: false
  14248. };
  14249. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  14250. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  14251. if ( this._pingPongRenderTarget !== null ) {
  14252. this._dispose();
  14253. }
  14254. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  14255. const { _lodMax } = this;
  14256. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  14257. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  14258. }
  14259. return cubeUVRenderTarget;
  14260. }
  14261. async _compileMaterial( material ) {
  14262. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  14263. await this._renderer.compile( tmpMesh, _flatCamera );
  14264. }
  14265. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  14266. const cubeCamera = _cubeCamera;
  14267. cubeCamera.near = near;
  14268. cubeCamera.far = far;
  14269. // px, py, pz, nx, ny, nz
  14270. const upSign = [ - 1, 1, - 1, - 1, - 1, - 1 ];
  14271. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  14272. const renderer = this._renderer;
  14273. const originalAutoClear = renderer.autoClear;
  14274. renderer.getClearColor( _clearColor );
  14275. renderer.autoClear = false;
  14276. let backgroundBox = this._backgroundBox;
  14277. if ( backgroundBox === null ) {
  14278. const backgroundMaterial = new MeshBasicMaterial( {
  14279. name: 'PMREM.Background',
  14280. side: BackSide,
  14281. depthWrite: false,
  14282. depthTest: false
  14283. } );
  14284. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  14285. }
  14286. let useSolidColor = false;
  14287. const background = scene.background;
  14288. if ( background ) {
  14289. if ( background.isColor ) {
  14290. backgroundBox.material.color.copy( background );
  14291. scene.background = null;
  14292. useSolidColor = true;
  14293. }
  14294. } else {
  14295. backgroundBox.material.color.copy( _clearColor );
  14296. useSolidColor = true;
  14297. }
  14298. renderer.setRenderTarget( cubeUVRenderTarget );
  14299. renderer.clear();
  14300. if ( useSolidColor ) {
  14301. renderer.render( backgroundBox, cubeCamera );
  14302. }
  14303. for ( let i = 0; i < 6; i ++ ) {
  14304. const col = i % 3;
  14305. if ( col === 0 ) {
  14306. cubeCamera.up.set( 0, upSign[ i ], 0 );
  14307. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  14308. } else if ( col === 1 ) {
  14309. cubeCamera.up.set( 0, 0, upSign[ i ] );
  14310. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  14311. } else {
  14312. cubeCamera.up.set( 0, upSign[ i ], 0 );
  14313. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  14314. }
  14315. const size = this._cubeSize;
  14316. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  14317. renderer.render( scene, cubeCamera );
  14318. }
  14319. renderer.autoClear = originalAutoClear;
  14320. scene.background = background;
  14321. }
  14322. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  14323. const renderer = this._renderer;
  14324. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  14325. if ( isCubeTexture ) {
  14326. if ( this._cubemapMaterial === null ) {
  14327. this._cubemapMaterial = _getCubemapMaterial( texture );
  14328. }
  14329. } else {
  14330. if ( this._equirectMaterial === null ) {
  14331. this._equirectMaterial = _getEquirectMaterial( texture );
  14332. }
  14333. }
  14334. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  14335. material.fragmentNode.value = texture;
  14336. const mesh = this._lodMeshes[ 0 ];
  14337. mesh.material = material;
  14338. const size = this._cubeSize;
  14339. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  14340. renderer.setRenderTarget( cubeUVRenderTarget );
  14341. renderer.render( mesh, _flatCamera );
  14342. }
  14343. _applyPMREM( cubeUVRenderTarget ) {
  14344. const renderer = this._renderer;
  14345. const autoClear = renderer.autoClear;
  14346. renderer.autoClear = false;
  14347. const n = this._lodPlanes.length;
  14348. for ( let i = 1; i < n; i ++ ) {
  14349. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  14350. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  14351. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  14352. }
  14353. renderer.autoClear = autoClear;
  14354. }
  14355. /**
  14356. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  14357. * vertically and horizontally, but this breaks down on a cube. Here we apply
  14358. * the blur latitudinally (around the poles), and then longitudinally (towards
  14359. * the poles) to approximate the orthogonally-separable blur. It is least
  14360. * accurate at the poles, but still does a decent job.
  14361. */
  14362. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  14363. const pingPongRenderTarget = this._pingPongRenderTarget;
  14364. this._halfBlur(
  14365. cubeUVRenderTarget,
  14366. pingPongRenderTarget,
  14367. lodIn,
  14368. lodOut,
  14369. sigma,
  14370. 'latitudinal',
  14371. poleAxis );
  14372. this._halfBlur(
  14373. pingPongRenderTarget,
  14374. cubeUVRenderTarget,
  14375. lodOut,
  14376. lodOut,
  14377. sigma,
  14378. 'longitudinal',
  14379. poleAxis );
  14380. }
  14381. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  14382. const renderer = this._renderer;
  14383. const blurMaterial = this._blurMaterial;
  14384. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  14385. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  14386. }
  14387. // Number of standard deviations at which to cut off the discrete approximation.
  14388. const STANDARD_DEVIATIONS = 3;
  14389. const blurMesh = this._lodMeshes[ lodOut ];
  14390. blurMesh.material = blurMaterial;
  14391. const blurUniforms = blurMaterial.uniforms;
  14392. const pixels = this._sizeLods[ lodIn ] - 1;
  14393. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  14394. const sigmaPixels = sigmaRadians / radiansPerPixel;
  14395. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  14396. if ( samples > MAX_SAMPLES ) {
  14397. console.warn( `sigmaRadians, ${
  14398. sigmaRadians}, is too large and will clip, as it requested ${
  14399. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  14400. }
  14401. const weights = [];
  14402. let sum = 0;
  14403. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  14404. const x = i / sigmaPixels;
  14405. const weight = Math.exp( - x * x / 2 );
  14406. weights.push( weight );
  14407. if ( i === 0 ) {
  14408. sum += weight;
  14409. } else if ( i < samples ) {
  14410. sum += 2 * weight;
  14411. }
  14412. }
  14413. for ( let i = 0; i < weights.length; i ++ ) {
  14414. weights[ i ] = weights[ i ] / sum;
  14415. }
  14416. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  14417. blurUniforms.envMap.value = targetIn.texture;
  14418. blurUniforms.samples.value = samples;
  14419. blurUniforms.weights.array = weights;
  14420. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  14421. if ( poleAxis ) {
  14422. blurUniforms.poleAxis.value = poleAxis;
  14423. }
  14424. const { _lodMax } = this;
  14425. blurUniforms.dTheta.value = radiansPerPixel;
  14426. blurUniforms.mipInt.value = _lodMax - lodIn;
  14427. const outputSize = this._sizeLods[ lodOut ];
  14428. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  14429. const y = 4 * ( this._cubeSize - outputSize );
  14430. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  14431. renderer.setRenderTarget( targetOut );
  14432. renderer.render( blurMesh, _flatCamera );
  14433. }
  14434. }
  14435. function _createPlanes( lodMax ) {
  14436. const lodPlanes = [];
  14437. const sizeLods = [];
  14438. const sigmas = [];
  14439. const lodMeshes = [];
  14440. let lod = lodMax;
  14441. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  14442. for ( let i = 0; i < totalLods; i ++ ) {
  14443. const sizeLod = Math.pow( 2, lod );
  14444. sizeLods.push( sizeLod );
  14445. let sigma = 1.0 / sizeLod;
  14446. if ( i > lodMax - LOD_MIN ) {
  14447. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  14448. } else if ( i === 0 ) {
  14449. sigma = 0;
  14450. }
  14451. sigmas.push( sigma );
  14452. const texelSize = 1.0 / ( sizeLod - 2 );
  14453. const min = - texelSize;
  14454. const max = 1 + texelSize;
  14455. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  14456. const cubeFaces = 6;
  14457. const vertices = 6;
  14458. const positionSize = 3;
  14459. const uvSize = 2;
  14460. const faceIndexSize = 1;
  14461. const position = new Float32Array( positionSize * vertices * cubeFaces );
  14462. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  14463. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  14464. for ( let face = 0; face < cubeFaces; face ++ ) {
  14465. const x = ( face % 3 ) * 2 / 3 - 1;
  14466. const y = face > 2 ? 0 : - 1;
  14467. const coordinates = [
  14468. x, y, 0,
  14469. x + 2 / 3, y, 0,
  14470. x + 2 / 3, y + 1, 0,
  14471. x, y, 0,
  14472. x + 2 / 3, y + 1, 0,
  14473. x, y + 1, 0
  14474. ];
  14475. const faceIdx = _faceLib[ face ];
  14476. position.set( coordinates, positionSize * vertices * faceIdx );
  14477. uv.set( uv1, uvSize * vertices * faceIdx );
  14478. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  14479. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  14480. }
  14481. const planes = new BufferGeometry();
  14482. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  14483. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  14484. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  14485. lodPlanes.push( planes );
  14486. lodMeshes.push( new Mesh( planes, null ) );
  14487. if ( lod > LOD_MIN ) {
  14488. lod --;
  14489. }
  14490. }
  14491. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  14492. }
  14493. function _createRenderTarget( width, height, params ) {
  14494. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  14495. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  14496. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  14497. cubeUVRenderTarget.texture.isPMREMTexture = true;
  14498. cubeUVRenderTarget.scissorTest = true;
  14499. return cubeUVRenderTarget;
  14500. }
  14501. function _setViewport( target, x, y, width, height ) {
  14502. target.viewport.set( x, y, width, height );
  14503. target.scissor.set( x, y, width, height );
  14504. }
  14505. function _getMaterial( type ) {
  14506. const material = new NodeMaterial();
  14507. material.depthTest = false;
  14508. material.depthWrite = false;
  14509. material.blending = NoBlending;
  14510. material.name = `PMREM_${ type }`;
  14511. return material;
  14512. }
  14513. function _getBlurShader( lodMax, width, height ) {
  14514. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  14515. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  14516. const dTheta = uniform( 0 );
  14517. const n = float( MAX_SAMPLES );
  14518. const latitudinal = uniform( 0 ); // false, bool
  14519. const samples = uniform( 1 ); // int
  14520. const envMap = texture( null );
  14521. const mipInt = uniform( 0 ); // int
  14522. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  14523. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  14524. const CUBEUV_MAX_MIP = float( lodMax );
  14525. const materialUniforms = {
  14526. n,
  14527. latitudinal,
  14528. weights,
  14529. poleAxis,
  14530. outputDirection,
  14531. dTheta,
  14532. samples,
  14533. envMap,
  14534. mipInt,
  14535. CUBEUV_TEXEL_WIDTH,
  14536. CUBEUV_TEXEL_HEIGHT,
  14537. CUBEUV_MAX_MIP
  14538. };
  14539. const material = _getMaterial( 'blur' );
  14540. material.uniforms = materialUniforms; // TODO: Move to outside of the material
  14541. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  14542. return material;
  14543. }
  14544. function _getCubemapMaterial( envTexture ) {
  14545. const material = _getMaterial( 'cubemap' );
  14546. material.fragmentNode = cubeTexture( envTexture, outputDirection );
  14547. return material;
  14548. }
  14549. function _getEquirectMaterial( envTexture ) {
  14550. const material = _getMaterial( 'equirect' );
  14551. material.fragmentNode = texture( envTexture, equirectUV( outputDirection ), 0 );
  14552. return material;
  14553. }
  14554. const rendererCache = new WeakMap();
  14555. const typeFromLength = new Map( [
  14556. [ 2, 'vec2' ],
  14557. [ 3, 'vec3' ],
  14558. [ 4, 'vec4' ],
  14559. [ 9, 'mat3' ],
  14560. [ 16, 'mat4' ]
  14561. ] );
  14562. const typeFromArray = new Map( [
  14563. [ Int8Array, 'int' ],
  14564. [ Int16Array, 'int' ],
  14565. [ Int32Array, 'int' ],
  14566. [ Uint8Array, 'uint' ],
  14567. [ Uint16Array, 'uint' ],
  14568. [ Uint32Array, 'uint' ],
  14569. [ Float32Array, 'float' ]
  14570. ] );
  14571. const toFloat = ( value ) => {
  14572. if ( /e/g.test( value ) ) {
  14573. return String( value ).replace( /\+/g, '' );
  14574. } else {
  14575. value = Number( value );
  14576. return value + ( value % 1 ? '' : '.0' );
  14577. }
  14578. };
  14579. class NodeBuilder {
  14580. constructor( object, renderer, parser ) {
  14581. this.object = object;
  14582. this.material = ( object && object.material ) || null;
  14583. this.geometry = ( object && object.geometry ) || null;
  14584. this.renderer = renderer;
  14585. this.parser = parser;
  14586. this.scene = null;
  14587. this.camera = null;
  14588. this.nodes = [];
  14589. this.sequentialNodes = [];
  14590. this.updateNodes = [];
  14591. this.updateBeforeNodes = [];
  14592. this.updateAfterNodes = [];
  14593. this.hashNodes = {};
  14594. this.monitor = null;
  14595. this.lightsNode = null;
  14596. this.environmentNode = null;
  14597. this.fogNode = null;
  14598. this.clippingContext = null;
  14599. this.vertexShader = null;
  14600. this.fragmentShader = null;
  14601. this.computeShader = null;
  14602. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  14603. this.flowCode = { vertex: '', fragment: '', compute: '' };
  14604. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  14605. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  14606. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  14607. this.bindingsIndexes = {};
  14608. this.bindGroups = null;
  14609. this.attributes = [];
  14610. this.bufferAttributes = [];
  14611. this.varyings = [];
  14612. this.codes = {};
  14613. this.vars = {};
  14614. this.flow = { code: '' };
  14615. this.chaining = [];
  14616. this.stack = stack();
  14617. this.stacks = [];
  14618. this.tab = '\t';
  14619. this.currentFunctionNode = null;
  14620. this.context = {
  14621. material: this.material
  14622. };
  14623. this.cache = new NodeCache();
  14624. this.globalCache = this.cache;
  14625. this.flowsData = new WeakMap();
  14626. this.shaderStage = null;
  14627. this.buildStage = null;
  14628. this.useComparisonMethod = false;
  14629. }
  14630. getBindGroupsCache() {
  14631. let bindGroupsCache = rendererCache.get( this.renderer );
  14632. if ( bindGroupsCache === undefined ) {
  14633. bindGroupsCache = new ChainMap();
  14634. rendererCache.set( this.renderer, bindGroupsCache );
  14635. }
  14636. return bindGroupsCache;
  14637. }
  14638. createRenderTarget( width, height, options ) {
  14639. return new RenderTarget( width, height, options );
  14640. }
  14641. createCubeRenderTarget( size, options ) {
  14642. return new CubeRenderTarget( size, options );
  14643. }
  14644. createPMREMGenerator() {
  14645. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  14646. return new PMREMGenerator( this.renderer );
  14647. }
  14648. includes( node ) {
  14649. return this.nodes.includes( node );
  14650. }
  14651. _getBindGroup( groupName, bindings ) {
  14652. const bindGroupsCache = this.getBindGroupsCache();
  14653. //
  14654. const bindingsArray = [];
  14655. let sharedGroup = true;
  14656. for ( const binding of bindings ) {
  14657. bindingsArray.push( binding );
  14658. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  14659. }
  14660. //
  14661. let bindGroup;
  14662. if ( sharedGroup ) {
  14663. bindGroup = bindGroupsCache.get( bindingsArray );
  14664. if ( bindGroup === undefined ) {
  14665. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  14666. bindGroupsCache.set( bindingsArray, bindGroup );
  14667. }
  14668. } else {
  14669. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  14670. }
  14671. return bindGroup;
  14672. }
  14673. getBindGroupArray( groupName, shaderStage ) {
  14674. const bindings = this.bindings[ shaderStage ];
  14675. let bindGroup = bindings[ groupName ];
  14676. if ( bindGroup === undefined ) {
  14677. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  14678. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  14679. }
  14680. bindings[ groupName ] = bindGroup = [];
  14681. }
  14682. return bindGroup;
  14683. }
  14684. getBindings() {
  14685. let bindingsGroups = this.bindGroups;
  14686. if ( bindingsGroups === null ) {
  14687. const groups = {};
  14688. const bindings = this.bindings;
  14689. for ( const shaderStage of shaderStages ) {
  14690. for ( const groupName in bindings[ shaderStage ] ) {
  14691. const uniforms = bindings[ shaderStage ][ groupName ];
  14692. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  14693. groupUniforms.push( ...uniforms );
  14694. }
  14695. }
  14696. bindingsGroups = [];
  14697. for ( const groupName in groups ) {
  14698. const group = groups[ groupName ];
  14699. const bindingsGroup = this._getBindGroup( groupName, group );
  14700. bindingsGroups.push( bindingsGroup );
  14701. }
  14702. this.bindGroups = bindingsGroups;
  14703. }
  14704. return bindingsGroups;
  14705. }
  14706. sortBindingGroups() {
  14707. const bindingsGroups = this.getBindings();
  14708. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  14709. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  14710. const bindingGroup = bindingsGroups[ i ];
  14711. this.bindingsIndexes[ bindingGroup.name ].group = i;
  14712. bindingGroup.index = i;
  14713. }
  14714. }
  14715. setHashNode( node, hash ) {
  14716. this.hashNodes[ hash ] = node;
  14717. }
  14718. addNode( node ) {
  14719. if ( this.nodes.includes( node ) === false ) {
  14720. this.nodes.push( node );
  14721. this.setHashNode( node, node.getHash( this ) );
  14722. }
  14723. }
  14724. addSequentialNode( node ) {
  14725. if ( this.sequentialNodes.includes( node ) === false ) {
  14726. this.sequentialNodes.push( node );
  14727. }
  14728. }
  14729. buildUpdateNodes() {
  14730. for ( const node of this.nodes ) {
  14731. const updateType = node.getUpdateType();
  14732. if ( updateType !== NodeUpdateType.NONE ) {
  14733. this.updateNodes.push( node.getSelf() );
  14734. }
  14735. }
  14736. for ( const node of this.sequentialNodes ) {
  14737. const updateBeforeType = node.getUpdateBeforeType();
  14738. const updateAfterType = node.getUpdateAfterType();
  14739. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  14740. this.updateBeforeNodes.push( node.getSelf() );
  14741. }
  14742. if ( updateAfterType !== NodeUpdateType.NONE ) {
  14743. this.updateAfterNodes.push( node.getSelf() );
  14744. }
  14745. }
  14746. }
  14747. get currentNode() {
  14748. return this.chaining[ this.chaining.length - 1 ];
  14749. }
  14750. isFilteredTexture( texture ) {
  14751. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  14752. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  14753. }
  14754. addChain( node ) {
  14755. /*
  14756. if ( this.chaining.indexOf( node ) !== - 1 ) {
  14757. console.warn( 'Recursive node: ', node );
  14758. }
  14759. */
  14760. this.chaining.push( node );
  14761. }
  14762. removeChain( node ) {
  14763. const lastChain = this.chaining.pop();
  14764. if ( lastChain !== node ) {
  14765. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  14766. }
  14767. }
  14768. getMethod( method ) {
  14769. return method;
  14770. }
  14771. getNodeFromHash( hash ) {
  14772. return this.hashNodes[ hash ];
  14773. }
  14774. addFlow( shaderStage, node ) {
  14775. this.flowNodes[ shaderStage ].push( node );
  14776. return node;
  14777. }
  14778. setContext( context ) {
  14779. this.context = context;
  14780. }
  14781. getContext() {
  14782. return this.context;
  14783. }
  14784. getSharedContext() {
  14785. ({ ...this.context });
  14786. return this.context;
  14787. }
  14788. setCache( cache ) {
  14789. this.cache = cache;
  14790. }
  14791. getCache() {
  14792. return this.cache;
  14793. }
  14794. getCacheFromNode( node, parent = true ) {
  14795. const data = this.getDataFromNode( node );
  14796. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  14797. return data.cache;
  14798. }
  14799. isAvailable( /*name*/ ) {
  14800. return false;
  14801. }
  14802. getVertexIndex() {
  14803. console.warn( 'Abstract function.' );
  14804. }
  14805. getInstanceIndex() {
  14806. console.warn( 'Abstract function.' );
  14807. }
  14808. getDrawIndex() {
  14809. console.warn( 'Abstract function.' );
  14810. }
  14811. getFrontFacing() {
  14812. console.warn( 'Abstract function.' );
  14813. }
  14814. getFragCoord() {
  14815. console.warn( 'Abstract function.' );
  14816. }
  14817. isFlipY() {
  14818. return false;
  14819. }
  14820. increaseUsage( node ) {
  14821. const nodeData = this.getDataFromNode( node );
  14822. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  14823. return nodeData.usageCount;
  14824. }
  14825. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  14826. console.warn( 'Abstract function.' );
  14827. }
  14828. generateTextureLod( /* texture, textureProperty, uvSnippet, levelSnippet */ ) {
  14829. console.warn( 'Abstract function.' );
  14830. }
  14831. generateConst( type, value = null ) {
  14832. if ( value === null ) {
  14833. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  14834. else if ( type === 'bool' ) value = false;
  14835. else if ( type === 'color' ) value = new Color();
  14836. else if ( type === 'vec2' ) value = new Vector2();
  14837. else if ( type === 'vec3' ) value = new Vector3();
  14838. else if ( type === 'vec4' ) value = new Vector4();
  14839. }
  14840. if ( type === 'float' ) return toFloat( value );
  14841. if ( type === 'int' ) return `${ Math.round( value ) }`;
  14842. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  14843. if ( type === 'bool' ) return value ? 'true' : 'false';
  14844. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  14845. const typeLength = this.getTypeLength( type );
  14846. const componentType = this.getComponentType( type );
  14847. const generateConst = value => this.generateConst( componentType, value );
  14848. if ( typeLength === 2 ) {
  14849. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  14850. } else if ( typeLength === 3 ) {
  14851. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  14852. } else if ( typeLength === 4 ) {
  14853. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  14854. } else if ( typeLength > 4 && value && ( value.isMatrix3 || value.isMatrix4 ) ) {
  14855. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  14856. } else if ( typeLength > 4 ) {
  14857. return `${ this.getType( type ) }()`;
  14858. }
  14859. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  14860. }
  14861. getType( type ) {
  14862. if ( type === 'color' ) return 'vec3';
  14863. return type;
  14864. }
  14865. hasGeometryAttribute( name ) {
  14866. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  14867. }
  14868. getAttribute( name, type ) {
  14869. const attributes = this.attributes;
  14870. // find attribute
  14871. for ( const attribute of attributes ) {
  14872. if ( attribute.name === name ) {
  14873. return attribute;
  14874. }
  14875. }
  14876. // create a new if no exist
  14877. const attribute = new NodeAttribute( name, type );
  14878. attributes.push( attribute );
  14879. return attribute;
  14880. }
  14881. getPropertyName( node/*, shaderStage*/ ) {
  14882. return node.name;
  14883. }
  14884. isVector( type ) {
  14885. return /vec\d/.test( type );
  14886. }
  14887. isMatrix( type ) {
  14888. return /mat\d/.test( type );
  14889. }
  14890. isReference( type ) {
  14891. return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  14892. }
  14893. needsToWorkingColorSpace( /*texture*/ ) {
  14894. return false;
  14895. }
  14896. getComponentTypeFromTexture( texture ) {
  14897. const type = texture.type;
  14898. if ( texture.isDataTexture ) {
  14899. if ( type === IntType ) return 'int';
  14900. if ( type === UnsignedIntType ) return 'uint';
  14901. }
  14902. return 'float';
  14903. }
  14904. getElementType( type ) {
  14905. if ( type === 'mat2' ) return 'vec2';
  14906. if ( type === 'mat3' ) return 'vec3';
  14907. if ( type === 'mat4' ) return 'vec4';
  14908. return this.getComponentType( type );
  14909. }
  14910. getComponentType( type ) {
  14911. type = this.getVectorType( type );
  14912. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  14913. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  14914. if ( componentType === null ) return null;
  14915. if ( componentType[ 1 ] === 'b' ) return 'bool';
  14916. if ( componentType[ 1 ] === 'i' ) return 'int';
  14917. if ( componentType[ 1 ] === 'u' ) return 'uint';
  14918. return 'float';
  14919. }
  14920. getVectorType( type ) {
  14921. if ( type === 'color' ) return 'vec3';
  14922. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  14923. return type;
  14924. }
  14925. getTypeFromLength( length, componentType = 'float' ) {
  14926. if ( length === 1 ) return componentType;
  14927. const baseType = typeFromLength.get( length );
  14928. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  14929. return prefix + baseType;
  14930. }
  14931. getTypeFromArray( array ) {
  14932. return typeFromArray.get( array.constructor );
  14933. }
  14934. getTypeFromAttribute( attribute ) {
  14935. let dataAttribute = attribute;
  14936. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  14937. const array = dataAttribute.array;
  14938. const itemSize = attribute.itemSize;
  14939. const normalized = attribute.normalized;
  14940. let arrayType;
  14941. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  14942. arrayType = this.getTypeFromArray( array );
  14943. }
  14944. return this.getTypeFromLength( itemSize, arrayType );
  14945. }
  14946. getTypeLength( type ) {
  14947. const vecType = this.getVectorType( type );
  14948. const vecNum = /vec([2-4])/.exec( vecType );
  14949. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  14950. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  14951. if ( /mat2/.test( type ) === true ) return 4;
  14952. if ( /mat3/.test( type ) === true ) return 9;
  14953. if ( /mat4/.test( type ) === true ) return 16;
  14954. return 0;
  14955. }
  14956. getVectorFromMatrix( type ) {
  14957. return type.replace( 'mat', 'vec' );
  14958. }
  14959. changeComponentType( type, newComponentType ) {
  14960. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  14961. }
  14962. getIntegerType( type ) {
  14963. const componentType = this.getComponentType( type );
  14964. if ( componentType === 'int' || componentType === 'uint' ) return type;
  14965. return this.changeComponentType( type, 'int' );
  14966. }
  14967. addStack() {
  14968. this.stack = stack( this.stack );
  14969. this.stacks.push( getCurrentStack() || this.stack );
  14970. setCurrentStack( this.stack );
  14971. return this.stack;
  14972. }
  14973. removeStack() {
  14974. const lastStack = this.stack;
  14975. this.stack = lastStack.parent;
  14976. setCurrentStack( this.stacks.pop() );
  14977. return lastStack;
  14978. }
  14979. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  14980. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  14981. let nodeData = cache.getData( node );
  14982. if ( nodeData === undefined ) {
  14983. nodeData = {};
  14984. cache.setData( node, nodeData );
  14985. }
  14986. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  14987. return nodeData[ shaderStage ];
  14988. }
  14989. getNodeProperties( node, shaderStage = 'any' ) {
  14990. const nodeData = this.getDataFromNode( node, shaderStage );
  14991. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  14992. }
  14993. getBufferAttributeFromNode( node, type ) {
  14994. const nodeData = this.getDataFromNode( node );
  14995. let bufferAttribute = nodeData.bufferAttribute;
  14996. if ( bufferAttribute === undefined ) {
  14997. const index = this.uniforms.index ++;
  14998. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  14999. this.bufferAttributes.push( bufferAttribute );
  15000. nodeData.bufferAttribute = bufferAttribute;
  15001. }
  15002. return bufferAttribute;
  15003. }
  15004. getStructTypeFromNode( node, shaderStage = this.shaderStage ) {
  15005. const nodeData = this.getDataFromNode( node, shaderStage );
  15006. if ( nodeData.structType === undefined ) {
  15007. const index = this.structs.index ++;
  15008. node.name = `StructType${ index }`;
  15009. this.structs[ shaderStage ].push( node );
  15010. nodeData.structType = node;
  15011. }
  15012. return node;
  15013. }
  15014. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  15015. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  15016. let nodeUniform = nodeData.uniform;
  15017. if ( nodeUniform === undefined ) {
  15018. const index = this.uniforms.index ++;
  15019. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  15020. this.uniforms[ shaderStage ].push( nodeUniform );
  15021. nodeData.uniform = nodeUniform;
  15022. }
  15023. return nodeUniform;
  15024. }
  15025. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage ) {
  15026. const nodeData = this.getDataFromNode( node, shaderStage );
  15027. let nodeVar = nodeData.variable;
  15028. if ( nodeVar === undefined ) {
  15029. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  15030. if ( name === null ) name = 'nodeVar' + vars.length;
  15031. nodeVar = new NodeVar( name, type );
  15032. vars.push( nodeVar );
  15033. nodeData.variable = nodeVar;
  15034. }
  15035. return nodeVar;
  15036. }
  15037. getVaryingFromNode( node, name = null, type = node.getNodeType( this ) ) {
  15038. const nodeData = this.getDataFromNode( node, 'any' );
  15039. let nodeVarying = nodeData.varying;
  15040. if ( nodeVarying === undefined ) {
  15041. const varyings = this.varyings;
  15042. const index = varyings.length;
  15043. if ( name === null ) name = 'nodeVarying' + index;
  15044. nodeVarying = new NodeVarying( name, type );
  15045. varyings.push( nodeVarying );
  15046. nodeData.varying = nodeVarying;
  15047. }
  15048. return nodeVarying;
  15049. }
  15050. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  15051. const nodeData = this.getDataFromNode( node );
  15052. let nodeCode = nodeData.code;
  15053. if ( nodeCode === undefined ) {
  15054. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  15055. const index = codes.length;
  15056. nodeCode = new NodeCode( 'nodeCode' + index, type );
  15057. codes.push( nodeCode );
  15058. nodeData.code = nodeCode;
  15059. }
  15060. return nodeCode;
  15061. }
  15062. addFlowCodeHierarchy( node, nodeBlock ) {
  15063. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  15064. let needsFlowCode = true;
  15065. let nodeBlockHierarchy = nodeBlock;
  15066. while ( nodeBlockHierarchy ) {
  15067. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  15068. needsFlowCode = false;
  15069. break;
  15070. }
  15071. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  15072. }
  15073. if ( needsFlowCode ) {
  15074. for ( const flowCode of flowCodes ) {
  15075. this.addLineFlowCode( flowCode );
  15076. }
  15077. }
  15078. }
  15079. addLineFlowCodeBlock( node, code, nodeBlock ) {
  15080. const nodeData = this.getDataFromNode( node );
  15081. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  15082. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  15083. flowCodes.push( code );
  15084. codeBlock.set( nodeBlock, true );
  15085. }
  15086. addLineFlowCode( code, node = null ) {
  15087. if ( code === '' ) return this;
  15088. if ( node !== null && this.context.nodeBlock ) {
  15089. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  15090. }
  15091. code = this.tab + code;
  15092. if ( ! /;\s*$/.test( code ) ) {
  15093. code = code + ';\n';
  15094. }
  15095. this.flow.code += code;
  15096. return this;
  15097. }
  15098. addFlowCode( code ) {
  15099. this.flow.code += code;
  15100. return this;
  15101. }
  15102. addFlowTab() {
  15103. this.tab += '\t';
  15104. return this;
  15105. }
  15106. removeFlowTab() {
  15107. this.tab = this.tab.slice( 0, - 1 );
  15108. return this;
  15109. }
  15110. getFlowData( node/*, shaderStage*/ ) {
  15111. return this.flowsData.get( node );
  15112. }
  15113. flowNode( node ) {
  15114. const output = node.getNodeType( this );
  15115. const flowData = this.flowChildNode( node, output );
  15116. this.flowsData.set( node, flowData );
  15117. return flowData;
  15118. }
  15119. buildFunctionNode( shaderNode ) {
  15120. const fn = new FunctionNode();
  15121. const previous = this.currentFunctionNode;
  15122. this.currentFunctionNode = fn;
  15123. fn.code = this.buildFunctionCode( shaderNode );
  15124. this.currentFunctionNode = previous;
  15125. return fn;
  15126. }
  15127. flowShaderNode( shaderNode ) {
  15128. const layout = shaderNode.layout;
  15129. const inputs = {
  15130. [ Symbol.iterator ]() {
  15131. let index = 0;
  15132. const values = Object.values( this );
  15133. return {
  15134. next: () => ( {
  15135. value: values[ index ],
  15136. done: index ++ >= values.length
  15137. } )
  15138. };
  15139. }
  15140. };
  15141. for ( const input of layout.inputs ) {
  15142. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  15143. }
  15144. //
  15145. shaderNode.layout = null;
  15146. const callNode = shaderNode.call( inputs );
  15147. const flowData = this.flowStagesNode( callNode, layout.type );
  15148. shaderNode.layout = layout;
  15149. return flowData;
  15150. }
  15151. flowStagesNode( node, output = null ) {
  15152. const previousFlow = this.flow;
  15153. const previousVars = this.vars;
  15154. const previousCache = this.cache;
  15155. const previousBuildStage = this.buildStage;
  15156. const previousStack = this.stack;
  15157. const flow = {
  15158. code: ''
  15159. };
  15160. this.flow = flow;
  15161. this.vars = {};
  15162. this.cache = new NodeCache();
  15163. this.stack = stack();
  15164. for ( const buildStage of defaultBuildStages ) {
  15165. this.setBuildStage( buildStage );
  15166. flow.result = node.build( this, output );
  15167. }
  15168. flow.vars = this.getVars( this.shaderStage );
  15169. this.flow = previousFlow;
  15170. this.vars = previousVars;
  15171. this.cache = previousCache;
  15172. this.stack = previousStack;
  15173. this.setBuildStage( previousBuildStage );
  15174. return flow;
  15175. }
  15176. getFunctionOperator() {
  15177. return null;
  15178. }
  15179. flowChildNode( node, output = null ) {
  15180. const previousFlow = this.flow;
  15181. const flow = {
  15182. code: ''
  15183. };
  15184. this.flow = flow;
  15185. flow.result = node.build( this, output );
  15186. this.flow = previousFlow;
  15187. return flow;
  15188. }
  15189. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  15190. const previousShaderStage = this.shaderStage;
  15191. this.setShaderStage( shaderStage );
  15192. const flowData = this.flowChildNode( node, output );
  15193. if ( propertyName !== null ) {
  15194. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  15195. }
  15196. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  15197. this.setShaderStage( previousShaderStage );
  15198. return flowData;
  15199. }
  15200. getAttributesArray() {
  15201. return this.attributes.concat( this.bufferAttributes );
  15202. }
  15203. getAttributes( /*shaderStage*/ ) {
  15204. console.warn( 'Abstract function.' );
  15205. }
  15206. getVaryings( /*shaderStage*/ ) {
  15207. console.warn( 'Abstract function.' );
  15208. }
  15209. getVar( type, name ) {
  15210. return `${ this.getType( type ) } ${ name }`;
  15211. }
  15212. getVars( shaderStage ) {
  15213. let snippet = '';
  15214. const vars = this.vars[ shaderStage ];
  15215. if ( vars !== undefined ) {
  15216. for ( const variable of vars ) {
  15217. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  15218. }
  15219. }
  15220. return snippet;
  15221. }
  15222. getUniforms( /*shaderStage*/ ) {
  15223. console.warn( 'Abstract function.' );
  15224. }
  15225. getCodes( shaderStage ) {
  15226. const codes = this.codes[ shaderStage ];
  15227. let code = '';
  15228. if ( codes !== undefined ) {
  15229. for ( const nodeCode of codes ) {
  15230. code += nodeCode.code + '\n';
  15231. }
  15232. }
  15233. return code;
  15234. }
  15235. getHash() {
  15236. return this.vertexShader + this.fragmentShader + this.computeShader;
  15237. }
  15238. setShaderStage( shaderStage ) {
  15239. this.shaderStage = shaderStage;
  15240. }
  15241. getShaderStage() {
  15242. return this.shaderStage;
  15243. }
  15244. setBuildStage( buildStage ) {
  15245. this.buildStage = buildStage;
  15246. }
  15247. getBuildStage() {
  15248. return this.buildStage;
  15249. }
  15250. buildCode() {
  15251. console.warn( 'Abstract function.' );
  15252. }
  15253. build() {
  15254. const { object, material, renderer } = this;
  15255. if ( material !== null ) {
  15256. let nodeMaterial = renderer.library.fromMaterial( material );
  15257. if ( nodeMaterial === null ) {
  15258. console.error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  15259. nodeMaterial = new NodeMaterial();
  15260. }
  15261. nodeMaterial.build( this );
  15262. } else {
  15263. this.addFlow( 'compute', object );
  15264. }
  15265. // setup() -> stage 1: create possible new nodes and returns an output reference node
  15266. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  15267. // generate() -> stage 3: generate shader
  15268. for ( const buildStage of defaultBuildStages ) {
  15269. this.setBuildStage( buildStage );
  15270. if ( this.context.vertex && this.context.vertex.isNode ) {
  15271. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  15272. }
  15273. for ( const shaderStage of shaderStages ) {
  15274. this.setShaderStage( shaderStage );
  15275. const flowNodes = this.flowNodes[ shaderStage ];
  15276. for ( const node of flowNodes ) {
  15277. if ( buildStage === 'generate' ) {
  15278. this.flowNode( node );
  15279. } else {
  15280. node.build( this );
  15281. }
  15282. }
  15283. }
  15284. }
  15285. this.setBuildStage( null );
  15286. this.setShaderStage( null );
  15287. // stage 4: build code for a specific output
  15288. this.buildCode();
  15289. this.buildUpdateNodes();
  15290. return this;
  15291. }
  15292. getNodeUniform( uniformNode, type ) {
  15293. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  15294. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  15295. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  15296. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  15297. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  15298. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  15299. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  15300. throw new Error( `Uniform "${type}" not declared.` );
  15301. }
  15302. createNodeMaterial( type = 'NodeMaterial' ) { // @deprecated, r168
  15303. throw new Error( `THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${ type }() instead.` );
  15304. }
  15305. format( snippet, fromType, toType ) {
  15306. fromType = this.getVectorType( fromType );
  15307. toType = this.getVectorType( toType );
  15308. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  15309. return snippet;
  15310. }
  15311. const fromTypeLength = this.getTypeLength( fromType );
  15312. const toTypeLength = this.getTypeLength( toType );
  15313. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  15314. return `${ this.getType( toType ) }(${ snippet }[0].xyz, ${ snippet }[1].xyz, ${ snippet }[2].xyz)`;
  15315. }
  15316. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  15317. return `${ this.getType( toType ) }(${ snippet }[0].xy, ${ snippet }[1].xy)`;
  15318. }
  15319. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  15320. // @TODO: ignore for now
  15321. return snippet;
  15322. }
  15323. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  15324. // @TODO: ignore for now
  15325. return snippet;
  15326. }
  15327. if ( fromTypeLength === toTypeLength ) {
  15328. return `${ this.getType( toType ) }( ${ snippet } )`;
  15329. }
  15330. if ( fromTypeLength > toTypeLength ) {
  15331. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  15332. }
  15333. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  15334. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  15335. }
  15336. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  15337. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  15338. }
  15339. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  15340. // convert a number value to vector type, e.g:
  15341. // vec3( 1u ) -> vec3( float( 1u ) )
  15342. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  15343. }
  15344. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  15345. }
  15346. getSignature() {
  15347. return `// Three.js r${ REVISION } - Node System\n`;
  15348. }
  15349. }
  15350. class NodeFrame {
  15351. constructor() {
  15352. this.time = 0;
  15353. this.deltaTime = 0;
  15354. this.frameId = 0;
  15355. this.renderId = 0;
  15356. this.startTime = null;
  15357. this.updateMap = new WeakMap();
  15358. this.updateBeforeMap = new WeakMap();
  15359. this.updateAfterMap = new WeakMap();
  15360. this.renderer = null;
  15361. this.material = null;
  15362. this.camera = null;
  15363. this.object = null;
  15364. this.scene = null;
  15365. }
  15366. _getMaps( referenceMap, nodeRef ) {
  15367. let maps = referenceMap.get( nodeRef );
  15368. if ( maps === undefined ) {
  15369. maps = {
  15370. renderMap: new WeakMap(),
  15371. frameMap: new WeakMap()
  15372. };
  15373. referenceMap.set( nodeRef, maps );
  15374. }
  15375. return maps;
  15376. }
  15377. updateBeforeNode( node ) {
  15378. const updateType = node.getUpdateBeforeType();
  15379. const reference = node.updateReference( this );
  15380. if ( updateType === NodeUpdateType.FRAME ) {
  15381. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  15382. if ( frameMap.get( reference ) !== this.frameId ) {
  15383. if ( node.updateBefore( this ) !== false ) {
  15384. frameMap.set( reference, this.frameId );
  15385. }
  15386. }
  15387. } else if ( updateType === NodeUpdateType.RENDER ) {
  15388. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  15389. if ( renderMap.get( reference ) !== this.renderId ) {
  15390. if ( node.updateBefore( this ) !== false ) {
  15391. renderMap.set( reference, this.renderId );
  15392. }
  15393. }
  15394. } else if ( updateType === NodeUpdateType.OBJECT ) {
  15395. node.updateBefore( this );
  15396. }
  15397. }
  15398. updateAfterNode( node ) {
  15399. const updateType = node.getUpdateAfterType();
  15400. const reference = node.updateReference( this );
  15401. if ( updateType === NodeUpdateType.FRAME ) {
  15402. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  15403. if ( frameMap.get( reference ) !== this.frameId ) {
  15404. if ( node.updateAfter( this ) !== false ) {
  15405. frameMap.set( reference, this.frameId );
  15406. }
  15407. }
  15408. } else if ( updateType === NodeUpdateType.RENDER ) {
  15409. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  15410. if ( renderMap.get( reference ) !== this.renderId ) {
  15411. if ( node.updateAfter( this ) !== false ) {
  15412. renderMap.set( reference, this.renderId );
  15413. }
  15414. }
  15415. } else if ( updateType === NodeUpdateType.OBJECT ) {
  15416. node.updateAfter( this );
  15417. }
  15418. }
  15419. updateNode( node ) {
  15420. const updateType = node.getUpdateType();
  15421. const reference = node.updateReference( this );
  15422. if ( updateType === NodeUpdateType.FRAME ) {
  15423. const { frameMap } = this._getMaps( this.updateMap, reference );
  15424. if ( frameMap.get( reference ) !== this.frameId ) {
  15425. if ( node.update( this ) !== false ) {
  15426. frameMap.set( reference, this.frameId );
  15427. }
  15428. }
  15429. } else if ( updateType === NodeUpdateType.RENDER ) {
  15430. const { renderMap } = this._getMaps( this.updateMap, reference );
  15431. if ( renderMap.get( reference ) !== this.renderId ) {
  15432. if ( node.update( this ) !== false ) {
  15433. renderMap.set( reference, this.renderId );
  15434. }
  15435. }
  15436. } else if ( updateType === NodeUpdateType.OBJECT ) {
  15437. node.update( this );
  15438. }
  15439. }
  15440. update() {
  15441. this.frameId ++;
  15442. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  15443. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  15444. this.lastTime = performance.now();
  15445. this.time += this.deltaTime;
  15446. }
  15447. }
  15448. class NodeFunctionInput {
  15449. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  15450. this.type = type;
  15451. this.name = name;
  15452. this.count = count;
  15453. this.qualifier = qualifier;
  15454. this.isConst = isConst;
  15455. }
  15456. }
  15457. NodeFunctionInput.isNodeFunctionInput = true;
  15458. class DirectionalLightNode extends AnalyticLightNode {
  15459. static get type() {
  15460. return 'DirectionalLightNode';
  15461. }
  15462. constructor( light = null ) {
  15463. super( light );
  15464. }
  15465. setup( builder ) {
  15466. super.setup( builder );
  15467. const lightingModel = builder.context.lightingModel;
  15468. const lightColor = this.colorNode;
  15469. const lightDirection = lightTargetDirection( this.light );
  15470. const reflectedLight = builder.context.reflectedLight;
  15471. lightingModel.direct( {
  15472. lightDirection,
  15473. lightColor,
  15474. reflectedLight
  15475. }, builder.stack, builder );
  15476. }
  15477. }
  15478. const _matrix41 = /*@__PURE__*/ new Matrix4();
  15479. const _matrix42 = /*@__PURE__*/ new Matrix4();
  15480. let ltcLib = null;
  15481. class RectAreaLightNode extends AnalyticLightNode {
  15482. static get type() {
  15483. return 'RectAreaLightNode';
  15484. }
  15485. constructor( light = null ) {
  15486. super( light );
  15487. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  15488. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  15489. this.updateType = NodeUpdateType.RENDER;
  15490. }
  15491. update( frame ) {
  15492. super.update( frame );
  15493. const { light } = this;
  15494. const viewMatrix = frame.camera.matrixWorldInverse;
  15495. _matrix42.identity();
  15496. _matrix41.copy( light.matrixWorld );
  15497. _matrix41.premultiply( viewMatrix );
  15498. _matrix42.extractRotation( _matrix41 );
  15499. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  15500. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  15501. this.halfWidth.value.applyMatrix4( _matrix42 );
  15502. this.halfHeight.value.applyMatrix4( _matrix42 );
  15503. }
  15504. setup( builder ) {
  15505. super.setup( builder );
  15506. let ltc_1, ltc_2;
  15507. if ( builder.isAvailable( 'float32Filterable' ) ) {
  15508. ltc_1 = texture( ltcLib.LTC_FLOAT_1 );
  15509. ltc_2 = texture( ltcLib.LTC_FLOAT_2 );
  15510. } else {
  15511. ltc_1 = texture( ltcLib.LTC_HALF_1 );
  15512. ltc_2 = texture( ltcLib.LTC_HALF_2 );
  15513. }
  15514. const { colorNode, light } = this;
  15515. const lightingModel = builder.context.lightingModel;
  15516. const lightPosition = lightViewPosition( light );
  15517. const reflectedLight = builder.context.reflectedLight;
  15518. lightingModel.directRectArea( {
  15519. lightColor: colorNode,
  15520. lightPosition,
  15521. halfWidth: this.halfWidth,
  15522. halfHeight: this.halfHeight,
  15523. reflectedLight,
  15524. ltc_1,
  15525. ltc_2
  15526. }, builder.stack, builder );
  15527. }
  15528. static setLTC( ltc ) {
  15529. ltcLib = ltc;
  15530. }
  15531. }
  15532. class SpotLightNode extends AnalyticLightNode {
  15533. static get type() {
  15534. return 'SpotLightNode';
  15535. }
  15536. constructor( light = null ) {
  15537. super( light );
  15538. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  15539. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  15540. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  15541. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  15542. }
  15543. update( frame ) {
  15544. super.update( frame );
  15545. const { light } = this;
  15546. this.coneCosNode.value = Math.cos( light.angle );
  15547. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  15548. this.cutoffDistanceNode.value = light.distance;
  15549. this.decayExponentNode.value = light.decay;
  15550. }
  15551. getSpotAttenuation( angleCosine ) {
  15552. const { coneCosNode, penumbraCosNode } = this;
  15553. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  15554. }
  15555. setup( builder ) {
  15556. super.setup( builder );
  15557. const lightingModel = builder.context.lightingModel;
  15558. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  15559. const lVector = lightViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  15560. const lightDirection = lVector.normalize();
  15561. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  15562. const spotAttenuation = this.getSpotAttenuation( angleCos );
  15563. const lightDistance = lVector.length();
  15564. const lightAttenuation = getDistanceAttenuation( {
  15565. lightDistance,
  15566. cutoffDistance: cutoffDistanceNode,
  15567. decayExponent: decayExponentNode
  15568. } );
  15569. const lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  15570. const reflectedLight = builder.context.reflectedLight;
  15571. lightingModel.direct( {
  15572. lightDirection,
  15573. lightColor,
  15574. reflectedLight
  15575. }, builder.stack, builder );
  15576. }
  15577. }
  15578. class IESSpotLightNode extends SpotLightNode {
  15579. static get type() {
  15580. return 'IESSpotLightNode';
  15581. }
  15582. getSpotAttenuation( angleCosine ) {
  15583. const iesMap = this.light.iesMap;
  15584. let spotAttenuation = null;
  15585. if ( iesMap && iesMap.isTexture === true ) {
  15586. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  15587. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  15588. } else {
  15589. spotAttenuation = super.getSpotAttenuation( angleCosine );
  15590. }
  15591. return spotAttenuation;
  15592. }
  15593. }
  15594. class AmbientLightNode extends AnalyticLightNode {
  15595. static get type() {
  15596. return 'AmbientLightNode';
  15597. }
  15598. constructor( light = null ) {
  15599. super( light );
  15600. }
  15601. setup( { context } ) {
  15602. context.irradiance.addAssign( this.colorNode );
  15603. }
  15604. }
  15605. class HemisphereLightNode extends AnalyticLightNode {
  15606. static get type() {
  15607. return 'HemisphereLightNode';
  15608. }
  15609. constructor( light = null ) {
  15610. super( light );
  15611. this.lightPositionNode = lightPosition( light );
  15612. this.lightDirectionNode = this.lightPositionNode.normalize();
  15613. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  15614. }
  15615. update( frame ) {
  15616. const { light } = this;
  15617. super.update( frame );
  15618. this.lightPositionNode.object3d = light;
  15619. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  15620. }
  15621. setup( builder ) {
  15622. const { colorNode, groundColorNode, lightDirectionNode } = this;
  15623. const dotNL = normalView.dot( lightDirectionNode );
  15624. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  15625. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  15626. builder.context.irradiance.addAssign( irradiance );
  15627. }
  15628. }
  15629. class LightProbeNode extends AnalyticLightNode {
  15630. static get type() {
  15631. return 'LightProbeNode';
  15632. }
  15633. constructor( light = null ) {
  15634. super( light );
  15635. const array = [];
  15636. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  15637. this.lightProbe = uniformArray( array );
  15638. }
  15639. update( frame ) {
  15640. const { light } = this;
  15641. super.update( frame );
  15642. //
  15643. for ( let i = 0; i < 9; i ++ ) {
  15644. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  15645. }
  15646. }
  15647. setup( builder ) {
  15648. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  15649. builder.context.irradiance.addAssign( irradiance );
  15650. }
  15651. }
  15652. class NodeParser {
  15653. parseFunction( /*source*/ ) {
  15654. console.warn( 'Abstract function.' );
  15655. }
  15656. }
  15657. class NodeFunction {
  15658. constructor( type, inputs, name = '', precision = '' ) {
  15659. this.type = type;
  15660. this.inputs = inputs;
  15661. this.name = name;
  15662. this.precision = precision;
  15663. }
  15664. getCode( /*name = this.name*/ ) {
  15665. console.warn( 'Abstract function.' );
  15666. }
  15667. }
  15668. NodeFunction.isNodeFunction = true;
  15669. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  15670. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  15671. const pragmaMain = '#pragma main';
  15672. const parse$1 = ( source ) => {
  15673. source = source.trim();
  15674. const pragmaMainIndex = source.indexOf( pragmaMain );
  15675. const mainCode = pragmaMainIndex !== - 1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  15676. const declaration = mainCode.match( declarationRegexp$1 );
  15677. if ( declaration !== null && declaration.length === 5 ) {
  15678. // tokenizer
  15679. const inputsCode = declaration[ 4 ];
  15680. const propsMatches = [];
  15681. let nameMatch = null;
  15682. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  15683. propsMatches.push( nameMatch );
  15684. }
  15685. // parser
  15686. const inputs = [];
  15687. let i = 0;
  15688. while ( i < propsMatches.length ) {
  15689. const isConst = propsMatches[ i ][ 0 ] === 'const';
  15690. if ( isConst === true ) {
  15691. i ++;
  15692. }
  15693. let qualifier = propsMatches[ i ][ 0 ];
  15694. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  15695. i ++;
  15696. } else {
  15697. qualifier = '';
  15698. }
  15699. const type = propsMatches[ i ++ ][ 0 ];
  15700. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  15701. if ( Number.isNaN( count ) === false ) i ++;
  15702. else count = null;
  15703. const name = propsMatches[ i ++ ][ 0 ];
  15704. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  15705. }
  15706. //
  15707. const blockCode = mainCode.substring( declaration[ 0 ].length );
  15708. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  15709. const type = declaration[ 2 ];
  15710. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  15711. const headerCode = pragmaMainIndex !== - 1 ? source.slice( 0, pragmaMainIndex ) : '';
  15712. return {
  15713. type,
  15714. inputs,
  15715. name,
  15716. precision,
  15717. inputsCode,
  15718. blockCode,
  15719. headerCode
  15720. };
  15721. } else {
  15722. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  15723. }
  15724. };
  15725. class GLSLNodeFunction extends NodeFunction {
  15726. constructor( source ) {
  15727. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  15728. super( type, inputs, name, precision );
  15729. this.inputsCode = inputsCode;
  15730. this.blockCode = blockCode;
  15731. this.headerCode = headerCode;
  15732. }
  15733. getCode( name = this.name ) {
  15734. let code;
  15735. const blockCode = this.blockCode;
  15736. if ( blockCode !== '' ) {
  15737. const { type, inputsCode, headerCode, precision } = this;
  15738. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  15739. if ( precision !== '' ) {
  15740. declarationCode = `${ precision } ${ declarationCode }`;
  15741. }
  15742. code = headerCode + declarationCode + blockCode;
  15743. } else {
  15744. // interface function
  15745. code = '';
  15746. }
  15747. return code;
  15748. }
  15749. }
  15750. class GLSLNodeParser extends NodeParser {
  15751. parseFunction( source ) {
  15752. return new GLSLNodeFunction( source );
  15753. }
  15754. }
  15755. const outputNodeMap = new WeakMap();
  15756. class Nodes extends DataMap {
  15757. constructor( renderer, backend ) {
  15758. super();
  15759. this.renderer = renderer;
  15760. this.backend = backend;
  15761. this.nodeFrame = new NodeFrame();
  15762. this.nodeBuilderCache = new Map();
  15763. this.callHashCache = new ChainMap();
  15764. this.groupsData = new ChainMap();
  15765. }
  15766. updateGroup( nodeUniformsGroup ) {
  15767. const groupNode = nodeUniformsGroup.groupNode;
  15768. const name = groupNode.name;
  15769. // objectGroup is every updated
  15770. if ( name === objectGroup.name ) return true;
  15771. // renderGroup is updated once per render/compute call
  15772. if ( name === renderGroup.name ) {
  15773. const uniformsGroupData = this.get( nodeUniformsGroup );
  15774. const renderId = this.nodeFrame.renderId;
  15775. if ( uniformsGroupData.renderId !== renderId ) {
  15776. uniformsGroupData.renderId = renderId;
  15777. return true;
  15778. }
  15779. return false;
  15780. }
  15781. // frameGroup is updated once per frame
  15782. if ( name === frameGroup.name ) {
  15783. const uniformsGroupData = this.get( nodeUniformsGroup );
  15784. const frameId = this.nodeFrame.frameId;
  15785. if ( uniformsGroupData.frameId !== frameId ) {
  15786. uniformsGroupData.frameId = frameId;
  15787. return true;
  15788. }
  15789. return false;
  15790. }
  15791. // other groups are updated just when groupNode.needsUpdate is true
  15792. const groupChain = [ groupNode, nodeUniformsGroup ];
  15793. let groupData = this.groupsData.get( groupChain );
  15794. if ( groupData === undefined ) this.groupsData.set( groupChain, groupData = {} );
  15795. if ( groupData.version !== groupNode.version ) {
  15796. groupData.version = groupNode.version;
  15797. return true;
  15798. }
  15799. return false;
  15800. }
  15801. getForRenderCacheKey( renderObject ) {
  15802. return renderObject.initialCacheKey;
  15803. }
  15804. getForRender( renderObject ) {
  15805. const renderObjectData = this.get( renderObject );
  15806. let nodeBuilderState = renderObjectData.nodeBuilderState;
  15807. if ( nodeBuilderState === undefined ) {
  15808. const { nodeBuilderCache } = this;
  15809. const cacheKey = this.getForRenderCacheKey( renderObject );
  15810. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  15811. if ( nodeBuilderState === undefined ) {
  15812. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  15813. nodeBuilder.scene = renderObject.scene;
  15814. nodeBuilder.material = renderObject.material;
  15815. nodeBuilder.camera = renderObject.camera;
  15816. nodeBuilder.context.material = renderObject.material;
  15817. nodeBuilder.lightsNode = renderObject.lightsNode;
  15818. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  15819. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  15820. nodeBuilder.clippingContext = renderObject.clippingContext;
  15821. nodeBuilder.build();
  15822. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  15823. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  15824. }
  15825. nodeBuilderState.usedTimes ++;
  15826. renderObjectData.nodeBuilderState = nodeBuilderState;
  15827. }
  15828. return nodeBuilderState;
  15829. }
  15830. delete( object ) {
  15831. if ( object.isRenderObject ) {
  15832. const nodeBuilderState = this.get( object ).nodeBuilderState;
  15833. nodeBuilderState.usedTimes --;
  15834. if ( nodeBuilderState.usedTimes === 0 ) {
  15835. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  15836. }
  15837. }
  15838. return super.delete( object );
  15839. }
  15840. getForCompute( computeNode ) {
  15841. const computeData = this.get( computeNode );
  15842. let nodeBuilderState = computeData.nodeBuilderState;
  15843. if ( nodeBuilderState === undefined ) {
  15844. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  15845. nodeBuilder.build();
  15846. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  15847. computeData.nodeBuilderState = nodeBuilderState;
  15848. }
  15849. return nodeBuilderState;
  15850. }
  15851. _createNodeBuilderState( nodeBuilder ) {
  15852. return new NodeBuilderState(
  15853. nodeBuilder.vertexShader,
  15854. nodeBuilder.fragmentShader,
  15855. nodeBuilder.computeShader,
  15856. nodeBuilder.getAttributesArray(),
  15857. nodeBuilder.getBindings(),
  15858. nodeBuilder.updateNodes,
  15859. nodeBuilder.updateBeforeNodes,
  15860. nodeBuilder.updateAfterNodes,
  15861. nodeBuilder.monitor,
  15862. nodeBuilder.transforms
  15863. );
  15864. }
  15865. getEnvironmentNode( scene ) {
  15866. return scene.environmentNode || this.get( scene ).environmentNode || null;
  15867. }
  15868. getBackgroundNode( scene ) {
  15869. return scene.backgroundNode || this.get( scene ).backgroundNode || null;
  15870. }
  15871. getFogNode( scene ) {
  15872. return scene.fogNode || this.get( scene ).fogNode || null;
  15873. }
  15874. getCacheKey( scene, lightsNode ) {
  15875. const chain = [ scene, lightsNode ];
  15876. const callId = this.renderer.info.calls;
  15877. let cacheKeyData = this.callHashCache.get( chain );
  15878. if ( cacheKeyData === undefined || cacheKeyData.callId !== callId ) {
  15879. const environmentNode = this.getEnvironmentNode( scene );
  15880. const fogNode = this.getFogNode( scene );
  15881. const values = [];
  15882. if ( lightsNode ) values.push( lightsNode.getCacheKey( true ) );
  15883. if ( environmentNode ) values.push( environmentNode.getCacheKey() );
  15884. if ( fogNode ) values.push( fogNode.getCacheKey() );
  15885. values.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  15886. cacheKeyData = {
  15887. callId,
  15888. cacheKey: hashArray( values )
  15889. };
  15890. this.callHashCache.set( chain, cacheKeyData );
  15891. }
  15892. return cacheKeyData.cacheKey;
  15893. }
  15894. updateScene( scene ) {
  15895. this.updateEnvironment( scene );
  15896. this.updateFog( scene );
  15897. this.updateBackground( scene );
  15898. }
  15899. get isToneMappingState() {
  15900. return this.renderer.getRenderTarget() ? false : true;
  15901. }
  15902. updateBackground( scene ) {
  15903. const sceneData = this.get( scene );
  15904. const background = scene.background;
  15905. if ( background ) {
  15906. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  15907. if ( sceneData.background !== background || forceUpdate ) {
  15908. let backgroundNode = null;
  15909. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  15910. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  15911. backgroundNode = pmremTexture( background );
  15912. } else {
  15913. let envMap;
  15914. if ( background.isCubeTexture === true ) {
  15915. envMap = cubeTexture( background );
  15916. } else {
  15917. envMap = texture( background );
  15918. }
  15919. backgroundNode = cubeMapNode( envMap );
  15920. }
  15921. } else if ( background.isTexture === true ) {
  15922. backgroundNode = texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  15923. } else if ( background.isColor !== true ) {
  15924. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  15925. }
  15926. sceneData.backgroundNode = backgroundNode;
  15927. sceneData.background = background;
  15928. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  15929. }
  15930. } else if ( sceneData.backgroundNode ) {
  15931. delete sceneData.backgroundNode;
  15932. delete sceneData.background;
  15933. }
  15934. }
  15935. updateFog( scene ) {
  15936. const sceneData = this.get( scene );
  15937. const fog = scene.fog;
  15938. if ( fog ) {
  15939. if ( sceneData.fog !== fog ) {
  15940. let fogNode = null;
  15941. if ( fog.isFogExp2 ) {
  15942. const color = reference( 'color', 'color', fog ).setGroup( renderGroup );
  15943. const density = reference( 'density', 'float', fog ).setGroup( renderGroup );
  15944. fogNode = densityFog( color, density );
  15945. } else if ( fog.isFog ) {
  15946. const color = reference( 'color', 'color', fog ).setGroup( renderGroup );
  15947. const near = reference( 'near', 'float', fog ).setGroup( renderGroup );
  15948. const far = reference( 'far', 'float', fog ).setGroup( renderGroup );
  15949. fogNode = rangeFog( color, near, far );
  15950. } else {
  15951. console.error( 'WebGPUNodes: Unsupported fog configuration.', fog );
  15952. }
  15953. sceneData.fogNode = fogNode;
  15954. sceneData.fog = fog;
  15955. }
  15956. } else {
  15957. delete sceneData.fogNode;
  15958. delete sceneData.fog;
  15959. }
  15960. }
  15961. updateEnvironment( scene ) {
  15962. const sceneData = this.get( scene );
  15963. const environment = scene.environment;
  15964. if ( environment ) {
  15965. if ( sceneData.environment !== environment ) {
  15966. let environmentNode = null;
  15967. if ( environment.isCubeTexture === true ) {
  15968. environmentNode = cubeTexture( environment );
  15969. } else if ( environment.isTexture === true ) {
  15970. environmentNode = texture( environment );
  15971. } else {
  15972. console.error( 'Nodes: Unsupported environment configuration.', environment );
  15973. }
  15974. sceneData.environmentNode = environmentNode;
  15975. sceneData.environment = environment;
  15976. }
  15977. } else if ( sceneData.environmentNode ) {
  15978. delete sceneData.environmentNode;
  15979. delete sceneData.environment;
  15980. }
  15981. }
  15982. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  15983. const nodeFrame = this.nodeFrame;
  15984. nodeFrame.renderer = renderer;
  15985. nodeFrame.scene = scene;
  15986. nodeFrame.object = object;
  15987. nodeFrame.camera = camera;
  15988. nodeFrame.material = material;
  15989. return nodeFrame;
  15990. }
  15991. getNodeFrameForRender( renderObject ) {
  15992. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  15993. }
  15994. getOutputCacheKey() {
  15995. const renderer = this.renderer;
  15996. return renderer.toneMapping + ',' + renderer.currentColorSpace;
  15997. }
  15998. hasOutputChange( outputTarget ) {
  15999. const cacheKey = outputNodeMap.get( outputTarget );
  16000. return cacheKey !== this.getOutputCacheKey();
  16001. }
  16002. getOutputNode( outputTexture ) {
  16003. const renderer = this.renderer;
  16004. const cacheKey = this.getOutputCacheKey();
  16005. const output = texture( outputTexture, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  16006. outputNodeMap.set( outputTexture, cacheKey );
  16007. return output;
  16008. }
  16009. updateBefore( renderObject ) {
  16010. const nodeBuilder = renderObject.getNodeBuilderState();
  16011. for ( const node of nodeBuilder.updateBeforeNodes ) {
  16012. // update frame state for each node
  16013. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  16014. }
  16015. }
  16016. updateAfter( renderObject ) {
  16017. const nodeBuilder = renderObject.getNodeBuilderState();
  16018. for ( const node of nodeBuilder.updateAfterNodes ) {
  16019. // update frame state for each node
  16020. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  16021. }
  16022. }
  16023. updateForCompute( computeNode ) {
  16024. const nodeFrame = this.getNodeFrame();
  16025. const nodeBuilder = this.getForCompute( computeNode );
  16026. for ( const node of nodeBuilder.updateNodes ) {
  16027. nodeFrame.updateNode( node );
  16028. }
  16029. }
  16030. updateForRender( renderObject ) {
  16031. const nodeFrame = this.getNodeFrameForRender( renderObject );
  16032. const nodeBuilder = renderObject.getNodeBuilderState();
  16033. for ( const node of nodeBuilder.updateNodes ) {
  16034. nodeFrame.updateNode( node );
  16035. }
  16036. }
  16037. needsRefresh( renderObject ) {
  16038. const nodeFrame = this.getNodeFrameForRender( renderObject );
  16039. const monitor = renderObject.getMonitor();
  16040. return monitor.needsRefresh( renderObject, nodeFrame );
  16041. }
  16042. dispose() {
  16043. super.dispose();
  16044. this.nodeFrame = new NodeFrame();
  16045. this.nodeBuilderCache = new Map();
  16046. }
  16047. }
  16048. const _plane = /*@__PURE__*/ new Plane();
  16049. class ClippingContext {
  16050. constructor( parentContext = null ) {
  16051. this.version = 0;
  16052. this.clipIntersection = null;
  16053. this.cacheKey = '';
  16054. if ( parentContext === null ) {
  16055. this.intersectionPlanes = [];
  16056. this.unionPlanes = [];
  16057. this.viewNormalMatrix = new Matrix3();
  16058. this.clippingGroupContexts = new WeakMap();
  16059. this.shadowPass = false;
  16060. } else {
  16061. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  16062. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  16063. this.shadowPass = parentContext.shadowPass;
  16064. this.viewMatrix = parentContext.viewMatrix;
  16065. }
  16066. this.parentVersion = null;
  16067. }
  16068. projectPlanes( source, destination, offset ) {
  16069. const l = source.length;
  16070. for ( let i = 0; i < l; i ++ ) {
  16071. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  16072. const v = destination[ offset + i ];
  16073. const normal = _plane.normal;
  16074. v.x = - normal.x;
  16075. v.y = - normal.y;
  16076. v.z = - normal.z;
  16077. v.w = _plane.constant;
  16078. }
  16079. }
  16080. updateGlobal( scene, camera ) {
  16081. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowNodeMaterial );
  16082. this.viewMatrix = camera.matrixWorldInverse;
  16083. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  16084. }
  16085. update( parentContext, clippingGroup ) {
  16086. let update = false;
  16087. if ( parentContext.version !== this.parentVersion ) {
  16088. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  16089. this.unionPlanes = Array.from( parentContext.unionPlanes );
  16090. this.parentVersion = parentContext.version;
  16091. }
  16092. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  16093. this.clipIntersection = clippingGroup.clipIntersection;
  16094. if ( this.clipIntersection ) {
  16095. this.unionPlanes.length = parentContext.unionPlanes.length;
  16096. } else {
  16097. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  16098. }
  16099. }
  16100. const srcClippingPlanes = clippingGroup.clippingPlanes;
  16101. const l = srcClippingPlanes.length;
  16102. let dstClippingPlanes;
  16103. let offset;
  16104. if ( this.clipIntersection ) {
  16105. dstClippingPlanes = this.intersectionPlanes;
  16106. offset = parentContext.intersectionPlanes.length;
  16107. } else {
  16108. dstClippingPlanes = this.unionPlanes;
  16109. offset = parentContext.unionPlanes.length;
  16110. }
  16111. if ( dstClippingPlanes.length !== offset + l ) {
  16112. dstClippingPlanes.length = offset + l;
  16113. for ( let i = 0; i < l; i ++ ) {
  16114. dstClippingPlanes[ offset + i ] = new Vector4();
  16115. }
  16116. update = true;
  16117. }
  16118. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  16119. if ( update ) {
  16120. this.version ++;
  16121. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  16122. }
  16123. }
  16124. getGroupContext( clippingGroup ) {
  16125. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  16126. let context = this.clippingGroupContexts.get( clippingGroup );
  16127. if ( context === undefined ) {
  16128. context = new ClippingContext( this );
  16129. this.clippingGroupContexts.set( clippingGroup, context );
  16130. }
  16131. context.update( this, clippingGroup );
  16132. return context;
  16133. }
  16134. get unionClippingCount() {
  16135. return this.unionPlanes.length;
  16136. }
  16137. }
  16138. class RenderBundle {
  16139. constructor( scene, camera ) {
  16140. this.scene = scene;
  16141. this.camera = camera;
  16142. }
  16143. clone() {
  16144. return Object.assign( new this.constructor(), this );
  16145. }
  16146. }
  16147. class RenderBundles {
  16148. constructor() {
  16149. this.lists = new ChainMap();
  16150. }
  16151. get( scene, camera ) {
  16152. const lists = this.lists;
  16153. const keys = [ scene, camera ];
  16154. let list = lists.get( keys );
  16155. if ( list === undefined ) {
  16156. list = new RenderBundle( scene, camera );
  16157. lists.set( keys, list );
  16158. }
  16159. return list;
  16160. }
  16161. dispose() {
  16162. this.lists = new ChainMap();
  16163. }
  16164. }
  16165. class NodeLibrary {
  16166. constructor() {
  16167. this.lightNodes = new WeakMap();
  16168. this.materialNodes = new Map();
  16169. this.toneMappingNodes = new Map();
  16170. }
  16171. fromMaterial( material ) {
  16172. if ( material.isNodeMaterial ) return material;
  16173. let nodeMaterial = null;
  16174. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  16175. if ( nodeMaterialClass !== null ) {
  16176. nodeMaterial = new nodeMaterialClass();
  16177. for ( const key in material ) {
  16178. nodeMaterial[ key ] = material[ key ];
  16179. }
  16180. }
  16181. return nodeMaterial;
  16182. }
  16183. addToneMapping( toneMappingNode, toneMapping ) {
  16184. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  16185. }
  16186. getToneMappingFunction( toneMapping ) {
  16187. return this.toneMappingNodes.get( toneMapping ) || null;
  16188. }
  16189. getMaterialNodeClass( materialType ) {
  16190. return this.materialNodes.get( materialType ) || null;
  16191. }
  16192. addMaterial( materialNodeClass, materialClassType ) {
  16193. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  16194. }
  16195. getLightNodeClass( light ) {
  16196. return this.lightNodes.get( light ) || null;
  16197. }
  16198. addLight( lightNodeClass, lightClass ) {
  16199. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  16200. }
  16201. addType( nodeClass, type, library ) {
  16202. if ( library.has( type ) ) {
  16203. console.warn( `Redefinition of node ${ type }` );
  16204. return;
  16205. }
  16206. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  16207. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  16208. library.set( type, nodeClass );
  16209. }
  16210. addClass( nodeClass, baseClass, library ) {
  16211. if ( library.has( baseClass ) ) {
  16212. console.warn( `Redefinition of node ${ baseClass.name }` );
  16213. return;
  16214. }
  16215. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  16216. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  16217. library.set( baseClass, nodeClass );
  16218. }
  16219. }
  16220. const _defaultLights = /*@__PURE__*/ new LightsNode();
  16221. class Lighting extends ChainMap {
  16222. constructor() {
  16223. super();
  16224. }
  16225. createNode( lights = [] ) {
  16226. return new LightsNode().setLights( lights );
  16227. }
  16228. getNode( scene, camera ) {
  16229. // ignore post-processing
  16230. if ( scene.isQuadMesh ) return _defaultLights;
  16231. // tiled lighting
  16232. const keys = [ scene, camera ];
  16233. let node = this.get( keys );
  16234. if ( node === undefined ) {
  16235. node = this.createNode();
  16236. this.set( keys, node );
  16237. }
  16238. return node;
  16239. }
  16240. }
  16241. const _scene = /*@__PURE__*/ new Scene();
  16242. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  16243. const _screen = /*@__PURE__*/ new Vector4();
  16244. const _frustum = /*@__PURE__*/ new Frustum();
  16245. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  16246. const _vector4 = /*@__PURE__*/ new Vector4();
  16247. class Renderer {
  16248. constructor( backend, parameters = {} ) {
  16249. this.isRenderer = true;
  16250. //
  16251. const {
  16252. logarithmicDepthBuffer = false,
  16253. alpha = true,
  16254. depth = true,
  16255. stencil = false,
  16256. antialias = false,
  16257. samples = 0,
  16258. getFallback = null
  16259. } = parameters;
  16260. // public
  16261. this.domElement = backend.getDomElement();
  16262. this.backend = backend;
  16263. this.samples = samples || ( antialias === true ) ? 4 : 0;
  16264. this.autoClear = true;
  16265. this.autoClearColor = true;
  16266. this.autoClearDepth = true;
  16267. this.autoClearStencil = true;
  16268. this.alpha = alpha;
  16269. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  16270. this.outputColorSpace = SRGBColorSpace;
  16271. this.toneMapping = NoToneMapping;
  16272. this.toneMappingExposure = 1.0;
  16273. this.sortObjects = true;
  16274. this.depth = depth;
  16275. this.stencil = stencil;
  16276. this.info = new Info();
  16277. this.nodes = {
  16278. modelViewMatrix: null,
  16279. modelNormalViewMatrix: null
  16280. };
  16281. this.library = new NodeLibrary();
  16282. this.lighting = new Lighting();
  16283. // internals
  16284. this._getFallback = getFallback;
  16285. this._pixelRatio = 1;
  16286. this._width = this.domElement.width;
  16287. this._height = this.domElement.height;
  16288. this._viewport = new Vector4( 0, 0, this._width, this._height );
  16289. this._scissor = new Vector4( 0, 0, this._width, this._height );
  16290. this._scissorTest = false;
  16291. this._attributes = null;
  16292. this._geometries = null;
  16293. this._nodes = null;
  16294. this._animation = null;
  16295. this._bindings = null;
  16296. this._objects = null;
  16297. this._pipelines = null;
  16298. this._bundles = null;
  16299. this._renderLists = null;
  16300. this._renderContexts = null;
  16301. this._textures = null;
  16302. this._background = null;
  16303. this._quad = new QuadMesh( new NodeMaterial() );
  16304. this._quad.material.type = 'Renderer_output';
  16305. this._currentRenderContext = null;
  16306. this._opaqueSort = null;
  16307. this._transparentSort = null;
  16308. this._frameBufferTarget = null;
  16309. const alphaClear = this.alpha === true ? 0 : 1;
  16310. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  16311. this._clearDepth = 1;
  16312. this._clearStencil = 0;
  16313. this._renderTarget = null;
  16314. this._activeCubeFace = 0;
  16315. this._activeMipmapLevel = 0;
  16316. this._mrt = null;
  16317. this._renderObjectFunction = null;
  16318. this._currentRenderObjectFunction = null;
  16319. this._currentRenderBundle = null;
  16320. this._handleObjectFunction = this._renderObjectDirect;
  16321. this._isDeviceLost = false;
  16322. this.onDeviceLost = this._onDeviceLost;
  16323. this._initialized = false;
  16324. this._initPromise = null;
  16325. this._compilationPromises = null;
  16326. this.transparent = true;
  16327. this.opaque = true;
  16328. this.shadowMap = {
  16329. enabled: false,
  16330. type: PCFShadowMap
  16331. };
  16332. this.xr = {
  16333. enabled: false
  16334. };
  16335. this.debug = {
  16336. checkShaderErrors: true,
  16337. onShaderError: null,
  16338. getShaderAsync: async ( scene, camera, object ) => {
  16339. await this.compileAsync( scene, camera );
  16340. const renderList = this._renderLists.get( scene, camera );
  16341. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  16342. const material = scene.overrideMaterial || object.material;
  16343. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  16344. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  16345. return { fragmentShader, vertexShader };
  16346. }
  16347. };
  16348. }
  16349. async init() {
  16350. if ( this._initialized ) {
  16351. throw new Error( 'Renderer: Backend has already been initialized.' );
  16352. }
  16353. if ( this._initPromise !== null ) {
  16354. return this._initPromise;
  16355. }
  16356. this._initPromise = new Promise( async ( resolve, reject ) => {
  16357. let backend = this.backend;
  16358. try {
  16359. await backend.init( this );
  16360. } catch ( error ) {
  16361. if ( this._getFallback !== null ) {
  16362. // try the fallback
  16363. try {
  16364. this.backend = backend = this._getFallback( error );
  16365. await backend.init( this );
  16366. } catch ( error ) {
  16367. reject( error );
  16368. return;
  16369. }
  16370. } else {
  16371. reject( error );
  16372. return;
  16373. }
  16374. }
  16375. this._nodes = new Nodes( this, backend );
  16376. this._animation = new Animation( this._nodes, this.info );
  16377. this._attributes = new Attributes( backend );
  16378. this._background = new Background( this, this._nodes );
  16379. this._geometries = new Geometries( this._attributes, this.info );
  16380. this._textures = new Textures( this, backend, this.info );
  16381. this._pipelines = new Pipelines( backend, this._nodes );
  16382. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  16383. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  16384. this._renderLists = new RenderLists( this.lighting );
  16385. this._bundles = new RenderBundles();
  16386. this._renderContexts = new RenderContexts();
  16387. //
  16388. this._animation.start();
  16389. this._initialized = true;
  16390. resolve();
  16391. } );
  16392. return this._initPromise;
  16393. }
  16394. get coordinateSystem() {
  16395. return this.backend.coordinateSystem;
  16396. }
  16397. async compileAsync( scene, camera, targetScene = null ) {
  16398. if ( this._isDeviceLost === true ) return;
  16399. if ( this._initialized === false ) await this.init();
  16400. // preserve render tree
  16401. const nodeFrame = this._nodes.nodeFrame;
  16402. const previousRenderId = nodeFrame.renderId;
  16403. const previousRenderContext = this._currentRenderContext;
  16404. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  16405. const previousCompilationPromises = this._compilationPromises;
  16406. //
  16407. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  16408. if ( targetScene === null ) targetScene = scene;
  16409. const renderTarget = this._renderTarget;
  16410. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  16411. const activeMipmapLevel = this._activeMipmapLevel;
  16412. const compilationPromises = [];
  16413. this._currentRenderContext = renderContext;
  16414. this._currentRenderObjectFunction = this.renderObject;
  16415. this._handleObjectFunction = this._createObjectPipeline;
  16416. this._compilationPromises = compilationPromises;
  16417. nodeFrame.renderId ++;
  16418. //
  16419. nodeFrame.update();
  16420. //
  16421. renderContext.depth = this.depth;
  16422. renderContext.stencil = this.stencil;
  16423. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  16424. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  16425. //
  16426. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  16427. //
  16428. const renderList = this._renderLists.get( scene, camera );
  16429. renderList.begin();
  16430. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  16431. // include lights from target scene
  16432. if ( targetScene !== scene ) {
  16433. targetScene.traverseVisible( function ( object ) {
  16434. if ( object.isLight && object.layers.test( camera.layers ) ) {
  16435. renderList.pushLight( object );
  16436. }
  16437. } );
  16438. }
  16439. renderList.finish();
  16440. //
  16441. if ( renderTarget !== null ) {
  16442. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  16443. const renderTargetData = this._textures.get( renderTarget );
  16444. renderContext.textures = renderTargetData.textures;
  16445. renderContext.depthTexture = renderTargetData.depthTexture;
  16446. } else {
  16447. renderContext.textures = null;
  16448. renderContext.depthTexture = null;
  16449. }
  16450. //
  16451. this._nodes.updateScene( sceneRef );
  16452. //
  16453. this._background.update( sceneRef, renderList, renderContext );
  16454. // process render lists
  16455. const opaqueObjects = renderList.opaque;
  16456. const transparentObjects = renderList.transparent;
  16457. const transparentDoublePassObjects = renderList.transparentDoublePass;
  16458. const lightsNode = renderList.lightsNode;
  16459. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  16460. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  16461. // restore render tree
  16462. nodeFrame.renderId = previousRenderId;
  16463. this._currentRenderContext = previousRenderContext;
  16464. this._currentRenderObjectFunction = previousRenderObjectFunction;
  16465. this._compilationPromises = previousCompilationPromises;
  16466. this._handleObjectFunction = this._renderObjectDirect;
  16467. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  16468. await Promise.all( compilationPromises );
  16469. }
  16470. async renderAsync( scene, camera ) {
  16471. if ( this._initialized === false ) await this.init();
  16472. const renderContext = this._renderScene( scene, camera );
  16473. await this.backend.resolveTimestampAsync( renderContext, 'render' );
  16474. }
  16475. async waitForGPU() {
  16476. await this.backend.waitForGPU();
  16477. }
  16478. setMRT( mrt ) {
  16479. this._mrt = mrt;
  16480. return this;
  16481. }
  16482. getMRT() {
  16483. return this._mrt;
  16484. }
  16485. _onDeviceLost( info ) {
  16486. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  16487. if ( info.reason ) {
  16488. errorMessage += `\nReason: ${info.reason}`;
  16489. }
  16490. console.error( errorMessage );
  16491. this._isDeviceLost = true;
  16492. }
  16493. _renderBundle( bundle, sceneRef, lightsNode ) {
  16494. const { bundleGroup, camera, renderList } = bundle;
  16495. const renderContext = this._currentRenderContext;
  16496. //
  16497. const renderBundle = this._bundles.get( bundleGroup, camera );
  16498. const renderBundleData = this.backend.get( renderBundle );
  16499. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  16500. //
  16501. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  16502. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  16503. renderBundleData.renderContexts.add( renderContext );
  16504. if ( renderBundleNeedsUpdate ) {
  16505. this.backend.beginBundle( renderContext );
  16506. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  16507. renderBundleData.renderObjects = [];
  16508. }
  16509. this._currentRenderBundle = renderBundle;
  16510. const opaqueObjects = renderList.opaque;
  16511. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  16512. this._currentRenderBundle = null;
  16513. //
  16514. this.backend.finishBundle( renderContext, renderBundle );
  16515. renderBundleData.version = bundleGroup.version;
  16516. } else {
  16517. const { renderObjects } = renderBundleData;
  16518. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  16519. const renderObject = renderObjects[ i ];
  16520. if ( this._nodes.needsRefresh( renderObject ) ) {
  16521. this._nodes.updateBefore( renderObject );
  16522. this._nodes.updateForRender( renderObject );
  16523. this._bindings.updateForRender( renderObject );
  16524. this._nodes.updateAfter( renderObject );
  16525. }
  16526. }
  16527. }
  16528. this.backend.addBundle( renderContext, renderBundle );
  16529. }
  16530. render( scene, camera ) {
  16531. if ( this._initialized === false ) {
  16532. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  16533. return this.renderAsync( scene, camera );
  16534. }
  16535. this._renderScene( scene, camera );
  16536. }
  16537. _getFrameBufferTarget() {
  16538. const { currentToneMapping, currentColorSpace } = this;
  16539. const useToneMapping = currentToneMapping !== NoToneMapping;
  16540. const useColorSpace = currentColorSpace !== LinearSRGBColorSpace;
  16541. if ( useToneMapping === false && useColorSpace === false ) return null;
  16542. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  16543. const { depth, stencil } = this;
  16544. let frameBufferTarget = this._frameBufferTarget;
  16545. if ( frameBufferTarget === null ) {
  16546. frameBufferTarget = new RenderTarget( width, height, {
  16547. depthBuffer: depth,
  16548. stencilBuffer: stencil,
  16549. type: HalfFloatType, // FloatType
  16550. format: RGBAFormat,
  16551. colorSpace: LinearSRGBColorSpace,
  16552. generateMipmaps: false,
  16553. minFilter: LinearFilter,
  16554. magFilter: LinearFilter,
  16555. samples: this.samples
  16556. } );
  16557. frameBufferTarget.isPostProcessingRenderTarget = true;
  16558. this._frameBufferTarget = frameBufferTarget;
  16559. }
  16560. frameBufferTarget.depthBuffer = depth;
  16561. frameBufferTarget.stencilBuffer = stencil;
  16562. frameBufferTarget.setSize( width, height );
  16563. frameBufferTarget.viewport.copy( this._viewport );
  16564. frameBufferTarget.scissor.copy( this._scissor );
  16565. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  16566. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  16567. frameBufferTarget.scissorTest = this._scissorTest;
  16568. return frameBufferTarget;
  16569. }
  16570. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  16571. if ( this._isDeviceLost === true ) return;
  16572. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  16573. // preserve render tree
  16574. const nodeFrame = this._nodes.nodeFrame;
  16575. const previousRenderId = nodeFrame.renderId;
  16576. const previousRenderContext = this._currentRenderContext;
  16577. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  16578. //
  16579. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  16580. const outputRenderTarget = this._renderTarget;
  16581. const activeCubeFace = this._activeCubeFace;
  16582. const activeMipmapLevel = this._activeMipmapLevel;
  16583. //
  16584. let renderTarget;
  16585. if ( frameBufferTarget !== null ) {
  16586. renderTarget = frameBufferTarget;
  16587. this.setRenderTarget( renderTarget );
  16588. } else {
  16589. renderTarget = outputRenderTarget;
  16590. }
  16591. //
  16592. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  16593. this._currentRenderContext = renderContext;
  16594. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  16595. //
  16596. this.info.calls ++;
  16597. this.info.render.calls ++;
  16598. this.info.render.frameCalls ++;
  16599. nodeFrame.renderId = this.info.calls;
  16600. //
  16601. const coordinateSystem = this.coordinateSystem;
  16602. if ( camera.coordinateSystem !== coordinateSystem ) {
  16603. camera.coordinateSystem = coordinateSystem;
  16604. camera.updateProjectionMatrix();
  16605. }
  16606. //
  16607. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  16608. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  16609. //
  16610. let viewport = this._viewport;
  16611. let scissor = this._scissor;
  16612. let pixelRatio = this._pixelRatio;
  16613. if ( renderTarget !== null ) {
  16614. viewport = renderTarget.viewport;
  16615. scissor = renderTarget.scissor;
  16616. pixelRatio = 1;
  16617. }
  16618. this.getDrawingBufferSize( _drawingBufferSize );
  16619. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  16620. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  16621. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  16622. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  16623. renderContext.viewportValue.width >>= activeMipmapLevel;
  16624. renderContext.viewportValue.height >>= activeMipmapLevel;
  16625. renderContext.viewportValue.minDepth = minDepth;
  16626. renderContext.viewportValue.maxDepth = maxDepth;
  16627. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  16628. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  16629. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  16630. renderContext.scissorValue.width >>= activeMipmapLevel;
  16631. renderContext.scissorValue.height >>= activeMipmapLevel;
  16632. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  16633. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  16634. //
  16635. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  16636. //
  16637. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  16638. _frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  16639. const renderList = this._renderLists.get( scene, camera );
  16640. renderList.begin();
  16641. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  16642. renderList.finish();
  16643. if ( this.sortObjects === true ) {
  16644. renderList.sort( this._opaqueSort, this._transparentSort );
  16645. }
  16646. //
  16647. if ( renderTarget !== null ) {
  16648. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  16649. const renderTargetData = this._textures.get( renderTarget );
  16650. renderContext.textures = renderTargetData.textures;
  16651. renderContext.depthTexture = renderTargetData.depthTexture;
  16652. renderContext.width = renderTargetData.width;
  16653. renderContext.height = renderTargetData.height;
  16654. renderContext.renderTarget = renderTarget;
  16655. renderContext.depth = renderTarget.depthBuffer;
  16656. renderContext.stencil = renderTarget.stencilBuffer;
  16657. } else {
  16658. renderContext.textures = null;
  16659. renderContext.depthTexture = null;
  16660. renderContext.width = this.domElement.width;
  16661. renderContext.height = this.domElement.height;
  16662. renderContext.depth = this.depth;
  16663. renderContext.stencil = this.stencil;
  16664. }
  16665. renderContext.width >>= activeMipmapLevel;
  16666. renderContext.height >>= activeMipmapLevel;
  16667. renderContext.activeCubeFace = activeCubeFace;
  16668. renderContext.activeMipmapLevel = activeMipmapLevel;
  16669. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  16670. //
  16671. this._nodes.updateScene( sceneRef );
  16672. //
  16673. this._background.update( sceneRef, renderList, renderContext );
  16674. //
  16675. this.backend.beginRender( renderContext );
  16676. // process render lists
  16677. const {
  16678. bundles,
  16679. lightsNode,
  16680. transparentDoublePass: transparentDoublePassObjects,
  16681. transparent: transparentObjects,
  16682. opaque: opaqueObjects
  16683. } = renderList;
  16684. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  16685. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  16686. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  16687. // finish render pass
  16688. this.backend.finishRender( renderContext );
  16689. // restore render tree
  16690. nodeFrame.renderId = previousRenderId;
  16691. this._currentRenderContext = previousRenderContext;
  16692. this._currentRenderObjectFunction = previousRenderObjectFunction;
  16693. //
  16694. if ( frameBufferTarget !== null ) {
  16695. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  16696. const quad = this._quad;
  16697. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  16698. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  16699. quad.material.needsUpdate = true;
  16700. }
  16701. this._renderScene( quad, quad.camera, false );
  16702. }
  16703. //
  16704. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  16705. //
  16706. return renderContext;
  16707. }
  16708. getMaxAnisotropy() {
  16709. return this.backend.getMaxAnisotropy();
  16710. }
  16711. getActiveCubeFace() {
  16712. return this._activeCubeFace;
  16713. }
  16714. getActiveMipmapLevel() {
  16715. return this._activeMipmapLevel;
  16716. }
  16717. async setAnimationLoop( callback ) {
  16718. if ( this._initialized === false ) await this.init();
  16719. this._animation.setAnimationLoop( callback );
  16720. }
  16721. async getArrayBufferAsync( attribute ) {
  16722. return await this.backend.getArrayBufferAsync( attribute );
  16723. }
  16724. getContext() {
  16725. return this.backend.getContext();
  16726. }
  16727. getPixelRatio() {
  16728. return this._pixelRatio;
  16729. }
  16730. getDrawingBufferSize( target ) {
  16731. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  16732. }
  16733. getSize( target ) {
  16734. return target.set( this._width, this._height );
  16735. }
  16736. setPixelRatio( value = 1 ) {
  16737. if ( this._pixelRatio === value ) return;
  16738. this._pixelRatio = value;
  16739. this.setSize( this._width, this._height, false );
  16740. }
  16741. setDrawingBufferSize( width, height, pixelRatio ) {
  16742. this._width = width;
  16743. this._height = height;
  16744. this._pixelRatio = pixelRatio;
  16745. this.domElement.width = Math.floor( width * pixelRatio );
  16746. this.domElement.height = Math.floor( height * pixelRatio );
  16747. this.setViewport( 0, 0, width, height );
  16748. if ( this._initialized ) this.backend.updateSize();
  16749. }
  16750. setSize( width, height, updateStyle = true ) {
  16751. this._width = width;
  16752. this._height = height;
  16753. this.domElement.width = Math.floor( width * this._pixelRatio );
  16754. this.domElement.height = Math.floor( height * this._pixelRatio );
  16755. if ( updateStyle === true ) {
  16756. this.domElement.style.width = width + 'px';
  16757. this.domElement.style.height = height + 'px';
  16758. }
  16759. this.setViewport( 0, 0, width, height );
  16760. if ( this._initialized ) this.backend.updateSize();
  16761. }
  16762. setOpaqueSort( method ) {
  16763. this._opaqueSort = method;
  16764. }
  16765. setTransparentSort( method ) {
  16766. this._transparentSort = method;
  16767. }
  16768. getScissor( target ) {
  16769. const scissor = this._scissor;
  16770. target.x = scissor.x;
  16771. target.y = scissor.y;
  16772. target.width = scissor.width;
  16773. target.height = scissor.height;
  16774. return target;
  16775. }
  16776. setScissor( x, y, width, height ) {
  16777. const scissor = this._scissor;
  16778. if ( x.isVector4 ) {
  16779. scissor.copy( x );
  16780. } else {
  16781. scissor.set( x, y, width, height );
  16782. }
  16783. }
  16784. getScissorTest() {
  16785. return this._scissorTest;
  16786. }
  16787. setScissorTest( boolean ) {
  16788. this._scissorTest = boolean;
  16789. this.backend.setScissorTest( boolean );
  16790. }
  16791. getViewport( target ) {
  16792. return target.copy( this._viewport );
  16793. }
  16794. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  16795. const viewport = this._viewport;
  16796. if ( x.isVector4 ) {
  16797. viewport.copy( x );
  16798. } else {
  16799. viewport.set( x, y, width, height );
  16800. }
  16801. viewport.minDepth = minDepth;
  16802. viewport.maxDepth = maxDepth;
  16803. }
  16804. getClearColor( target ) {
  16805. return target.copy( this._clearColor );
  16806. }
  16807. setClearColor( color, alpha = 1 ) {
  16808. this._clearColor.set( color );
  16809. this._clearColor.a = alpha;
  16810. }
  16811. getClearAlpha() {
  16812. return this._clearColor.a;
  16813. }
  16814. setClearAlpha( alpha ) {
  16815. this._clearColor.a = alpha;
  16816. }
  16817. getClearDepth() {
  16818. return this._clearDepth;
  16819. }
  16820. setClearDepth( depth ) {
  16821. this._clearDepth = depth;
  16822. }
  16823. getClearStencil() {
  16824. return this._clearStencil;
  16825. }
  16826. setClearStencil( stencil ) {
  16827. this._clearStencil = stencil;
  16828. }
  16829. isOccluded( object ) {
  16830. const renderContext = this._currentRenderContext;
  16831. return renderContext && this.backend.isOccluded( renderContext, object );
  16832. }
  16833. clear( color = true, depth = true, stencil = true ) {
  16834. if ( this._initialized === false ) {
  16835. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  16836. return this.clearAsync( color, depth, stencil );
  16837. }
  16838. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  16839. let renderTargetData = null;
  16840. if ( renderTarget !== null ) {
  16841. this._textures.updateRenderTarget( renderTarget );
  16842. renderTargetData = this._textures.get( renderTarget );
  16843. }
  16844. this.backend.clear( color, depth, stencil, renderTargetData );
  16845. if ( renderTarget !== null && this._renderTarget === null ) {
  16846. // If a color space transform or tone mapping is required,
  16847. // the clear operation clears the intermediate renderTarget texture, but does not update the screen canvas.
  16848. const quad = this._quad;
  16849. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  16850. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  16851. quad.material.needsUpdate = true;
  16852. }
  16853. this._renderScene( quad, quad.camera, false );
  16854. }
  16855. }
  16856. clearColor() {
  16857. return this.clear( true, false, false );
  16858. }
  16859. clearDepth() {
  16860. return this.clear( false, true, false );
  16861. }
  16862. clearStencil() {
  16863. return this.clear( false, false, true );
  16864. }
  16865. async clearAsync( color = true, depth = true, stencil = true ) {
  16866. if ( this._initialized === false ) await this.init();
  16867. this.clear( color, depth, stencil );
  16868. }
  16869. clearColorAsync() {
  16870. return this.clearAsync( true, false, false );
  16871. }
  16872. clearDepthAsync() {
  16873. return this.clearAsync( false, true, false );
  16874. }
  16875. clearStencilAsync() {
  16876. return this.clearAsync( false, false, true );
  16877. }
  16878. get currentToneMapping() {
  16879. return this._renderTarget !== null ? NoToneMapping : this.toneMapping;
  16880. }
  16881. get currentColorSpace() {
  16882. return this._renderTarget !== null ? LinearSRGBColorSpace : this.outputColorSpace;
  16883. }
  16884. dispose() {
  16885. this.info.dispose();
  16886. this.backend.dispose();
  16887. this._animation.dispose();
  16888. this._objects.dispose();
  16889. this._pipelines.dispose();
  16890. this._nodes.dispose();
  16891. this._bindings.dispose();
  16892. this._renderLists.dispose();
  16893. this._renderContexts.dispose();
  16894. this._textures.dispose();
  16895. this.setRenderTarget( null );
  16896. this.setAnimationLoop( null );
  16897. }
  16898. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  16899. this._renderTarget = renderTarget;
  16900. this._activeCubeFace = activeCubeFace;
  16901. this._activeMipmapLevel = activeMipmapLevel;
  16902. }
  16903. getRenderTarget() {
  16904. return this._renderTarget;
  16905. }
  16906. setRenderObjectFunction( renderObjectFunction ) {
  16907. this._renderObjectFunction = renderObjectFunction;
  16908. }
  16909. getRenderObjectFunction() {
  16910. return this._renderObjectFunction;
  16911. }
  16912. compute( computeNodes ) {
  16913. if ( this.isDeviceLost === true ) return;
  16914. if ( this._initialized === false ) {
  16915. console.warn( 'THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  16916. return this.computeAsync( computeNodes );
  16917. }
  16918. //
  16919. const nodeFrame = this._nodes.nodeFrame;
  16920. const previousRenderId = nodeFrame.renderId;
  16921. //
  16922. this.info.calls ++;
  16923. this.info.compute.calls ++;
  16924. this.info.compute.frameCalls ++;
  16925. nodeFrame.renderId = this.info.calls;
  16926. //
  16927. const backend = this.backend;
  16928. const pipelines = this._pipelines;
  16929. const bindings = this._bindings;
  16930. const nodes = this._nodes;
  16931. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  16932. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  16933. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  16934. }
  16935. backend.beginCompute( computeNodes );
  16936. for ( const computeNode of computeList ) {
  16937. // onInit
  16938. if ( pipelines.has( computeNode ) === false ) {
  16939. const dispose = () => {
  16940. computeNode.removeEventListener( 'dispose', dispose );
  16941. pipelines.delete( computeNode );
  16942. bindings.delete( computeNode );
  16943. nodes.delete( computeNode );
  16944. };
  16945. computeNode.addEventListener( 'dispose', dispose );
  16946. //
  16947. const onInitFn = computeNode.onInitFunction;
  16948. if ( onInitFn !== null ) {
  16949. onInitFn.call( computeNode, { renderer: this } );
  16950. }
  16951. }
  16952. nodes.updateForCompute( computeNode );
  16953. bindings.updateForCompute( computeNode );
  16954. const computeBindings = bindings.getForCompute( computeNode );
  16955. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  16956. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  16957. }
  16958. backend.finishCompute( computeNodes );
  16959. //
  16960. nodeFrame.renderId = previousRenderId;
  16961. }
  16962. async computeAsync( computeNodes ) {
  16963. if ( this._initialized === false ) await this.init();
  16964. this.compute( computeNodes );
  16965. await this.backend.resolveTimestampAsync( computeNodes, 'compute' );
  16966. }
  16967. async hasFeatureAsync( name ) {
  16968. if ( this._initialized === false ) await this.init();
  16969. return this.backend.hasFeature( name );
  16970. }
  16971. hasFeature( name ) {
  16972. if ( this._initialized === false ) {
  16973. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  16974. return false;
  16975. }
  16976. return this.backend.hasFeature( name );
  16977. }
  16978. hasInitialized() {
  16979. return this._initialized;
  16980. }
  16981. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  16982. if ( rectangle !== null ) {
  16983. if ( rectangle.isVector2 ) {
  16984. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  16985. } else if ( rectangle.isVector4 ) {
  16986. rectangle = _vector4.copy( rectangle ).floor();
  16987. } else {
  16988. console.error( 'THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  16989. return;
  16990. }
  16991. } else {
  16992. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  16993. }
  16994. //
  16995. let renderContext = this._currentRenderContext;
  16996. let renderTarget;
  16997. if ( renderContext !== null ) {
  16998. renderTarget = renderContext.renderTarget;
  16999. } else {
  17000. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  17001. if ( renderTarget !== null ) {
  17002. this._textures.updateRenderTarget( renderTarget );
  17003. renderContext = this._textures.get( renderTarget );
  17004. }
  17005. }
  17006. //
  17007. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  17008. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  17009. }
  17010. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  17011. this._textures.updateTexture( srcTexture );
  17012. this._textures.updateTexture( dstTexture );
  17013. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  17014. }
  17015. readRenderTargetPixelsAsync( renderTarget, x, y, width, height, index = 0, faceIndex = 0 ) {
  17016. return this.backend.copyTextureToBuffer( renderTarget.textures[ index ], x, y, width, height, faceIndex );
  17017. }
  17018. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  17019. if ( object.visible === false ) return;
  17020. const visible = object.layers.test( camera.layers );
  17021. if ( visible ) {
  17022. if ( object.isGroup ) {
  17023. groupOrder = object.renderOrder;
  17024. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  17025. } else if ( object.isLOD ) {
  17026. if ( object.autoUpdate === true ) object.update( camera );
  17027. } else if ( object.isLight ) {
  17028. renderList.pushLight( object );
  17029. } else if ( object.isSprite ) {
  17030. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  17031. if ( this.sortObjects === true ) {
  17032. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  17033. }
  17034. const { geometry, material } = object;
  17035. if ( material.visible ) {
  17036. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  17037. }
  17038. }
  17039. } else if ( object.isLineLoop ) {
  17040. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  17041. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  17042. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  17043. const { geometry, material } = object;
  17044. if ( this.sortObjects === true ) {
  17045. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  17046. _vector4
  17047. .copy( geometry.boundingSphere.center )
  17048. .applyMatrix4( object.matrixWorld )
  17049. .applyMatrix4( _projScreenMatrix );
  17050. }
  17051. if ( Array.isArray( material ) ) {
  17052. const groups = geometry.groups;
  17053. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  17054. const group = groups[ i ];
  17055. const groupMaterial = material[ group.materialIndex ];
  17056. if ( groupMaterial && groupMaterial.visible ) {
  17057. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  17058. }
  17059. }
  17060. } else if ( material.visible ) {
  17061. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  17062. }
  17063. }
  17064. }
  17065. }
  17066. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  17067. const baseRenderList = renderList;
  17068. // replace render list
  17069. renderList = this._renderLists.get( object, camera );
  17070. renderList.begin();
  17071. baseRenderList.pushBundle( {
  17072. bundleGroup: object,
  17073. camera,
  17074. renderList,
  17075. } );
  17076. renderList.finish();
  17077. }
  17078. const children = object.children;
  17079. for ( let i = 0, l = children.length; i < l; i ++ ) {
  17080. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  17081. }
  17082. }
  17083. _renderBundles( bundles, sceneRef, lightsNode ) {
  17084. for ( const bundle of bundles ) {
  17085. this._renderBundle( bundle, sceneRef, lightsNode );
  17086. }
  17087. }
  17088. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  17089. if ( doublePassList.length > 0 ) {
  17090. // render back side
  17091. for ( const { material } of doublePassList ) {
  17092. material.side = BackSide;
  17093. }
  17094. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  17095. // render front side
  17096. for ( const { material } of doublePassList ) {
  17097. material.side = FrontSide;
  17098. }
  17099. this._renderObjects( renderList, camera, scene, lightsNode );
  17100. // restore
  17101. for ( const { material } of doublePassList ) {
  17102. material.side = DoubleSide;
  17103. }
  17104. } else {
  17105. this._renderObjects( renderList, camera, scene, lightsNode );
  17106. }
  17107. }
  17108. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  17109. // process renderable objects
  17110. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  17111. const renderItem = renderList[ i ];
  17112. // @TODO: Add support for multiple materials per object. This will require to extract
  17113. // the material from the renderItem object and pass it with its group data to renderObject().
  17114. const { object, geometry, material, group, clippingContext } = renderItem;
  17115. if ( camera.isArrayCamera ) {
  17116. const cameras = camera.cameras;
  17117. for ( let j = 0, jl = cameras.length; j < jl; j ++ ) {
  17118. const camera2 = cameras[ j ];
  17119. if ( object.layers.test( camera2.layers ) ) {
  17120. const vp = camera2.viewport;
  17121. const minDepth = ( vp.minDepth === undefined ) ? 0 : vp.minDepth;
  17122. const maxDepth = ( vp.maxDepth === undefined ) ? 1 : vp.maxDepth;
  17123. const viewportValue = this._currentRenderContext.viewportValue;
  17124. viewportValue.copy( vp ).multiplyScalar( this._pixelRatio ).floor();
  17125. viewportValue.minDepth = minDepth;
  17126. viewportValue.maxDepth = maxDepth;
  17127. this.backend.updateViewport( this._currentRenderContext );
  17128. this._currentRenderObjectFunction( object, scene, camera2, geometry, material, group, lightsNode, clippingContext, passId );
  17129. }
  17130. }
  17131. } else {
  17132. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  17133. }
  17134. }
  17135. }
  17136. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  17137. let overridePositionNode;
  17138. let overrideFragmentNode;
  17139. let overrideDepthNode;
  17140. //
  17141. object.onBeforeRender( this, scene, camera, geometry, material, group );
  17142. //
  17143. if ( scene.overrideMaterial !== null ) {
  17144. const overrideMaterial = scene.overrideMaterial;
  17145. if ( material.positionNode && material.positionNode.isNode ) {
  17146. overridePositionNode = overrideMaterial.positionNode;
  17147. overrideMaterial.positionNode = material.positionNode;
  17148. }
  17149. if ( overrideMaterial.isShadowNodeMaterial ) {
  17150. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  17151. if ( material.depthNode && material.depthNode.isNode ) {
  17152. overrideDepthNode = overrideMaterial.depthNode;
  17153. overrideMaterial.depthNode = material.depthNode;
  17154. }
  17155. if ( material.castShadowNode && material.castShadowNode.isNode ) {
  17156. overrideFragmentNode = overrideMaterial.fragmentNode;
  17157. overrideMaterial.fragmentNode = material.castShadowNode;
  17158. }
  17159. }
  17160. material = overrideMaterial;
  17161. }
  17162. //
  17163. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  17164. material.side = BackSide;
  17165. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  17166. material.side = FrontSide;
  17167. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  17168. material.side = DoubleSide;
  17169. } else {
  17170. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  17171. }
  17172. //
  17173. if ( overridePositionNode !== undefined ) {
  17174. scene.overrideMaterial.positionNode = overridePositionNode;
  17175. }
  17176. if ( overrideDepthNode !== undefined ) {
  17177. scene.overrideMaterial.depthNode = overrideDepthNode;
  17178. }
  17179. if ( overrideFragmentNode !== undefined ) {
  17180. scene.overrideMaterial.fragmentNode = overrideFragmentNode;
  17181. }
  17182. //
  17183. object.onAfterRender( this, scene, camera, geometry, material, group );
  17184. }
  17185. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  17186. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  17187. renderObject.drawRange = object.geometry.drawRange;
  17188. renderObject.group = group;
  17189. //
  17190. const needsRefresh = this._nodes.needsRefresh( renderObject );
  17191. if ( needsRefresh ) {
  17192. this._nodes.updateBefore( renderObject );
  17193. this._geometries.updateForRender( renderObject );
  17194. this._nodes.updateForRender( renderObject );
  17195. this._bindings.updateForRender( renderObject );
  17196. }
  17197. this._pipelines.updateForRender( renderObject );
  17198. //
  17199. if ( this._currentRenderBundle !== null ) {
  17200. const renderBundleData = this.backend.get( this._currentRenderBundle );
  17201. renderBundleData.renderObjects.push( renderObject );
  17202. renderObject.bundle = this._currentRenderBundle.scene;
  17203. }
  17204. this.backend.draw( renderObject, this.info );
  17205. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  17206. }
  17207. _createObjectPipeline( object, material, scene, camera, lightsNode, clippingContext, passId ) {
  17208. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  17209. //
  17210. this._nodes.updateBefore( renderObject );
  17211. this._geometries.updateForRender( renderObject );
  17212. this._nodes.updateForRender( renderObject );
  17213. this._bindings.updateForRender( renderObject );
  17214. this._pipelines.getForRender( renderObject, this._compilationPromises );
  17215. this._nodes.updateAfter( renderObject );
  17216. }
  17217. get compile() {
  17218. return this.compileAsync;
  17219. }
  17220. }
  17221. class Binding {
  17222. constructor( name = '' ) {
  17223. this.name = name;
  17224. this.visibility = 0;
  17225. }
  17226. setVisibility( visibility ) {
  17227. this.visibility |= visibility;
  17228. }
  17229. clone() {
  17230. return Object.assign( new this.constructor(), this );
  17231. }
  17232. }
  17233. function getFloatLength( floatLength ) {
  17234. // ensure chunk size alignment (STD140 layout)
  17235. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  17236. }
  17237. class Buffer extends Binding {
  17238. constructor( name, buffer = null ) {
  17239. super( name );
  17240. this.isBuffer = true;
  17241. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  17242. this._buffer = buffer;
  17243. }
  17244. get byteLength() {
  17245. return getFloatLength( this._buffer.byteLength );
  17246. }
  17247. get buffer() {
  17248. return this._buffer;
  17249. }
  17250. update() {
  17251. return true;
  17252. }
  17253. }
  17254. class UniformBuffer extends Buffer {
  17255. constructor( name, buffer = null ) {
  17256. super( name, buffer );
  17257. this.isUniformBuffer = true;
  17258. }
  17259. }
  17260. let _id$4 = 0;
  17261. class NodeUniformBuffer extends UniformBuffer {
  17262. constructor( nodeUniform, groupNode ) {
  17263. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  17264. this.nodeUniform = nodeUniform;
  17265. this.groupNode = groupNode;
  17266. }
  17267. get buffer() {
  17268. return this.nodeUniform.value;
  17269. }
  17270. }
  17271. class UniformsGroup extends UniformBuffer {
  17272. constructor( name ) {
  17273. super( name );
  17274. this.isUniformsGroup = true;
  17275. this._values = null;
  17276. // the order of uniforms in this array must match the order of uniforms in the shader
  17277. this.uniforms = [];
  17278. }
  17279. addUniform( uniform ) {
  17280. this.uniforms.push( uniform );
  17281. return this;
  17282. }
  17283. removeUniform( uniform ) {
  17284. const index = this.uniforms.indexOf( uniform );
  17285. if ( index !== - 1 ) {
  17286. this.uniforms.splice( index, 1 );
  17287. }
  17288. return this;
  17289. }
  17290. get values() {
  17291. if ( this._values === null ) {
  17292. this._values = Array.from( this.buffer );
  17293. }
  17294. return this._values;
  17295. }
  17296. get buffer() {
  17297. let buffer = this._buffer;
  17298. if ( buffer === null ) {
  17299. const byteLength = this.byteLength;
  17300. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  17301. this._buffer = buffer;
  17302. }
  17303. return buffer;
  17304. }
  17305. get byteLength() {
  17306. let offset = 0; // global buffer offset in bytes
  17307. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  17308. const uniform = this.uniforms[ i ];
  17309. const { boundary, itemSize } = uniform;
  17310. // offset within a single chunk in bytes
  17311. const chunkOffset = offset % GPU_CHUNK_BYTES;
  17312. const remainingSizeInChunk = GPU_CHUNK_BYTES - chunkOffset;
  17313. // conformance tests
  17314. if ( chunkOffset !== 0 && ( remainingSizeInChunk - boundary ) < 0 ) {
  17315. // check for chunk overflow
  17316. offset += ( GPU_CHUNK_BYTES - chunkOffset );
  17317. } else if ( chunkOffset % boundary !== 0 ) {
  17318. // check for correct alignment
  17319. offset += ( chunkOffset % boundary );
  17320. }
  17321. uniform.offset = ( offset / this.bytesPerElement );
  17322. offset += ( itemSize * this.bytesPerElement );
  17323. }
  17324. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  17325. }
  17326. update() {
  17327. let updated = false;
  17328. for ( const uniform of this.uniforms ) {
  17329. if ( this.updateByType( uniform ) === true ) {
  17330. updated = true;
  17331. }
  17332. }
  17333. return updated;
  17334. }
  17335. updateByType( uniform ) {
  17336. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  17337. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  17338. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  17339. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  17340. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  17341. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  17342. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  17343. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  17344. }
  17345. updateNumber( uniform ) {
  17346. let updated = false;
  17347. const a = this.values;
  17348. const v = uniform.getValue();
  17349. const offset = uniform.offset;
  17350. if ( a[ offset ] !== v ) {
  17351. const b = this.buffer;
  17352. b[ offset ] = a[ offset ] = v;
  17353. updated = true;
  17354. }
  17355. return updated;
  17356. }
  17357. updateVector2( uniform ) {
  17358. let updated = false;
  17359. const a = this.values;
  17360. const v = uniform.getValue();
  17361. const offset = uniform.offset;
  17362. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  17363. const b = this.buffer;
  17364. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  17365. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  17366. updated = true;
  17367. }
  17368. return updated;
  17369. }
  17370. updateVector3( uniform ) {
  17371. let updated = false;
  17372. const a = this.values;
  17373. const v = uniform.getValue();
  17374. const offset = uniform.offset;
  17375. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  17376. const b = this.buffer;
  17377. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  17378. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  17379. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  17380. updated = true;
  17381. }
  17382. return updated;
  17383. }
  17384. updateVector4( uniform ) {
  17385. let updated = false;
  17386. const a = this.values;
  17387. const v = uniform.getValue();
  17388. const offset = uniform.offset;
  17389. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  17390. const b = this.buffer;
  17391. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  17392. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  17393. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  17394. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  17395. updated = true;
  17396. }
  17397. return updated;
  17398. }
  17399. updateColor( uniform ) {
  17400. let updated = false;
  17401. const a = this.values;
  17402. const c = uniform.getValue();
  17403. const offset = uniform.offset;
  17404. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  17405. const b = this.buffer;
  17406. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  17407. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  17408. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  17409. updated = true;
  17410. }
  17411. return updated;
  17412. }
  17413. updateMatrix3( uniform ) {
  17414. let updated = false;
  17415. const a = this.values;
  17416. const e = uniform.getValue().elements;
  17417. const offset = uniform.offset;
  17418. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  17419. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  17420. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  17421. const b = this.buffer;
  17422. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  17423. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  17424. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  17425. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  17426. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  17427. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  17428. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  17429. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  17430. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  17431. updated = true;
  17432. }
  17433. return updated;
  17434. }
  17435. updateMatrix4( uniform ) {
  17436. let updated = false;
  17437. const a = this.values;
  17438. const e = uniform.getValue().elements;
  17439. const offset = uniform.offset;
  17440. if ( arraysEqual( a, e, offset ) === false ) {
  17441. const b = this.buffer;
  17442. b.set( e, offset );
  17443. setArray( a, e, offset );
  17444. updated = true;
  17445. }
  17446. return updated;
  17447. }
  17448. }
  17449. function setArray( a, b, offset ) {
  17450. for ( let i = 0, l = b.length; i < l; i ++ ) {
  17451. a[ offset + i ] = b[ i ];
  17452. }
  17453. }
  17454. function arraysEqual( a, b, offset ) {
  17455. for ( let i = 0, l = b.length; i < l; i ++ ) {
  17456. if ( a[ offset + i ] !== b[ i ] ) return false;
  17457. }
  17458. return true;
  17459. }
  17460. let _id$3 = 0;
  17461. class NodeUniformsGroup extends UniformsGroup {
  17462. constructor( name, groupNode ) {
  17463. super( name );
  17464. this.id = _id$3 ++;
  17465. this.groupNode = groupNode;
  17466. this.isNodeUniformsGroup = true;
  17467. }
  17468. getNodes() {
  17469. const nodes = [];
  17470. for ( const uniform of this.uniforms ) {
  17471. const node = uniform.nodeUniform.node;
  17472. if ( ! node ) throw new Error( 'NodeUniformsGroup: Uniform has no node.' );
  17473. nodes.push( node );
  17474. }
  17475. return nodes;
  17476. }
  17477. }
  17478. let _id$2 = 0;
  17479. class SampledTexture extends Binding {
  17480. constructor( name, texture ) {
  17481. super( name );
  17482. this.id = _id$2 ++;
  17483. this.texture = texture;
  17484. this.version = texture ? texture.version : 0;
  17485. this.store = false;
  17486. this.generation = null;
  17487. this.isSampledTexture = true;
  17488. }
  17489. needsBindingsUpdate( generation ) {
  17490. const { texture } = this;
  17491. if ( generation !== this.generation ) {
  17492. this.generation = generation;
  17493. return true;
  17494. }
  17495. return texture.isVideoTexture;
  17496. }
  17497. update() {
  17498. const { texture, version } = this;
  17499. if ( version !== texture.version ) {
  17500. this.version = texture.version;
  17501. return true;
  17502. }
  17503. return false;
  17504. }
  17505. }
  17506. class NodeSampledTexture extends SampledTexture {
  17507. constructor( name, textureNode, groupNode, access = null ) {
  17508. super( name, textureNode ? textureNode.value : null );
  17509. this.textureNode = textureNode;
  17510. this.groupNode = groupNode;
  17511. this.access = access;
  17512. }
  17513. needsBindingsUpdate( generation ) {
  17514. return this.textureNode.value !== this.texture || super.needsBindingsUpdate( generation );
  17515. }
  17516. update() {
  17517. const { textureNode } = this;
  17518. if ( this.texture !== textureNode.value ) {
  17519. this.texture = textureNode.value;
  17520. return true;
  17521. }
  17522. return super.update();
  17523. }
  17524. }
  17525. class NodeSampledCubeTexture extends NodeSampledTexture {
  17526. constructor( name, textureNode, groupNode, access ) {
  17527. super( name, textureNode, groupNode, access );
  17528. this.isSampledCubeTexture = true;
  17529. }
  17530. }
  17531. class NodeSampledTexture3D extends NodeSampledTexture {
  17532. constructor( name, textureNode, groupNode, access ) {
  17533. super( name, textureNode, groupNode, access );
  17534. this.isSampledTexture3D = true;
  17535. }
  17536. }
  17537. const glslMethods = {
  17538. atan2: 'atan',
  17539. textureDimensions: 'textureSize',
  17540. equals: 'equal'
  17541. };
  17542. const precisionLib = {
  17543. low: 'lowp',
  17544. medium: 'mediump',
  17545. high: 'highp'
  17546. };
  17547. const supports$1 = {
  17548. swizzleAssign: true,
  17549. storageBuffer: false
  17550. };
  17551. const defaultPrecisions = `
  17552. precision highp float;
  17553. precision highp int;
  17554. precision highp sampler2D;
  17555. precision highp sampler3D;
  17556. precision highp samplerCube;
  17557. precision highp sampler2DArray;
  17558. precision highp usampler2D;
  17559. precision highp usampler3D;
  17560. precision highp usamplerCube;
  17561. precision highp usampler2DArray;
  17562. precision highp isampler2D;
  17563. precision highp isampler3D;
  17564. precision highp isamplerCube;
  17565. precision highp isampler2DArray;
  17566. precision lowp sampler2DShadow;
  17567. `;
  17568. class GLSLNodeBuilder extends NodeBuilder {
  17569. constructor( object, renderer ) {
  17570. super( object, renderer, new GLSLNodeParser() );
  17571. this.uniformGroups = {};
  17572. this.transforms = [];
  17573. this.extensions = {};
  17574. this.builtins = { vertex: [], fragment: [], compute: [] };
  17575. this.useComparisonMethod = true;
  17576. }
  17577. needsColorSpaceToLinearSRGB( texture ) {
  17578. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  17579. }
  17580. getMethod( method ) {
  17581. return glslMethods[ method ] || method;
  17582. }
  17583. getOutputStructName() {
  17584. return '';
  17585. }
  17586. buildFunctionCode( shaderNode ) {
  17587. const layout = shaderNode.layout;
  17588. const flowData = this.flowShaderNode( shaderNode );
  17589. const parameters = [];
  17590. for ( const input of layout.inputs ) {
  17591. parameters.push( this.getType( input.type ) + ' ' + input.name );
  17592. }
  17593. //
  17594. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  17595. ${ flowData.vars }
  17596. ${ flowData.code }
  17597. return ${ flowData.result };
  17598. }`;
  17599. //
  17600. return code;
  17601. }
  17602. setupPBO( storageBufferNode ) {
  17603. const attribute = storageBufferNode.value;
  17604. if ( attribute.pbo === undefined ) {
  17605. const originalArray = attribute.array;
  17606. const numElements = attribute.count * attribute.itemSize;
  17607. const { itemSize } = attribute;
  17608. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  17609. let format = isInteger ? RedIntegerFormat : RedFormat;
  17610. if ( itemSize === 2 ) {
  17611. format = isInteger ? RGIntegerFormat : RGFormat;
  17612. } else if ( itemSize === 3 ) {
  17613. format = isInteger ? RGBIntegerFormat : RGBFormat;
  17614. } else if ( itemSize === 4 ) {
  17615. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  17616. }
  17617. const typeMap = {
  17618. Float32Array: FloatType,
  17619. Uint8Array: UnsignedByteType,
  17620. Uint16Array: UnsignedShortType,
  17621. Uint32Array: UnsignedIntType,
  17622. Int8Array: ByteType,
  17623. Int16Array: ShortType,
  17624. Int32Array: IntType,
  17625. Uint8ClampedArray: UnsignedByteType,
  17626. };
  17627. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  17628. let height = Math.ceil( ( numElements / itemSize ) / width );
  17629. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  17630. const newSize = width * height * itemSize;
  17631. const newArray = new originalArray.constructor( newSize );
  17632. newArray.set( originalArray, 0 );
  17633. attribute.array = newArray;
  17634. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  17635. pboTexture.needsUpdate = true;
  17636. pboTexture.isPBOTexture = true;
  17637. const pbo = new TextureNode( pboTexture, null, null );
  17638. pbo.setPrecision( 'high' );
  17639. attribute.pboNode = pbo;
  17640. attribute.pbo = pbo.value;
  17641. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  17642. }
  17643. }
  17644. getPropertyName( node, shaderStage = this.shaderStage ) {
  17645. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  17646. return shaderStage.charAt( 0 ) + '_' + node.name;
  17647. }
  17648. return super.getPropertyName( node, shaderStage );
  17649. }
  17650. generatePBO( storageArrayElementNode ) {
  17651. const { node, indexNode } = storageArrayElementNode;
  17652. const attribute = node.value;
  17653. if ( this.renderer.backend.has( attribute ) ) {
  17654. const attributeData = this.renderer.backend.get( attribute );
  17655. attributeData.pbo = attribute.pbo;
  17656. }
  17657. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  17658. const textureName = this.getPropertyName( nodeUniform );
  17659. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  17660. const indexSnippet = indexNode.build( this, 'uint' );
  17661. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  17662. let propertyName = elementNodeData.propertyName;
  17663. if ( propertyName === undefined ) {
  17664. // property element
  17665. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  17666. propertyName = this.getPropertyName( nodeVar );
  17667. // property size
  17668. const bufferNodeData = this.getDataFromNode( node );
  17669. let propertySizeName = bufferNodeData.propertySizeName;
  17670. if ( propertySizeName === undefined ) {
  17671. propertySizeName = propertyName + 'Size';
  17672. this.getVarFromNode( node, propertySizeName, 'uint' );
  17673. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  17674. bufferNodeData.propertySizeName = propertySizeName;
  17675. }
  17676. //
  17677. const { itemSize } = attribute;
  17678. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  17679. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  17680. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  17681. //
  17682. let prefix = 'vec4';
  17683. if ( attribute.pbo.type === UnsignedIntType ) {
  17684. prefix = 'uvec4';
  17685. } else if ( attribute.pbo.type === IntType ) {
  17686. prefix = 'ivec4';
  17687. }
  17688. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  17689. elementNodeData.propertyName = propertyName;
  17690. }
  17691. return propertyName;
  17692. }
  17693. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  17694. if ( depthSnippet ) {
  17695. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  17696. } else {
  17697. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  17698. }
  17699. }
  17700. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  17701. if ( texture.isDepthTexture ) {
  17702. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  17703. } else {
  17704. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  17705. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  17706. }
  17707. }
  17708. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  17709. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  17710. }
  17711. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
  17712. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  17713. }
  17714. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  17715. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  17716. }
  17717. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  17718. if ( shaderStage === 'fragment' ) {
  17719. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  17720. } else {
  17721. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  17722. }
  17723. }
  17724. getVars( shaderStage ) {
  17725. const snippets = [];
  17726. const vars = this.vars[ shaderStage ];
  17727. if ( vars !== undefined ) {
  17728. for ( const variable of vars ) {
  17729. snippets.push( `${ this.getVar( variable.type, variable.name ) };` );
  17730. }
  17731. }
  17732. return snippets.join( '\n\t' );
  17733. }
  17734. getUniforms( shaderStage ) {
  17735. const uniforms = this.uniforms[ shaderStage ];
  17736. const bindingSnippets = [];
  17737. const uniformGroups = {};
  17738. for ( const uniform of uniforms ) {
  17739. let snippet = null;
  17740. let group = false;
  17741. if ( uniform.type === 'texture' ) {
  17742. const texture = uniform.node.value;
  17743. let typePrefix = '';
  17744. if ( texture.isDataTexture === true ) {
  17745. if ( texture.type === UnsignedIntType ) {
  17746. typePrefix = 'u';
  17747. } else if ( texture.type === IntType ) {
  17748. typePrefix = 'i';
  17749. }
  17750. }
  17751. if ( texture.compareFunction ) {
  17752. snippet = `sampler2DShadow ${ uniform.name };`;
  17753. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  17754. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  17755. } else {
  17756. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  17757. }
  17758. } else if ( uniform.type === 'cubeTexture' ) {
  17759. snippet = `samplerCube ${ uniform.name };`;
  17760. } else if ( uniform.type === 'texture3D' ) {
  17761. snippet = `sampler3D ${ uniform.name };`;
  17762. } else if ( uniform.type === 'buffer' ) {
  17763. const bufferNode = uniform.node;
  17764. const bufferType = this.getType( bufferNode.bufferType );
  17765. const bufferCount = bufferNode.bufferCount;
  17766. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  17767. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  17768. } else {
  17769. const vectorType = this.getVectorType( uniform.type );
  17770. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  17771. group = true;
  17772. }
  17773. const precision = uniform.node.precision;
  17774. if ( precision !== null ) {
  17775. snippet = precisionLib[ precision ] + ' ' + snippet;
  17776. }
  17777. if ( group ) {
  17778. snippet = '\t' + snippet;
  17779. const groupName = uniform.groupNode.name;
  17780. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  17781. groupSnippets.push( snippet );
  17782. } else {
  17783. snippet = 'uniform ' + snippet;
  17784. bindingSnippets.push( snippet );
  17785. }
  17786. }
  17787. let output = '';
  17788. for ( const name in uniformGroups ) {
  17789. const groupSnippets = uniformGroups[ name ];
  17790. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  17791. }
  17792. output += bindingSnippets.join( '\n' );
  17793. return output;
  17794. }
  17795. getTypeFromAttribute( attribute ) {
  17796. let nodeType = super.getTypeFromAttribute( attribute );
  17797. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  17798. let dataAttribute = attribute;
  17799. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  17800. const array = dataAttribute.array;
  17801. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  17802. nodeType = nodeType.slice( 1 );
  17803. }
  17804. }
  17805. return nodeType;
  17806. }
  17807. getAttributes( shaderStage ) {
  17808. let snippet = '';
  17809. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  17810. const attributes = this.getAttributesArray();
  17811. let location = 0;
  17812. for ( const attribute of attributes ) {
  17813. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  17814. }
  17815. }
  17816. return snippet;
  17817. }
  17818. getStructMembers( struct ) {
  17819. const snippets = [];
  17820. const members = struct.getMemberTypes();
  17821. for ( let i = 0; i < members.length; i ++ ) {
  17822. const member = members[ i ];
  17823. snippets.push( `layout( location = ${i} ) out ${ member} m${i};` );
  17824. }
  17825. return snippets.join( '\n' );
  17826. }
  17827. getStructs( shaderStage ) {
  17828. const snippets = [];
  17829. const structs = this.structs[ shaderStage ];
  17830. if ( structs.length === 0 ) {
  17831. return 'layout( location = 0 ) out vec4 fragColor;\n';
  17832. }
  17833. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  17834. const struct = structs[ index ];
  17835. let snippet = '\n';
  17836. snippet += this.getStructMembers( struct );
  17837. snippet += '\n';
  17838. snippets.push( snippet );
  17839. }
  17840. return snippets.join( '\n\n' );
  17841. }
  17842. getVaryings( shaderStage ) {
  17843. let snippet = '';
  17844. const varyings = this.varyings;
  17845. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  17846. for ( const varying of varyings ) {
  17847. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  17848. const type = varying.type;
  17849. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  17850. snippet += `${flat}${varying.needsInterpolation ? 'out' : '/*out*/'} ${type} ${varying.name};\n`;
  17851. }
  17852. } else if ( shaderStage === 'fragment' ) {
  17853. for ( const varying of varyings ) {
  17854. if ( varying.needsInterpolation ) {
  17855. const type = varying.type;
  17856. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  17857. snippet += `${flat}in ${type} ${varying.name};\n`;
  17858. }
  17859. }
  17860. }
  17861. for ( const builtin of this.builtins[ shaderStage ] ) {
  17862. snippet += `${builtin};\n`;
  17863. }
  17864. return snippet;
  17865. }
  17866. getVertexIndex() {
  17867. return 'uint( gl_VertexID )';
  17868. }
  17869. getInstanceIndex() {
  17870. return 'uint( gl_InstanceID )';
  17871. }
  17872. getInvocationLocalIndex() {
  17873. const workgroupSize = this.object.workgroupSize;
  17874. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  17875. return `uint( gl_InstanceID ) % ${size}u`;
  17876. }
  17877. getDrawIndex() {
  17878. const extensions = this.renderer.backend.extensions;
  17879. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  17880. return 'uint( gl_DrawID )';
  17881. }
  17882. return null;
  17883. }
  17884. getFrontFacing() {
  17885. return 'gl_FrontFacing';
  17886. }
  17887. getFragCoord() {
  17888. return 'gl_FragCoord.xy';
  17889. }
  17890. getFragDepth() {
  17891. return 'gl_FragDepth';
  17892. }
  17893. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  17894. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  17895. if ( map.has( name ) === false ) {
  17896. map.set( name, {
  17897. name,
  17898. behavior
  17899. } );
  17900. }
  17901. }
  17902. getExtensions( shaderStage ) {
  17903. const snippets = [];
  17904. if ( shaderStage === 'vertex' ) {
  17905. const ext = this.renderer.backend.extensions;
  17906. const isBatchedMesh = this.object.isBatchedMesh;
  17907. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  17908. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  17909. }
  17910. }
  17911. const extensions = this.extensions[ shaderStage ];
  17912. if ( extensions !== undefined ) {
  17913. for ( const { name, behavior } of extensions.values() ) {
  17914. snippets.push( `#extension ${name} : ${behavior}` );
  17915. }
  17916. }
  17917. return snippets.join( '\n' );
  17918. }
  17919. getClipDistance() {
  17920. return 'gl_ClipDistance';
  17921. }
  17922. isAvailable( name ) {
  17923. let result = supports$1[ name ];
  17924. if ( result === undefined ) {
  17925. let extensionName;
  17926. result = false;
  17927. switch ( name ) {
  17928. case 'float32Filterable':
  17929. extensionName = 'OES_texture_float_linear';
  17930. break;
  17931. case 'clipDistance':
  17932. extensionName = 'WEBGL_clip_cull_distance';
  17933. break;
  17934. }
  17935. if ( extensionName !== undefined ) {
  17936. const extensions = this.renderer.backend.extensions;
  17937. if ( extensions.has( extensionName ) ) {
  17938. extensions.get( extensionName );
  17939. result = true;
  17940. }
  17941. }
  17942. supports$1[ name ] = result;
  17943. }
  17944. return result;
  17945. }
  17946. isFlipY() {
  17947. return true;
  17948. }
  17949. enableHardwareClipping( planeCount ) {
  17950. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  17951. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  17952. }
  17953. registerTransform( varyingName, attributeNode ) {
  17954. this.transforms.push( { varyingName, attributeNode } );
  17955. }
  17956. getTransforms( /* shaderStage */ ) {
  17957. const transforms = this.transforms;
  17958. let snippet = '';
  17959. for ( let i = 0; i < transforms.length; i ++ ) {
  17960. const transform = transforms[ i ];
  17961. const attributeName = this.getPropertyName( transform.attributeNode );
  17962. snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  17963. }
  17964. return snippet;
  17965. }
  17966. _getGLSLUniformStruct( name, vars ) {
  17967. return `
  17968. layout( std140 ) uniform ${name} {
  17969. ${vars}
  17970. };`;
  17971. }
  17972. _getGLSLVertexCode( shaderData ) {
  17973. return `#version 300 es
  17974. ${ this.getSignature() }
  17975. // extensions
  17976. ${shaderData.extensions}
  17977. // precision
  17978. ${ defaultPrecisions }
  17979. // uniforms
  17980. ${shaderData.uniforms}
  17981. // varyings
  17982. ${shaderData.varyings}
  17983. // attributes
  17984. ${shaderData.attributes}
  17985. // codes
  17986. ${shaderData.codes}
  17987. void main() {
  17988. // vars
  17989. ${shaderData.vars}
  17990. // transforms
  17991. ${shaderData.transforms}
  17992. // flow
  17993. ${shaderData.flow}
  17994. gl_PointSize = 1.0;
  17995. }
  17996. `;
  17997. }
  17998. _getGLSLFragmentCode( shaderData ) {
  17999. return `#version 300 es
  18000. ${ this.getSignature() }
  18001. // precision
  18002. ${ defaultPrecisions }
  18003. // uniforms
  18004. ${shaderData.uniforms}
  18005. // varyings
  18006. ${shaderData.varyings}
  18007. // codes
  18008. ${shaderData.codes}
  18009. ${shaderData.structs}
  18010. void main() {
  18011. // vars
  18012. ${shaderData.vars}
  18013. // flow
  18014. ${shaderData.flow}
  18015. }
  18016. `;
  18017. }
  18018. buildCode() {
  18019. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  18020. this.sortBindingGroups();
  18021. for ( const shaderStage in shadersData ) {
  18022. let flow = '// code\n\n';
  18023. flow += this.flowCode[ shaderStage ];
  18024. const flowNodes = this.flowNodes[ shaderStage ];
  18025. const mainNode = flowNodes[ flowNodes.length - 1 ];
  18026. for ( const node of flowNodes ) {
  18027. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  18028. const slotName = node.name;
  18029. if ( slotName ) {
  18030. if ( flow.length > 0 ) flow += '\n';
  18031. flow += `\t// flow -> ${ slotName }\n\t`;
  18032. }
  18033. flow += `${ flowSlotData.code }\n\t`;
  18034. if ( node === mainNode && shaderStage !== 'compute' ) {
  18035. flow += '// result\n\t';
  18036. if ( shaderStage === 'vertex' ) {
  18037. flow += 'gl_Position = ';
  18038. flow += `${ flowSlotData.result };`;
  18039. } else if ( shaderStage === 'fragment' ) {
  18040. if ( ! node.outputNode.isOutputStructNode ) {
  18041. flow += 'fragColor = ';
  18042. flow += `${ flowSlotData.result };`;
  18043. }
  18044. }
  18045. }
  18046. }
  18047. const stageData = shadersData[ shaderStage ];
  18048. stageData.extensions = this.getExtensions( shaderStage );
  18049. stageData.uniforms = this.getUniforms( shaderStage );
  18050. stageData.attributes = this.getAttributes( shaderStage );
  18051. stageData.varyings = this.getVaryings( shaderStage );
  18052. stageData.vars = this.getVars( shaderStage );
  18053. stageData.structs = this.getStructs( shaderStage );
  18054. stageData.codes = this.getCodes( shaderStage );
  18055. stageData.transforms = this.getTransforms( shaderStage );
  18056. stageData.flow = flow;
  18057. }
  18058. if ( this.material !== null ) {
  18059. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  18060. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  18061. } else {
  18062. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  18063. }
  18064. }
  18065. getUniformFromNode( node, type, shaderStage, name = null ) {
  18066. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  18067. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  18068. let uniformGPU = nodeData.uniformGPU;
  18069. if ( uniformGPU === undefined ) {
  18070. const group = node.groupNode;
  18071. const groupName = group.name;
  18072. const bindings = this.getBindGroupArray( groupName, shaderStage );
  18073. if ( type === 'texture' ) {
  18074. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  18075. bindings.push( uniformGPU );
  18076. } else if ( type === 'cubeTexture' ) {
  18077. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  18078. bindings.push( uniformGPU );
  18079. } else if ( type === 'texture3D' ) {
  18080. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  18081. bindings.push( uniformGPU );
  18082. } else if ( type === 'buffer' ) {
  18083. node.name = `NodeBuffer_${ node.id }`;
  18084. uniformNode.name = `buffer${ node.id }`;
  18085. const buffer = new NodeUniformBuffer( node, group );
  18086. buffer.name = node.name;
  18087. bindings.push( buffer );
  18088. uniformGPU = buffer;
  18089. } else {
  18090. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  18091. let uniformsGroup = uniformsStage[ groupName ];
  18092. if ( uniformsGroup === undefined ) {
  18093. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  18094. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  18095. uniformsStage[ groupName ] = uniformsGroup;
  18096. bindings.push( uniformsGroup );
  18097. }
  18098. uniformGPU = this.getNodeUniform( uniformNode, type );
  18099. uniformsGroup.addUniform( uniformGPU );
  18100. }
  18101. nodeData.uniformGPU = uniformGPU;
  18102. }
  18103. return uniformNode;
  18104. }
  18105. }
  18106. let vector2 = null;
  18107. let vector4 = null;
  18108. let color4 = null;
  18109. class Backend {
  18110. constructor( parameters = {} ) {
  18111. this.parameters = Object.assign( {}, parameters );
  18112. this.data = new WeakMap();
  18113. this.renderer = null;
  18114. this.domElement = null;
  18115. }
  18116. async init( renderer ) {
  18117. this.renderer = renderer;
  18118. }
  18119. // render context
  18120. begin( /*renderContext*/ ) { }
  18121. finish( /*renderContext*/ ) { }
  18122. // render object
  18123. draw( /*renderObject, info*/ ) { }
  18124. // program
  18125. createProgram( /*program*/ ) { }
  18126. destroyProgram( /*program*/ ) { }
  18127. // bindings
  18128. createBindings( /*bingGroup, bindings*/ ) { }
  18129. updateBindings( /*bingGroup, bindings*/ ) { }
  18130. // pipeline
  18131. createRenderPipeline( /*renderObject*/ ) { }
  18132. createComputePipeline( /*computeNode, pipeline*/ ) { }
  18133. destroyPipeline( /*pipeline*/ ) { }
  18134. // cache key
  18135. needsRenderUpdate( /*renderObject*/ ) { } // return Boolean ( fast test )
  18136. getRenderCacheKey( /*renderObject*/ ) { } // return String
  18137. // node builder
  18138. createNodeBuilder( /*renderObject*/ ) { } // return NodeBuilder (ADD IT)
  18139. // textures
  18140. createSampler( /*texture*/ ) { }
  18141. createDefaultTexture( /*texture*/ ) { }
  18142. createTexture( /*texture*/ ) { }
  18143. copyTextureToBuffer( /*texture, x, y, width, height*/ ) {}
  18144. // attributes
  18145. createAttribute( /*attribute*/ ) { }
  18146. createIndexAttribute( /*attribute*/ ) { }
  18147. updateAttribute( /*attribute*/ ) { }
  18148. destroyAttribute( /*attribute*/ ) { }
  18149. // canvas
  18150. getContext() { }
  18151. updateSize() { }
  18152. // utils
  18153. resolveTimestampAsync( /*renderContext, type*/ ) { }
  18154. hasFeatureAsync( /*name*/ ) { } // return Boolean
  18155. hasFeature( /*name*/ ) { } // return Boolean
  18156. getInstanceCount( renderObject ) {
  18157. const { object, geometry } = renderObject;
  18158. return geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  18159. }
  18160. getDrawingBufferSize() {
  18161. vector2 = vector2 || new Vector2();
  18162. return this.renderer.getDrawingBufferSize( vector2 );
  18163. }
  18164. getScissor() {
  18165. vector4 = vector4 || new Vector4();
  18166. return this.renderer.getScissor( vector4 );
  18167. }
  18168. setScissorTest( /*boolean*/ ) { }
  18169. getClearColor() {
  18170. const renderer = this.renderer;
  18171. color4 = color4 || new Color4();
  18172. renderer.getClearColor( color4 );
  18173. color4.getRGB( color4, this.renderer.currentColorSpace );
  18174. return color4;
  18175. }
  18176. getDomElement() {
  18177. let domElement = this.domElement;
  18178. if ( domElement === null ) {
  18179. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  18180. // OffscreenCanvas does not have setAttribute, see #22811
  18181. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  18182. this.domElement = domElement;
  18183. }
  18184. return domElement;
  18185. }
  18186. // resource properties
  18187. set( object, value ) {
  18188. this.data.set( object, value );
  18189. }
  18190. get( object ) {
  18191. let map = this.data.get( object );
  18192. if ( map === undefined ) {
  18193. map = {};
  18194. this.data.set( object, map );
  18195. }
  18196. return map;
  18197. }
  18198. has( object ) {
  18199. return this.data.has( object );
  18200. }
  18201. delete( object ) {
  18202. this.data.delete( object );
  18203. }
  18204. dispose() { }
  18205. }
  18206. let _id$1 = 0;
  18207. class DualAttributeData {
  18208. constructor( attributeData, dualBuffer ) {
  18209. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  18210. this.type = attributeData.type;
  18211. this.bufferType = attributeData.bufferType;
  18212. this.pbo = attributeData.pbo;
  18213. this.byteLength = attributeData.byteLength;
  18214. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  18215. this.version = attributeData.version;
  18216. this.isInteger = attributeData.isInteger;
  18217. this.activeBufferIndex = 0;
  18218. this.baseId = attributeData.id;
  18219. }
  18220. get id() {
  18221. return `${ this.baseId }|${ this.activeBufferIndex }`;
  18222. }
  18223. get bufferGPU() {
  18224. return this.buffers[ this.activeBufferIndex ];
  18225. }
  18226. get transformBuffer() {
  18227. return this.buffers[ this.activeBufferIndex ^ 1 ];
  18228. }
  18229. switchBuffers() {
  18230. this.activeBufferIndex ^= 1;
  18231. }
  18232. }
  18233. class WebGLAttributeUtils {
  18234. constructor( backend ) {
  18235. this.backend = backend;
  18236. }
  18237. createAttribute( attribute, bufferType ) {
  18238. const backend = this.backend;
  18239. const { gl } = backend;
  18240. const array = attribute.array;
  18241. const usage = attribute.usage || gl.STATIC_DRAW;
  18242. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  18243. const bufferData = backend.get( bufferAttribute );
  18244. let bufferGPU = bufferData.bufferGPU;
  18245. if ( bufferGPU === undefined ) {
  18246. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  18247. bufferData.bufferGPU = bufferGPU;
  18248. bufferData.bufferType = bufferType;
  18249. bufferData.version = bufferAttribute.version;
  18250. }
  18251. //attribute.onUploadCallback();
  18252. let type;
  18253. if ( array instanceof Float32Array ) {
  18254. type = gl.FLOAT;
  18255. } else if ( array instanceof Uint16Array ) {
  18256. if ( attribute.isFloat16BufferAttribute ) {
  18257. type = gl.HALF_FLOAT;
  18258. } else {
  18259. type = gl.UNSIGNED_SHORT;
  18260. }
  18261. } else if ( array instanceof Int16Array ) {
  18262. type = gl.SHORT;
  18263. } else if ( array instanceof Uint32Array ) {
  18264. type = gl.UNSIGNED_INT;
  18265. } else if ( array instanceof Int32Array ) {
  18266. type = gl.INT;
  18267. } else if ( array instanceof Int8Array ) {
  18268. type = gl.BYTE;
  18269. } else if ( array instanceof Uint8Array ) {
  18270. type = gl.UNSIGNED_BYTE;
  18271. } else if ( array instanceof Uint8ClampedArray ) {
  18272. type = gl.UNSIGNED_BYTE;
  18273. } else {
  18274. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  18275. }
  18276. let attributeData = {
  18277. bufferGPU,
  18278. bufferType,
  18279. type,
  18280. byteLength: array.byteLength,
  18281. bytesPerElement: array.BYTES_PER_ELEMENT,
  18282. version: attribute.version,
  18283. pbo: attribute.pbo,
  18284. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  18285. id: _id$1 ++
  18286. };
  18287. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  18288. // create buffer for tranform feedback use
  18289. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  18290. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  18291. }
  18292. backend.set( attribute, attributeData );
  18293. }
  18294. updateAttribute( attribute ) {
  18295. const backend = this.backend;
  18296. const { gl } = backend;
  18297. const array = attribute.array;
  18298. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  18299. const bufferData = backend.get( bufferAttribute );
  18300. const bufferType = bufferData.bufferType;
  18301. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  18302. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  18303. if ( updateRanges.length === 0 ) {
  18304. // Not using update ranges
  18305. gl.bufferSubData( bufferType, 0, array );
  18306. } else {
  18307. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  18308. const range = updateRanges[ i ];
  18309. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  18310. array, range.start, range.count );
  18311. }
  18312. bufferAttribute.clearUpdateRanges();
  18313. }
  18314. gl.bindBuffer( bufferType, null );
  18315. bufferData.version = bufferAttribute.version;
  18316. }
  18317. destroyAttribute( attribute ) {
  18318. const backend = this.backend;
  18319. const { gl } = backend;
  18320. if ( attribute.isInterleavedBufferAttribute ) {
  18321. backend.delete( attribute.data );
  18322. }
  18323. const attributeData = backend.get( attribute );
  18324. gl.deleteBuffer( attributeData.bufferGPU );
  18325. backend.delete( attribute );
  18326. }
  18327. async getArrayBufferAsync( attribute ) {
  18328. const backend = this.backend;
  18329. const { gl } = backend;
  18330. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  18331. const { bufferGPU } = backend.get( bufferAttribute );
  18332. const array = attribute.array;
  18333. const byteLength = array.byteLength;
  18334. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  18335. const writeBuffer = gl.createBuffer();
  18336. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  18337. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  18338. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  18339. await backend.utils._clientWaitAsync();
  18340. const dstBuffer = new attribute.array.constructor( array.length );
  18341. // Ensure the buffer is bound before reading
  18342. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  18343. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  18344. gl.deleteBuffer( writeBuffer );
  18345. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  18346. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  18347. return dstBuffer.buffer;
  18348. }
  18349. _createBuffer( gl, bufferType, array, usage ) {
  18350. const bufferGPU = gl.createBuffer();
  18351. gl.bindBuffer( bufferType, bufferGPU );
  18352. gl.bufferData( bufferType, array, usage );
  18353. gl.bindBuffer( bufferType, null );
  18354. return bufferGPU;
  18355. }
  18356. }
  18357. let initialized$1 = false, equationToGL, factorToGL;
  18358. class WebGLState {
  18359. constructor( backend ) {
  18360. this.backend = backend;
  18361. this.gl = this.backend.gl;
  18362. this.enabled = {};
  18363. this.currentFlipSided = null;
  18364. this.currentCullFace = null;
  18365. this.currentProgram = null;
  18366. this.currentBlendingEnabled = false;
  18367. this.currentBlending = null;
  18368. this.currentBlendSrc = null;
  18369. this.currentBlendDst = null;
  18370. this.currentBlendSrcAlpha = null;
  18371. this.currentBlendDstAlpha = null;
  18372. this.currentPremultipledAlpha = null;
  18373. this.currentPolygonOffsetFactor = null;
  18374. this.currentPolygonOffsetUnits = null;
  18375. this.currentColorMask = null;
  18376. this.currentDepthFunc = null;
  18377. this.currentDepthMask = null;
  18378. this.currentStencilFunc = null;
  18379. this.currentStencilRef = null;
  18380. this.currentStencilFuncMask = null;
  18381. this.currentStencilFail = null;
  18382. this.currentStencilZFail = null;
  18383. this.currentStencilZPass = null;
  18384. this.currentStencilMask = null;
  18385. this.currentLineWidth = null;
  18386. this.currentClippingPlanes = 0;
  18387. this.currentBoundFramebuffers = {};
  18388. this.currentDrawbuffers = new WeakMap();
  18389. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  18390. this.currentTextureSlot = null;
  18391. this.currentBoundTextures = {};
  18392. this.currentBoundBufferBases = {};
  18393. if ( initialized$1 === false ) {
  18394. this._init( this.gl );
  18395. initialized$1 = true;
  18396. }
  18397. }
  18398. _init( gl ) {
  18399. // Store only WebGL constants here.
  18400. equationToGL = {
  18401. [ AddEquation ]: gl.FUNC_ADD,
  18402. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  18403. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  18404. };
  18405. factorToGL = {
  18406. [ ZeroFactor ]: gl.ZERO,
  18407. [ OneFactor ]: gl.ONE,
  18408. [ SrcColorFactor ]: gl.SRC_COLOR,
  18409. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  18410. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  18411. [ DstColorFactor ]: gl.DST_COLOR,
  18412. [ DstAlphaFactor ]: gl.DST_ALPHA,
  18413. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  18414. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  18415. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  18416. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  18417. };
  18418. }
  18419. enable( id ) {
  18420. const { enabled } = this;
  18421. if ( enabled[ id ] !== true ) {
  18422. this.gl.enable( id );
  18423. enabled[ id ] = true;
  18424. }
  18425. }
  18426. disable( id ) {
  18427. const { enabled } = this;
  18428. if ( enabled[ id ] !== false ) {
  18429. this.gl.disable( id );
  18430. enabled[ id ] = false;
  18431. }
  18432. }
  18433. setFlipSided( flipSided ) {
  18434. if ( this.currentFlipSided !== flipSided ) {
  18435. const { gl } = this;
  18436. if ( flipSided ) {
  18437. gl.frontFace( gl.CW );
  18438. } else {
  18439. gl.frontFace( gl.CCW );
  18440. }
  18441. this.currentFlipSided = flipSided;
  18442. }
  18443. }
  18444. setCullFace( cullFace ) {
  18445. const { gl } = this;
  18446. if ( cullFace !== CullFaceNone ) {
  18447. this.enable( gl.CULL_FACE );
  18448. if ( cullFace !== this.currentCullFace ) {
  18449. if ( cullFace === CullFaceBack ) {
  18450. gl.cullFace( gl.BACK );
  18451. } else if ( cullFace === CullFaceFront ) {
  18452. gl.cullFace( gl.FRONT );
  18453. } else {
  18454. gl.cullFace( gl.FRONT_AND_BACK );
  18455. }
  18456. }
  18457. } else {
  18458. this.disable( gl.CULL_FACE );
  18459. }
  18460. this.currentCullFace = cullFace;
  18461. }
  18462. setLineWidth( width ) {
  18463. const { currentLineWidth, gl } = this;
  18464. if ( width !== currentLineWidth ) {
  18465. gl.lineWidth( width );
  18466. this.currentLineWidth = width;
  18467. }
  18468. }
  18469. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  18470. const { gl } = this;
  18471. if ( blending === NoBlending ) {
  18472. if ( this.currentBlendingEnabled === true ) {
  18473. this.disable( gl.BLEND );
  18474. this.currentBlendingEnabled = false;
  18475. }
  18476. return;
  18477. }
  18478. if ( this.currentBlendingEnabled === false ) {
  18479. this.enable( gl.BLEND );
  18480. this.currentBlendingEnabled = true;
  18481. }
  18482. if ( blending !== CustomBlending ) {
  18483. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  18484. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  18485. gl.blendEquation( gl.FUNC_ADD );
  18486. this.currentBlendEquation = AddEquation;
  18487. this.currentBlendEquationAlpha = AddEquation;
  18488. }
  18489. if ( premultipliedAlpha ) {
  18490. switch ( blending ) {
  18491. case NormalBlending:
  18492. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  18493. break;
  18494. case AdditiveBlending:
  18495. gl.blendFunc( gl.ONE, gl.ONE );
  18496. break;
  18497. case SubtractiveBlending:
  18498. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  18499. break;
  18500. case MultiplyBlending:
  18501. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  18502. break;
  18503. default:
  18504. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  18505. break;
  18506. }
  18507. } else {
  18508. switch ( blending ) {
  18509. case NormalBlending:
  18510. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  18511. break;
  18512. case AdditiveBlending:
  18513. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  18514. break;
  18515. case SubtractiveBlending:
  18516. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  18517. break;
  18518. case MultiplyBlending:
  18519. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  18520. break;
  18521. default:
  18522. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  18523. break;
  18524. }
  18525. }
  18526. this.currentBlendSrc = null;
  18527. this.currentBlendDst = null;
  18528. this.currentBlendSrcAlpha = null;
  18529. this.currentBlendDstAlpha = null;
  18530. this.currentBlending = blending;
  18531. this.currentPremultipledAlpha = premultipliedAlpha;
  18532. }
  18533. return;
  18534. }
  18535. // custom blending
  18536. blendEquationAlpha = blendEquationAlpha || blendEquation;
  18537. blendSrcAlpha = blendSrcAlpha || blendSrc;
  18538. blendDstAlpha = blendDstAlpha || blendDst;
  18539. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  18540. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  18541. this.currentBlendEquation = blendEquation;
  18542. this.currentBlendEquationAlpha = blendEquationAlpha;
  18543. }
  18544. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  18545. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  18546. this.currentBlendSrc = blendSrc;
  18547. this.currentBlendDst = blendDst;
  18548. this.currentBlendSrcAlpha = blendSrcAlpha;
  18549. this.currentBlendDstAlpha = blendDstAlpha;
  18550. }
  18551. this.currentBlending = blending;
  18552. this.currentPremultipledAlpha = false;
  18553. }
  18554. setColorMask( colorMask ) {
  18555. if ( this.currentColorMask !== colorMask ) {
  18556. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  18557. this.currentColorMask = colorMask;
  18558. }
  18559. }
  18560. setDepthTest( depthTest ) {
  18561. const { gl } = this;
  18562. if ( depthTest ) {
  18563. this.enable( gl.DEPTH_TEST );
  18564. } else {
  18565. this.disable( gl.DEPTH_TEST );
  18566. }
  18567. }
  18568. setDepthMask( depthMask ) {
  18569. if ( this.currentDepthMask !== depthMask ) {
  18570. this.gl.depthMask( depthMask );
  18571. this.currentDepthMask = depthMask;
  18572. }
  18573. }
  18574. setDepthFunc( depthFunc ) {
  18575. if ( this.currentDepthFunc !== depthFunc ) {
  18576. const { gl } = this;
  18577. switch ( depthFunc ) {
  18578. case NeverDepth:
  18579. gl.depthFunc( gl.NEVER );
  18580. break;
  18581. case AlwaysDepth:
  18582. gl.depthFunc( gl.ALWAYS );
  18583. break;
  18584. case LessDepth:
  18585. gl.depthFunc( gl.LESS );
  18586. break;
  18587. case LessEqualDepth:
  18588. gl.depthFunc( gl.LEQUAL );
  18589. break;
  18590. case EqualDepth:
  18591. gl.depthFunc( gl.EQUAL );
  18592. break;
  18593. case GreaterEqualDepth:
  18594. gl.depthFunc( gl.GEQUAL );
  18595. break;
  18596. case GreaterDepth:
  18597. gl.depthFunc( gl.GREATER );
  18598. break;
  18599. case NotEqualDepth:
  18600. gl.depthFunc( gl.NOTEQUAL );
  18601. break;
  18602. default:
  18603. gl.depthFunc( gl.LEQUAL );
  18604. }
  18605. this.currentDepthFunc = depthFunc;
  18606. }
  18607. }
  18608. setStencilTest( stencilTest ) {
  18609. const { gl } = this;
  18610. if ( stencilTest ) {
  18611. this.enable( gl.STENCIL_TEST );
  18612. } else {
  18613. this.disable( gl.STENCIL_TEST );
  18614. }
  18615. }
  18616. setStencilMask( stencilMask ) {
  18617. if ( this.currentStencilMask !== stencilMask ) {
  18618. this.gl.stencilMask( stencilMask );
  18619. this.currentStencilMask = stencilMask;
  18620. }
  18621. }
  18622. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  18623. if ( this.currentStencilFunc !== stencilFunc ||
  18624. this.currentStencilRef !== stencilRef ||
  18625. this.currentStencilFuncMask !== stencilMask ) {
  18626. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  18627. this.currentStencilFunc = stencilFunc;
  18628. this.currentStencilRef = stencilRef;
  18629. this.currentStencilFuncMask = stencilMask;
  18630. }
  18631. }
  18632. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  18633. if ( this.currentStencilFail !== stencilFail ||
  18634. this.currentStencilZFail !== stencilZFail ||
  18635. this.currentStencilZPass !== stencilZPass ) {
  18636. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  18637. this.currentStencilFail = stencilFail;
  18638. this.currentStencilZFail = stencilZFail;
  18639. this.currentStencilZPass = stencilZPass;
  18640. }
  18641. }
  18642. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  18643. const { gl } = this;
  18644. material.side === DoubleSide
  18645. ? this.disable( gl.CULL_FACE )
  18646. : this.enable( gl.CULL_FACE );
  18647. let flipSided = ( material.side === BackSide );
  18648. if ( frontFaceCW ) flipSided = ! flipSided;
  18649. this.setFlipSided( flipSided );
  18650. ( material.blending === NormalBlending && material.transparent === false )
  18651. ? this.setBlending( NoBlending )
  18652. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  18653. this.setDepthFunc( material.depthFunc );
  18654. this.setDepthTest( material.depthTest );
  18655. this.setDepthMask( material.depthWrite );
  18656. this.setColorMask( material.colorWrite );
  18657. const stencilWrite = material.stencilWrite;
  18658. this.setStencilTest( stencilWrite );
  18659. if ( stencilWrite ) {
  18660. this.setStencilMask( material.stencilWriteMask );
  18661. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  18662. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  18663. }
  18664. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  18665. material.alphaToCoverage === true && this.backend.renderer.samples > 1
  18666. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  18667. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  18668. if ( hardwareClippingPlanes > 0 ) {
  18669. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  18670. const CLIP_DISTANCE0_WEBGL = 0x3000;
  18671. for ( let i = 0; i < 8; i ++ ) {
  18672. if ( i < hardwareClippingPlanes ) {
  18673. this.enable( CLIP_DISTANCE0_WEBGL + i );
  18674. } else {
  18675. this.disable( CLIP_DISTANCE0_WEBGL + i );
  18676. }
  18677. }
  18678. }
  18679. }
  18680. }
  18681. setPolygonOffset( polygonOffset, factor, units ) {
  18682. const { gl } = this;
  18683. if ( polygonOffset ) {
  18684. this.enable( gl.POLYGON_OFFSET_FILL );
  18685. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  18686. gl.polygonOffset( factor, units );
  18687. this.currentPolygonOffsetFactor = factor;
  18688. this.currentPolygonOffsetUnits = units;
  18689. }
  18690. } else {
  18691. this.disable( gl.POLYGON_OFFSET_FILL );
  18692. }
  18693. }
  18694. useProgram( program ) {
  18695. if ( this.currentProgram !== program ) {
  18696. this.gl.useProgram( program );
  18697. this.currentProgram = program;
  18698. return true;
  18699. }
  18700. return false;
  18701. }
  18702. // framebuffer
  18703. bindFramebuffer( target, framebuffer ) {
  18704. const { gl, currentBoundFramebuffers } = this;
  18705. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  18706. gl.bindFramebuffer( target, framebuffer );
  18707. currentBoundFramebuffers[ target ] = framebuffer;
  18708. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  18709. if ( target === gl.DRAW_FRAMEBUFFER ) {
  18710. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  18711. }
  18712. if ( target === gl.FRAMEBUFFER ) {
  18713. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  18714. }
  18715. return true;
  18716. }
  18717. return false;
  18718. }
  18719. drawBuffers( renderContext, framebuffer ) {
  18720. const { gl } = this;
  18721. let drawBuffers = [];
  18722. let needsUpdate = false;
  18723. if ( renderContext.textures !== null ) {
  18724. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  18725. if ( drawBuffers === undefined ) {
  18726. drawBuffers = [];
  18727. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  18728. }
  18729. const textures = renderContext.textures;
  18730. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  18731. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  18732. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  18733. }
  18734. drawBuffers.length = textures.length;
  18735. needsUpdate = true;
  18736. }
  18737. } else {
  18738. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  18739. drawBuffers[ 0 ] = gl.BACK;
  18740. needsUpdate = true;
  18741. }
  18742. }
  18743. if ( needsUpdate ) {
  18744. gl.drawBuffers( drawBuffers );
  18745. }
  18746. }
  18747. // texture
  18748. activeTexture( webglSlot ) {
  18749. const { gl, currentTextureSlot, maxTextures } = this;
  18750. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  18751. if ( currentTextureSlot !== webglSlot ) {
  18752. gl.activeTexture( webglSlot );
  18753. this.currentTextureSlot = webglSlot;
  18754. }
  18755. }
  18756. bindTexture( webglType, webglTexture, webglSlot ) {
  18757. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  18758. if ( webglSlot === undefined ) {
  18759. if ( currentTextureSlot === null ) {
  18760. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  18761. } else {
  18762. webglSlot = currentTextureSlot;
  18763. }
  18764. }
  18765. let boundTexture = currentBoundTextures[ webglSlot ];
  18766. if ( boundTexture === undefined ) {
  18767. boundTexture = { type: undefined, texture: undefined };
  18768. currentBoundTextures[ webglSlot ] = boundTexture;
  18769. }
  18770. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  18771. if ( currentTextureSlot !== webglSlot ) {
  18772. gl.activeTexture( webglSlot );
  18773. this.currentTextureSlot = webglSlot;
  18774. }
  18775. gl.bindTexture( webglType, webglTexture );
  18776. boundTexture.type = webglType;
  18777. boundTexture.texture = webglTexture;
  18778. }
  18779. }
  18780. bindBufferBase( target, index, buffer ) {
  18781. const { gl } = this;
  18782. const key = `${target}-${index}`;
  18783. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  18784. gl.bindBufferBase( target, index, buffer );
  18785. this.currentBoundBufferBases[ key ] = buffer;
  18786. return true;
  18787. }
  18788. return false;
  18789. }
  18790. unbindTexture() {
  18791. const { gl, currentTextureSlot, currentBoundTextures } = this;
  18792. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  18793. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  18794. gl.bindTexture( boundTexture.type, null );
  18795. boundTexture.type = undefined;
  18796. boundTexture.texture = undefined;
  18797. }
  18798. }
  18799. }
  18800. class WebGLUtils {
  18801. constructor( backend ) {
  18802. this.backend = backend;
  18803. this.gl = this.backend.gl;
  18804. this.extensions = backend.extensions;
  18805. }
  18806. convert( p, colorSpace = NoColorSpace ) {
  18807. const { gl, extensions } = this;
  18808. let extension;
  18809. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  18810. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  18811. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  18812. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  18813. if ( p === ByteType ) return gl.BYTE;
  18814. if ( p === ShortType ) return gl.SHORT;
  18815. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  18816. if ( p === IntType ) return gl.INT;
  18817. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  18818. if ( p === FloatType ) return gl.FLOAT;
  18819. if ( p === HalfFloatType ) {
  18820. return gl.HALF_FLOAT;
  18821. }
  18822. if ( p === AlphaFormat ) return gl.ALPHA;
  18823. if ( p === RGBFormat ) return gl.RGB;
  18824. if ( p === RGBAFormat ) return gl.RGBA;
  18825. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  18826. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  18827. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  18828. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  18829. // WebGL2 formats.
  18830. if ( p === RedFormat ) return gl.RED;
  18831. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  18832. if ( p === RGFormat ) return gl.RG;
  18833. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  18834. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  18835. // S3TC
  18836. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  18837. if ( colorSpace === SRGBColorSpace ) {
  18838. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  18839. if ( extension !== null ) {
  18840. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  18841. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  18842. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  18843. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  18844. } else {
  18845. return null;
  18846. }
  18847. } else {
  18848. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  18849. if ( extension !== null ) {
  18850. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  18851. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  18852. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  18853. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  18854. } else {
  18855. return null;
  18856. }
  18857. }
  18858. }
  18859. // PVRTC
  18860. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  18861. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  18862. if ( extension !== null ) {
  18863. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  18864. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  18865. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  18866. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  18867. } else {
  18868. return null;
  18869. }
  18870. }
  18871. // ETC
  18872. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  18873. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  18874. if ( extension !== null ) {
  18875. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  18876. if ( p === RGBA_ETC2_EAC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  18877. } else {
  18878. return null;
  18879. }
  18880. }
  18881. // ASTC
  18882. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  18883. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  18884. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  18885. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  18886. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  18887. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  18888. if ( extension !== null ) {
  18889. if ( p === RGBA_ASTC_4x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  18890. if ( p === RGBA_ASTC_5x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  18891. if ( p === RGBA_ASTC_5x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  18892. if ( p === RGBA_ASTC_6x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  18893. if ( p === RGBA_ASTC_6x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  18894. if ( p === RGBA_ASTC_8x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  18895. if ( p === RGBA_ASTC_8x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  18896. if ( p === RGBA_ASTC_8x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  18897. if ( p === RGBA_ASTC_10x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  18898. if ( p === RGBA_ASTC_10x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  18899. if ( p === RGBA_ASTC_10x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  18900. if ( p === RGBA_ASTC_10x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  18901. if ( p === RGBA_ASTC_12x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  18902. if ( p === RGBA_ASTC_12x12_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  18903. } else {
  18904. return null;
  18905. }
  18906. }
  18907. // BPTC
  18908. if ( p === RGBA_BPTC_Format ) {
  18909. extension = extensions.get( 'EXT_texture_compression_bptc' );
  18910. if ( extension !== null ) {
  18911. if ( p === RGBA_BPTC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  18912. } else {
  18913. return null;
  18914. }
  18915. }
  18916. // RGTC
  18917. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  18918. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  18919. if ( extension !== null ) {
  18920. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  18921. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  18922. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  18923. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  18924. } else {
  18925. return null;
  18926. }
  18927. }
  18928. //
  18929. if ( p === UnsignedInt248Type ) {
  18930. return gl.UNSIGNED_INT_24_8;
  18931. }
  18932. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  18933. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  18934. }
  18935. _clientWaitAsync() {
  18936. const { gl } = this;
  18937. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  18938. gl.flush();
  18939. return new Promise( ( resolve, reject ) => {
  18940. function test() {
  18941. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  18942. if ( res === gl.WAIT_FAILED ) {
  18943. gl.deleteSync( sync );
  18944. reject();
  18945. return;
  18946. }
  18947. if ( res === gl.TIMEOUT_EXPIRED ) {
  18948. requestAnimationFrame( test );
  18949. return;
  18950. }
  18951. gl.deleteSync( sync );
  18952. resolve();
  18953. }
  18954. test();
  18955. } );
  18956. }
  18957. }
  18958. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  18959. class WebGLTextureUtils {
  18960. constructor( backend ) {
  18961. this.backend = backend;
  18962. this.gl = backend.gl;
  18963. this.extensions = backend.extensions;
  18964. this.defaultTextures = {};
  18965. if ( initialized === false ) {
  18966. this._init( this.gl );
  18967. initialized = true;
  18968. }
  18969. }
  18970. _init( gl ) {
  18971. // Store only WebGL constants here.
  18972. wrappingToGL = {
  18973. [ RepeatWrapping ]: gl.REPEAT,
  18974. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  18975. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  18976. };
  18977. filterToGL = {
  18978. [ NearestFilter ]: gl.NEAREST,
  18979. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  18980. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  18981. [ LinearFilter ]: gl.LINEAR,
  18982. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  18983. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  18984. };
  18985. compareToGL = {
  18986. [ NeverCompare ]: gl.NEVER,
  18987. [ AlwaysCompare ]: gl.ALWAYS,
  18988. [ LessCompare ]: gl.LESS,
  18989. [ LessEqualCompare ]: gl.LEQUAL,
  18990. [ EqualCompare ]: gl.EQUAL,
  18991. [ GreaterEqualCompare ]: gl.GEQUAL,
  18992. [ GreaterCompare ]: gl.GREATER,
  18993. [ NotEqualCompare ]: gl.NOTEQUAL
  18994. };
  18995. }
  18996. filterFallback( f ) {
  18997. const { gl } = this;
  18998. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  18999. return gl.NEAREST;
  19000. }
  19001. return gl.LINEAR;
  19002. }
  19003. getGLTextureType( texture ) {
  19004. const { gl } = this;
  19005. let glTextureType;
  19006. if ( texture.isCubeTexture === true ) {
  19007. glTextureType = gl.TEXTURE_CUBE_MAP;
  19008. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  19009. glTextureType = gl.TEXTURE_2D_ARRAY;
  19010. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  19011. glTextureType = gl.TEXTURE_3D;
  19012. } else {
  19013. glTextureType = gl.TEXTURE_2D;
  19014. }
  19015. return glTextureType;
  19016. }
  19017. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  19018. const { gl, extensions } = this;
  19019. if ( internalFormatName !== null ) {
  19020. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  19021. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  19022. }
  19023. let internalFormat = glFormat;
  19024. if ( glFormat === gl.RED ) {
  19025. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  19026. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  19027. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  19028. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  19029. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  19030. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  19031. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  19032. if ( glType === gl.INT ) internalFormat = gl.R32I;
  19033. }
  19034. if ( glFormat === gl.RED_INTEGER ) {
  19035. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  19036. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  19037. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  19038. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  19039. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  19040. if ( glType === gl.INT ) internalFormat = gl.R32I;
  19041. }
  19042. if ( glFormat === gl.RG ) {
  19043. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  19044. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  19045. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  19046. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  19047. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  19048. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  19049. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  19050. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  19051. }
  19052. if ( glFormat === gl.RG_INTEGER ) {
  19053. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  19054. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  19055. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  19056. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  19057. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  19058. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  19059. }
  19060. if ( glFormat === gl.RGB ) {
  19061. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  19062. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  19063. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  19064. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  19065. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  19066. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  19067. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  19068. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  19069. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8 : gl.RGB8;
  19070. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  19071. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  19072. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  19073. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  19074. }
  19075. if ( glFormat === gl.RGB_INTEGER ) {
  19076. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  19077. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  19078. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  19079. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  19080. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  19081. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  19082. }
  19083. if ( glFormat === gl.RGBA ) {
  19084. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  19085. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  19086. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  19087. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  19088. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  19089. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  19090. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  19091. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  19092. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  19093. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  19094. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  19095. }
  19096. if ( glFormat === gl.RGBA_INTEGER ) {
  19097. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  19098. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  19099. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  19100. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  19101. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  19102. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  19103. }
  19104. if ( glFormat === gl.DEPTH_COMPONENT ) {
  19105. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH24_STENCIL8;
  19106. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  19107. }
  19108. if ( glFormat === gl.DEPTH_STENCIL ) {
  19109. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  19110. }
  19111. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  19112. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  19113. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  19114. extensions.get( 'EXT_color_buffer_float' );
  19115. }
  19116. return internalFormat;
  19117. }
  19118. setTextureParameters( textureType, texture ) {
  19119. const { gl, extensions, backend } = this;
  19120. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  19121. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  19122. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  19123. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE );
  19124. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  19125. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  19126. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  19127. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  19128. }
  19129. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  19130. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  19131. // follow WebGPU backend mapping for texture filtering
  19132. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  19133. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  19134. if ( texture.compareFunction ) {
  19135. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  19136. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  19137. }
  19138. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  19139. if ( texture.magFilter === NearestFilter ) return;
  19140. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  19141. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  19142. if ( texture.anisotropy > 1 ) {
  19143. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  19144. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  19145. }
  19146. }
  19147. }
  19148. createDefaultTexture( texture ) {
  19149. const { gl, backend, defaultTextures } = this;
  19150. const glTextureType = this.getGLTextureType( texture );
  19151. let textureGPU = defaultTextures[ glTextureType ];
  19152. if ( textureGPU === undefined ) {
  19153. textureGPU = gl.createTexture();
  19154. backend.state.bindTexture( glTextureType, textureGPU );
  19155. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  19156. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  19157. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  19158. defaultTextures[ glTextureType ] = textureGPU;
  19159. }
  19160. backend.set( texture, {
  19161. textureGPU,
  19162. glTextureType,
  19163. isDefault: true
  19164. } );
  19165. }
  19166. createTexture( texture, options ) {
  19167. const { gl, backend } = this;
  19168. const { levels, width, height, depth } = options;
  19169. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  19170. const glType = backend.utils.convert( texture.type );
  19171. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  19172. const textureGPU = gl.createTexture();
  19173. const glTextureType = this.getGLTextureType( texture );
  19174. backend.state.bindTexture( glTextureType, textureGPU );
  19175. this.setTextureParameters( glTextureType, texture );
  19176. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  19177. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  19178. } else if ( texture.isData3DTexture ) {
  19179. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  19180. } else if ( ! texture.isVideoTexture ) {
  19181. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  19182. }
  19183. backend.set( texture, {
  19184. textureGPU,
  19185. glTextureType,
  19186. glFormat,
  19187. glType,
  19188. glInternalFormat
  19189. } );
  19190. }
  19191. copyBufferToTexture( buffer, texture ) {
  19192. const { gl, backend } = this;
  19193. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  19194. const { width, height } = texture.source.data;
  19195. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  19196. backend.state.bindTexture( glTextureType, textureGPU );
  19197. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  19198. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  19199. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  19200. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  19201. backend.state.unbindTexture();
  19202. // debug
  19203. // const framebuffer = gl.createFramebuffer();
  19204. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  19205. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  19206. // const readout = new Float32Array( width * height * 4 );
  19207. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  19208. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  19209. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  19210. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  19211. // console.log( readout );
  19212. }
  19213. updateTexture( texture, options ) {
  19214. const { gl } = this;
  19215. const { width, height } = options;
  19216. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  19217. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  19218. return;
  19219. const getImage = ( source ) => {
  19220. if ( source.isDataTexture ) {
  19221. return source.image.data;
  19222. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  19223. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  19224. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  19225. source instanceof OffscreenCanvas ) {
  19226. return source;
  19227. }
  19228. return source.data;
  19229. };
  19230. this.backend.state.bindTexture( glTextureType, textureGPU );
  19231. this.setTextureParameters( glTextureType, texture );
  19232. if ( texture.isCompressedTexture ) {
  19233. const mipmaps = texture.mipmaps;
  19234. const image = options.image;
  19235. for ( let i = 0; i < mipmaps.length; i ++ ) {
  19236. const mipmap = mipmaps[ i ];
  19237. if ( texture.isCompressedArrayTexture ) {
  19238. if ( texture.format !== gl.RGBA ) {
  19239. if ( glFormat !== null ) {
  19240. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  19241. } else {
  19242. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  19243. }
  19244. } else {
  19245. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  19246. }
  19247. } else {
  19248. if ( glFormat !== null ) {
  19249. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  19250. } else {
  19251. console.warn( 'Unsupported compressed texture format' );
  19252. }
  19253. }
  19254. }
  19255. } else if ( texture.isCubeTexture ) {
  19256. const images = options.images;
  19257. for ( let i = 0; i < 6; i ++ ) {
  19258. const image = getImage( images[ i ] );
  19259. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  19260. }
  19261. } else if ( texture.isDataArrayTexture ) {
  19262. const image = options.image;
  19263. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  19264. } else if ( texture.isData3DTexture ) {
  19265. const image = options.image;
  19266. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  19267. } else if ( texture.isVideoTexture ) {
  19268. texture.update();
  19269. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  19270. } else {
  19271. const image = getImage( options.image );
  19272. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  19273. }
  19274. }
  19275. generateMipmaps( texture ) {
  19276. const { gl, backend } = this;
  19277. const { textureGPU, glTextureType } = backend.get( texture );
  19278. backend.state.bindTexture( glTextureType, textureGPU );
  19279. gl.generateMipmap( glTextureType );
  19280. }
  19281. deallocateRenderBuffers( renderTarget ) {
  19282. const { gl, backend } = this;
  19283. // remove framebuffer reference
  19284. if ( renderTarget ) {
  19285. const renderContextData = backend.get( renderTarget );
  19286. renderContextData.renderBufferStorageSetup = undefined;
  19287. if ( renderContextData.framebuffers ) {
  19288. for ( const cacheKey in renderContextData.framebuffers ) {
  19289. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  19290. }
  19291. delete renderContextData.framebuffers;
  19292. }
  19293. if ( renderContextData.depthRenderbuffer ) {
  19294. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  19295. delete renderContextData.depthRenderbuffer;
  19296. }
  19297. if ( renderContextData.stencilRenderbuffer ) {
  19298. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  19299. delete renderContextData.stencilRenderbuffer;
  19300. }
  19301. if ( renderContextData.msaaFrameBuffer ) {
  19302. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  19303. delete renderContextData.msaaFrameBuffer;
  19304. }
  19305. if ( renderContextData.msaaRenderbuffers ) {
  19306. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  19307. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  19308. }
  19309. delete renderContextData.msaaRenderbuffers;
  19310. }
  19311. }
  19312. }
  19313. destroyTexture( texture ) {
  19314. const { gl, backend } = this;
  19315. const { textureGPU, renderTarget } = backend.get( texture );
  19316. this.deallocateRenderBuffers( renderTarget );
  19317. gl.deleteTexture( textureGPU );
  19318. backend.delete( texture );
  19319. }
  19320. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  19321. const { gl, backend } = this;
  19322. const { state } = this.backend;
  19323. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  19324. let width, height, minX, minY;
  19325. let dstX, dstY;
  19326. if ( srcRegion !== null ) {
  19327. width = srcRegion.max.x - srcRegion.min.x;
  19328. height = srcRegion.max.y - srcRegion.min.y;
  19329. minX = srcRegion.min.x;
  19330. minY = srcRegion.min.y;
  19331. } else {
  19332. width = srcTexture.image.width;
  19333. height = srcTexture.image.height;
  19334. minX = 0;
  19335. minY = 0;
  19336. }
  19337. if ( dstPosition !== null ) {
  19338. dstX = dstPosition.x;
  19339. dstY = dstPosition.y;
  19340. } else {
  19341. dstX = 0;
  19342. dstY = 0;
  19343. }
  19344. state.bindTexture( glTextureType, dstTextureGPU );
  19345. // As another texture upload may have changed pixelStorei
  19346. // parameters, make sure they are correct for the dstTexture
  19347. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  19348. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  19349. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  19350. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  19351. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  19352. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  19353. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  19354. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  19355. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  19356. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  19357. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  19358. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  19359. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  19360. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  19361. if ( srcTexture.isRenderTargetTexture || srcTexture.isDepthTexture ) {
  19362. const srcTextureData = backend.get( srcTexture );
  19363. const dstTextureData = backend.get( dstTexture );
  19364. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  19365. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  19366. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  19367. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  19368. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  19369. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  19370. let mask = gl.COLOR_BUFFER_BIT;
  19371. if ( srcTexture.isDepthTexture ) mask = gl.DEPTH_BUFFER_BIT;
  19372. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, mask, gl.NEAREST );
  19373. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  19374. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  19375. } else {
  19376. if ( srcTexture.isDataTexture ) {
  19377. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image.data );
  19378. } else {
  19379. if ( srcTexture.isCompressedTexture ) {
  19380. gl.compressedTexSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, image.width, image.height, glFormat, image.data );
  19381. } else {
  19382. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image );
  19383. }
  19384. }
  19385. }
  19386. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  19387. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  19388. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  19389. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  19390. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  19391. // Generate mipmaps only when copying level 0
  19392. if ( level === 0 && dstTexture.generateMipmaps ) gl.generateMipmap( gl.TEXTURE_2D );
  19393. state.unbindTexture();
  19394. }
  19395. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  19396. const { gl } = this;
  19397. const { state } = this.backend;
  19398. const { textureGPU } = this.backend.get( texture );
  19399. const { x, y, z: width, w: height } = rectangle;
  19400. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  19401. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.gerDrawingBufferSize().y;
  19402. if ( requireDrawFrameBuffer ) {
  19403. const partial = ( x !== 0 || y !== 0 );
  19404. let mask;
  19405. let attachment;
  19406. if ( texture.isDepthTexture === true ) {
  19407. mask = gl.DEPTH_BUFFER_BIT;
  19408. attachment = gl.DEPTH_ATTACHMENT;
  19409. if ( renderContext.stencil ) {
  19410. mask |= gl.STENCIL_BUFFER_BIT;
  19411. }
  19412. } else {
  19413. mask = gl.COLOR_BUFFER_BIT;
  19414. attachment = gl.COLOR_ATTACHMENT0;
  19415. }
  19416. if ( partial ) {
  19417. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  19418. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  19419. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  19420. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  19421. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  19422. const flippedY = srcHeight - y - height;
  19423. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  19424. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  19425. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  19426. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  19427. state.unbindTexture();
  19428. } else {
  19429. const fb = gl.createFramebuffer();
  19430. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  19431. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  19432. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  19433. gl.deleteFramebuffer( fb );
  19434. }
  19435. } else {
  19436. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  19437. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  19438. state.unbindTexture();
  19439. }
  19440. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  19441. this.backend._setFramebuffer( renderContext );
  19442. }
  19443. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  19444. setupRenderBufferStorage( renderbuffer, renderContext ) {
  19445. const { gl } = this;
  19446. const renderTarget = renderContext.renderTarget;
  19447. const { samples, depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  19448. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  19449. if ( depthBuffer && ! stencilBuffer ) {
  19450. let glInternalFormat = gl.DEPTH_COMPONENT24;
  19451. if ( samples > 0 ) {
  19452. if ( depthTexture && depthTexture.isDepthTexture ) {
  19453. if ( depthTexture.type === gl.FLOAT ) {
  19454. glInternalFormat = gl.DEPTH_COMPONENT32F;
  19455. }
  19456. }
  19457. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  19458. } else {
  19459. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  19460. }
  19461. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  19462. } else if ( depthBuffer && stencilBuffer ) {
  19463. if ( samples > 0 ) {
  19464. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  19465. } else {
  19466. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  19467. }
  19468. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  19469. }
  19470. }
  19471. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  19472. const { backend, gl } = this;
  19473. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  19474. const fb = gl.createFramebuffer();
  19475. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  19476. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  19477. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  19478. const typedArrayType = this._getTypedArrayType( glType );
  19479. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  19480. const elementCount = width * height;
  19481. const byteLength = elementCount * bytesPerTexel;
  19482. const buffer = gl.createBuffer();
  19483. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  19484. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  19485. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  19486. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  19487. await backend.utils._clientWaitAsync();
  19488. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  19489. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  19490. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  19491. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  19492. gl.deleteFramebuffer( fb );
  19493. return dstBuffer;
  19494. }
  19495. _getTypedArrayType( glType ) {
  19496. const { gl } = this;
  19497. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  19498. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  19499. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  19500. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  19501. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  19502. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  19503. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  19504. if ( glType === gl.FLOAT ) return Float32Array;
  19505. throw new Error( `Unsupported WebGL type: ${glType}` );
  19506. }
  19507. _getBytesPerTexel( glType, glFormat ) {
  19508. const { gl } = this;
  19509. let bytesPerComponent = 0;
  19510. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  19511. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  19512. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  19513. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  19514. glType === gl.UNSIGNED_SHORT ||
  19515. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  19516. if ( glType === gl.UNSIGNED_INT ||
  19517. glType === gl.FLOAT ) bytesPerComponent = 4;
  19518. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  19519. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  19520. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  19521. }
  19522. }
  19523. class WebGLExtensions {
  19524. constructor( backend ) {
  19525. this.backend = backend;
  19526. this.gl = this.backend.gl;
  19527. this.availableExtensions = this.gl.getSupportedExtensions();
  19528. this.extensions = {};
  19529. }
  19530. get( name ) {
  19531. let extension = this.extensions[ name ];
  19532. if ( extension === undefined ) {
  19533. extension = this.gl.getExtension( name );
  19534. this.extensions[ name ] = extension;
  19535. }
  19536. return extension;
  19537. }
  19538. has( name ) {
  19539. return this.availableExtensions.includes( name );
  19540. }
  19541. }
  19542. class WebGLCapabilities {
  19543. constructor( backend ) {
  19544. this.backend = backend;
  19545. this.maxAnisotropy = null;
  19546. }
  19547. getMaxAnisotropy() {
  19548. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  19549. const gl = this.backend.gl;
  19550. const extensions = this.backend.extensions;
  19551. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  19552. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  19553. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  19554. } else {
  19555. this.maxAnisotropy = 0;
  19556. }
  19557. return this.maxAnisotropy;
  19558. }
  19559. }
  19560. const GLFeatureName = {
  19561. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  19562. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  19563. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  19564. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  19565. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  19566. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  19567. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  19568. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  19569. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  19570. };
  19571. class WebGLBufferRenderer {
  19572. constructor( backend ) {
  19573. this.gl = backend.gl;
  19574. this.extensions = backend.extensions;
  19575. this.info = backend.renderer.info;
  19576. this.mode = null;
  19577. this.index = 0;
  19578. this.type = null;
  19579. this.object = null;
  19580. }
  19581. render( start, count ) {
  19582. const { gl, mode, object, type, info, index } = this;
  19583. if ( index !== 0 ) {
  19584. gl.drawElements( mode, count, type, start );
  19585. } else {
  19586. gl.drawArrays( mode, start, count );
  19587. }
  19588. info.update( object, count, mode, 1 );
  19589. }
  19590. renderInstances( start, count, primcount ) {
  19591. const { gl, mode, type, index, object, info } = this;
  19592. if ( primcount === 0 ) return;
  19593. if ( index !== 0 ) {
  19594. gl.drawElementsInstanced( mode, count, type, start, primcount );
  19595. } else {
  19596. gl.drawArraysInstanced( mode, start, count, primcount );
  19597. }
  19598. info.update( object, count, mode, primcount );
  19599. }
  19600. renderMultiDraw( starts, counts, drawCount ) {
  19601. const { extensions, mode, object, info } = this;
  19602. if ( drawCount === 0 ) return;
  19603. const extension = extensions.get( 'WEBGL_multi_draw' );
  19604. if ( extension === null ) {
  19605. for ( let i = 0; i < drawCount; i ++ ) {
  19606. this.render( starts[ i ], counts[ i ] );
  19607. }
  19608. } else {
  19609. if ( this.index !== 0 ) {
  19610. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  19611. } else {
  19612. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  19613. }
  19614. let elementCount = 0;
  19615. for ( let i = 0; i < drawCount; i ++ ) {
  19616. elementCount += counts[ i ];
  19617. }
  19618. info.update( object, elementCount, mode, 1 );
  19619. }
  19620. }
  19621. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  19622. const { extensions, mode, object, info } = this;
  19623. if ( drawCount === 0 ) return;
  19624. const extension = extensions.get( 'WEBGL_multi_draw' );
  19625. if ( extension === null ) {
  19626. for ( let i = 0; i < drawCount; i ++ ) {
  19627. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  19628. }
  19629. } else {
  19630. if ( this.index !== 0 ) {
  19631. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  19632. } else {
  19633. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  19634. }
  19635. let elementCount = 0;
  19636. for ( let i = 0; i < drawCount; i ++ ) {
  19637. elementCount += counts[ i ] * primcount[ i ];
  19638. }
  19639. info.update( object, elementCount, mode, 1 );
  19640. }
  19641. }
  19642. //
  19643. }
  19644. //
  19645. class WebGLBackend extends Backend {
  19646. constructor( parameters = {} ) {
  19647. super( parameters );
  19648. this.isWebGLBackend = true;
  19649. }
  19650. init( renderer ) {
  19651. super.init( renderer );
  19652. //
  19653. const parameters = this.parameters;
  19654. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2' );
  19655. function onContextLost( event ) {
  19656. event.preventDefault();
  19657. const contextLossInfo = {
  19658. api: 'WebGL',
  19659. message: event.statusMessage || 'Unknown reason',
  19660. reason: null,
  19661. originalEvent: event
  19662. };
  19663. renderer.onDeviceLost( contextLossInfo );
  19664. }
  19665. this._onContextLost = onContextLost;
  19666. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  19667. this.gl = glContext;
  19668. this.extensions = new WebGLExtensions( this );
  19669. this.capabilities = new WebGLCapabilities( this );
  19670. this.attributeUtils = new WebGLAttributeUtils( this );
  19671. this.textureUtils = new WebGLTextureUtils( this );
  19672. this.bufferRenderer = new WebGLBufferRenderer( this );
  19673. this.state = new WebGLState( this );
  19674. this.utils = new WebGLUtils( this );
  19675. this.vaoCache = {};
  19676. this.transformFeedbackCache = {};
  19677. this.discard = false;
  19678. this.trackTimestamp = ( parameters.trackTimestamp === true );
  19679. this.extensions.get( 'EXT_color_buffer_float' );
  19680. this.extensions.get( 'WEBGL_clip_cull_distance' );
  19681. this.extensions.get( 'OES_texture_float_linear' );
  19682. this.extensions.get( 'EXT_color_buffer_half_float' );
  19683. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  19684. this.extensions.get( 'WEBGL_render_shared_exponent' );
  19685. this.extensions.get( 'WEBGL_multi_draw' );
  19686. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  19687. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  19688. this._knownBindings = new WeakSet();
  19689. this._currentContext = null;
  19690. }
  19691. get coordinateSystem() {
  19692. return WebGLCoordinateSystem;
  19693. }
  19694. async getArrayBufferAsync( attribute ) {
  19695. return await this.attributeUtils.getArrayBufferAsync( attribute );
  19696. }
  19697. async waitForGPU() {
  19698. await this.utils._clientWaitAsync();
  19699. }
  19700. initTimestampQuery( renderContext ) {
  19701. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  19702. const renderContextData = this.get( renderContext );
  19703. if ( this.queryRunning ) {
  19704. if ( ! renderContextData.queryQueue ) renderContextData.queryQueue = [];
  19705. renderContextData.queryQueue.push( renderContext );
  19706. return;
  19707. }
  19708. if ( renderContextData.activeQuery ) {
  19709. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  19710. renderContextData.activeQuery = null;
  19711. }
  19712. renderContextData.activeQuery = this.gl.createQuery();
  19713. if ( renderContextData.activeQuery !== null ) {
  19714. this.gl.beginQuery( this.disjoint.TIME_ELAPSED_EXT, renderContextData.activeQuery );
  19715. this.queryRunning = true;
  19716. }
  19717. }
  19718. // timestamp utils
  19719. prepareTimestampBuffer( renderContext ) {
  19720. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  19721. const renderContextData = this.get( renderContext );
  19722. if ( renderContextData.activeQuery ) {
  19723. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  19724. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  19725. renderContextData.gpuQueries.push( { query: renderContextData.activeQuery } );
  19726. renderContextData.activeQuery = null;
  19727. this.queryRunning = false;
  19728. if ( renderContextData.queryQueue && renderContextData.queryQueue.length > 0 ) {
  19729. const nextRenderContext = renderContextData.queryQueue.shift();
  19730. this.initTimestampQuery( nextRenderContext );
  19731. }
  19732. }
  19733. }
  19734. async resolveTimestampAsync( renderContext, type = 'render' ) {
  19735. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  19736. const renderContextData = this.get( renderContext );
  19737. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  19738. for ( let i = 0; i < renderContextData.gpuQueries.length; i ++ ) {
  19739. const queryInfo = renderContextData.gpuQueries[ i ];
  19740. const available = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT_AVAILABLE );
  19741. const disjoint = this.gl.getParameter( this.disjoint.GPU_DISJOINT_EXT );
  19742. if ( available && ! disjoint ) {
  19743. const elapsed = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT );
  19744. const duration = Number( elapsed ) / 1000000; // Convert nanoseconds to milliseconds
  19745. this.gl.deleteQuery( queryInfo.query );
  19746. renderContextData.gpuQueries.splice( i, 1 ); // Remove the processed query
  19747. i --;
  19748. this.renderer.info.updateTimestamp( type, duration );
  19749. }
  19750. }
  19751. }
  19752. getContext() {
  19753. return this.gl;
  19754. }
  19755. beginRender( renderContext ) {
  19756. const { gl } = this;
  19757. const renderContextData = this.get( renderContext );
  19758. //
  19759. //
  19760. this.initTimestampQuery( renderContext );
  19761. renderContextData.previousContext = this._currentContext;
  19762. this._currentContext = renderContext;
  19763. this._setFramebuffer( renderContext );
  19764. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  19765. //
  19766. if ( renderContext.viewport ) {
  19767. this.updateViewport( renderContext );
  19768. } else {
  19769. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  19770. }
  19771. if ( renderContext.scissor ) {
  19772. const { x, y, width, height } = renderContext.scissorValue;
  19773. gl.scissor( x, renderContext.height - height - y, width, height );
  19774. }
  19775. const occlusionQueryCount = renderContext.occlusionQueryCount;
  19776. if ( occlusionQueryCount > 0 ) {
  19777. // Get a reference to the array of objects with queries. The renderContextData property
  19778. // can be changed by another render pass before the async reading of all previous queries complete
  19779. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  19780. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  19781. renderContextData.lastOcclusionObject = null;
  19782. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  19783. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  19784. renderContextData.occlusionQueryIndex = 0;
  19785. }
  19786. }
  19787. finishRender( renderContext ) {
  19788. const { gl, state } = this;
  19789. const renderContextData = this.get( renderContext );
  19790. const previousContext = renderContextData.previousContext;
  19791. const occlusionQueryCount = renderContext.occlusionQueryCount;
  19792. if ( occlusionQueryCount > 0 ) {
  19793. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  19794. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  19795. }
  19796. this.resolveOccludedAsync( renderContext );
  19797. }
  19798. const textures = renderContext.textures;
  19799. if ( textures !== null ) {
  19800. for ( let i = 0; i < textures.length; i ++ ) {
  19801. const texture = textures[ i ];
  19802. if ( texture.generateMipmaps ) {
  19803. this.generateMipmaps( texture );
  19804. }
  19805. }
  19806. }
  19807. this._currentContext = previousContext;
  19808. if ( renderContext.textures !== null && renderContext.renderTarget ) {
  19809. const renderTargetContextData = this.get( renderContext.renderTarget );
  19810. const { samples } = renderContext.renderTarget;
  19811. if ( samples > 0 ) {
  19812. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  19813. const mask = gl.COLOR_BUFFER_BIT;
  19814. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  19815. const textures = renderContext.textures;
  19816. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  19817. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  19818. for ( let i = 0; i < textures.length; i ++ ) {
  19819. // TODO Add support for MRT
  19820. if ( renderContext.scissor ) {
  19821. const { x, y, width, height } = renderContext.scissorValue;
  19822. const viewY = renderContext.height - height - y;
  19823. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  19824. gl.invalidateSubFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray, x, viewY, width, height );
  19825. } else {
  19826. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  19827. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  19828. }
  19829. }
  19830. }
  19831. }
  19832. if ( previousContext !== null ) {
  19833. this._setFramebuffer( previousContext );
  19834. if ( previousContext.viewport ) {
  19835. this.updateViewport( previousContext );
  19836. } else {
  19837. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  19838. }
  19839. }
  19840. this.prepareTimestampBuffer( renderContext );
  19841. }
  19842. resolveOccludedAsync( renderContext ) {
  19843. const renderContextData = this.get( renderContext );
  19844. // handle occlusion query results
  19845. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  19846. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  19847. const occluded = new WeakSet();
  19848. const { gl } = this;
  19849. renderContextData.currentOcclusionQueryObjects = null;
  19850. renderContextData.currentOcclusionQueries = null;
  19851. const check = () => {
  19852. let completed = 0;
  19853. // check all queries and requeue as appropriate
  19854. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  19855. const query = currentOcclusionQueries[ i ];
  19856. if ( query === null ) continue;
  19857. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  19858. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) > 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  19859. currentOcclusionQueries[ i ] = null;
  19860. gl.deleteQuery( query );
  19861. completed ++;
  19862. }
  19863. }
  19864. if ( completed < currentOcclusionQueries.length ) {
  19865. requestAnimationFrame( check );
  19866. } else {
  19867. renderContextData.occluded = occluded;
  19868. }
  19869. };
  19870. check();
  19871. }
  19872. }
  19873. isOccluded( renderContext, object ) {
  19874. const renderContextData = this.get( renderContext );
  19875. return renderContextData.occluded && renderContextData.occluded.has( object );
  19876. }
  19877. updateViewport( renderContext ) {
  19878. const gl = this.gl;
  19879. const { x, y, width, height } = renderContext.viewportValue;
  19880. gl.viewport( x, renderContext.height - height - y, width, height );
  19881. }
  19882. setScissorTest( boolean ) {
  19883. const gl = this.gl;
  19884. if ( boolean ) {
  19885. gl.enable( gl.SCISSOR_TEST );
  19886. } else {
  19887. gl.disable( gl.SCISSOR_TEST );
  19888. }
  19889. }
  19890. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  19891. const { gl } = this;
  19892. if ( descriptor === null ) {
  19893. const clearColor = this.getClearColor();
  19894. // premultiply alpha
  19895. clearColor.r *= clearColor.a;
  19896. clearColor.g *= clearColor.a;
  19897. clearColor.b *= clearColor.a;
  19898. descriptor = {
  19899. textures: null,
  19900. clearColorValue: clearColor
  19901. };
  19902. }
  19903. //
  19904. let clear = 0;
  19905. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  19906. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  19907. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  19908. if ( clear !== 0 ) {
  19909. let clearColor;
  19910. if ( descriptor.clearColorValue ) {
  19911. clearColor = descriptor.clearColorValue;
  19912. } else {
  19913. clearColor = this.getClearColor();
  19914. // premultiply alpha
  19915. clearColor.r *= clearColor.a;
  19916. clearColor.g *= clearColor.a;
  19917. clearColor.b *= clearColor.a;
  19918. }
  19919. if ( depth ) this.state.setDepthMask( true );
  19920. if ( descriptor.textures === null ) {
  19921. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  19922. gl.clear( clear );
  19923. } else {
  19924. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  19925. if ( color ) {
  19926. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  19927. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  19928. }
  19929. }
  19930. if ( depth && stencil ) {
  19931. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, 1, 0 );
  19932. } else if ( depth ) {
  19933. gl.clearBufferfv( gl.DEPTH, 0, [ 1.0 ] );
  19934. } else if ( stencil ) {
  19935. gl.clearBufferiv( gl.STENCIL, 0, [ 0 ] );
  19936. }
  19937. }
  19938. }
  19939. }
  19940. beginCompute( computeGroup ) {
  19941. const { state, gl } = this;
  19942. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  19943. this.initTimestampQuery( computeGroup );
  19944. }
  19945. compute( computeGroup, computeNode, bindings, pipeline ) {
  19946. const { state, gl } = this;
  19947. if ( ! this.discard ) {
  19948. // required here to handle async behaviour of render.compute()
  19949. gl.enable( gl.RASTERIZER_DISCARD );
  19950. this.discard = true;
  19951. }
  19952. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  19953. const vaoKey = this._getVaoKey( null, attributes );
  19954. const vaoGPU = this.vaoCache[ vaoKey ];
  19955. if ( vaoGPU === undefined ) {
  19956. this._createVao( null, attributes );
  19957. } else {
  19958. gl.bindVertexArray( vaoGPU );
  19959. }
  19960. state.useProgram( programGPU );
  19961. this._bindUniforms( bindings );
  19962. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  19963. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  19964. gl.beginTransformFeedback( gl.POINTS );
  19965. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  19966. gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count );
  19967. } else {
  19968. gl.drawArrays( gl.POINTS, 0, computeNode.count );
  19969. }
  19970. gl.endTransformFeedback();
  19971. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  19972. // switch active buffers
  19973. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  19974. const dualAttributeData = transformBuffers[ i ];
  19975. if ( dualAttributeData.pbo ) {
  19976. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  19977. }
  19978. dualAttributeData.switchBuffers();
  19979. }
  19980. }
  19981. finishCompute( computeGroup ) {
  19982. const gl = this.gl;
  19983. this.discard = false;
  19984. gl.disable( gl.RASTERIZER_DISCARD );
  19985. this.prepareTimestampBuffer( computeGroup );
  19986. if ( this._currentContext ) {
  19987. this._setFramebuffer( this._currentContext );
  19988. }
  19989. }
  19990. draw( renderObject/*, info*/ ) {
  19991. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  19992. const { programGPU } = this.get( pipeline );
  19993. const { gl, state } = this;
  19994. const contextData = this.get( context );
  19995. const drawParams = renderObject.getDrawParameters();
  19996. if ( drawParams === null ) return;
  19997. //
  19998. this._bindUniforms( renderObject.getBindings() );
  19999. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  20000. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  20001. state.useProgram( programGPU );
  20002. //
  20003. const renderObjectData = this.get( renderObject );
  20004. let vaoGPU = renderObjectData.staticVao;
  20005. if ( vaoGPU === undefined || renderObjectData.geometryId !== renderObject.geometry.id ) {
  20006. const vaoKey = this._getVaoKey( renderObject.getIndex(), renderObject.getAttributes() );
  20007. vaoGPU = this.vaoCache[ vaoKey ];
  20008. if ( vaoGPU === undefined ) {
  20009. let staticVao;
  20010. ( { vaoGPU, staticVao } = this._createVao( renderObject.getIndex(), renderObject.getAttributes() ) );
  20011. if ( staticVao ) {
  20012. renderObjectData.staticVao = vaoGPU;
  20013. renderObjectData.geometryId = renderObject.geometry.id;
  20014. }
  20015. }
  20016. }
  20017. gl.bindVertexArray( vaoGPU );
  20018. //
  20019. const index = renderObject.getIndex();
  20020. //
  20021. const lastObject = contextData.lastOcclusionObject;
  20022. if ( lastObject !== object && lastObject !== undefined ) {
  20023. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  20024. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  20025. contextData.occlusionQueryIndex ++;
  20026. }
  20027. if ( object.occlusionTest === true ) {
  20028. const query = gl.createQuery();
  20029. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  20030. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  20031. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  20032. }
  20033. contextData.lastOcclusionObject = object;
  20034. }
  20035. //
  20036. const renderer = this.bufferRenderer;
  20037. if ( object.isPoints ) renderer.mode = gl.POINTS;
  20038. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  20039. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  20040. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  20041. else {
  20042. if ( material.wireframe === true ) {
  20043. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  20044. renderer.mode = gl.LINES;
  20045. } else {
  20046. renderer.mode = gl.TRIANGLES;
  20047. }
  20048. }
  20049. //
  20050. const { vertexCount, instanceCount } = drawParams;
  20051. let { firstVertex } = drawParams;
  20052. renderer.object = object;
  20053. if ( index !== null ) {
  20054. firstVertex *= index.array.BYTES_PER_ELEMENT;
  20055. const indexData = this.get( index );
  20056. renderer.index = index.count;
  20057. renderer.type = indexData.type;
  20058. } else {
  20059. renderer.index = 0;
  20060. }
  20061. if ( object.isBatchedMesh ) {
  20062. if ( object._multiDrawInstances !== null ) {
  20063. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  20064. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  20065. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  20066. } else {
  20067. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  20068. }
  20069. } else if ( instanceCount > 1 ) {
  20070. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  20071. } else {
  20072. renderer.render( firstVertex, vertexCount );
  20073. }
  20074. //
  20075. gl.bindVertexArray( null );
  20076. }
  20077. needsRenderUpdate( /*renderObject*/ ) {
  20078. return false;
  20079. }
  20080. getRenderCacheKey( /*renderObject*/ ) {
  20081. return '';
  20082. }
  20083. // textures
  20084. createDefaultTexture( texture ) {
  20085. this.textureUtils.createDefaultTexture( texture );
  20086. }
  20087. createTexture( texture, options ) {
  20088. this.textureUtils.createTexture( texture, options );
  20089. }
  20090. updateTexture( texture, options ) {
  20091. this.textureUtils.updateTexture( texture, options );
  20092. }
  20093. generateMipmaps( texture ) {
  20094. this.textureUtils.generateMipmaps( texture );
  20095. }
  20096. destroyTexture( texture ) {
  20097. this.textureUtils.destroyTexture( texture );
  20098. }
  20099. copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  20100. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  20101. }
  20102. createSampler( /*texture*/ ) {
  20103. //console.warn( 'Abstract class.' );
  20104. }
  20105. destroySampler() {}
  20106. // node builder
  20107. createNodeBuilder( object, renderer ) {
  20108. return new GLSLNodeBuilder( object, renderer );
  20109. }
  20110. // program
  20111. createProgram( program ) {
  20112. const gl = this.gl;
  20113. const { stage, code } = program;
  20114. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  20115. gl.shaderSource( shader, code );
  20116. gl.compileShader( shader );
  20117. this.set( program, {
  20118. shaderGPU: shader
  20119. } );
  20120. }
  20121. destroyProgram( /*program*/ ) {
  20122. console.warn( 'Abstract class.' );
  20123. }
  20124. createRenderPipeline( renderObject, promises ) {
  20125. const gl = this.gl;
  20126. const pipeline = renderObject.pipeline;
  20127. // Program
  20128. const { fragmentProgram, vertexProgram } = pipeline;
  20129. const programGPU = gl.createProgram();
  20130. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  20131. const vertexShader = this.get( vertexProgram ).shaderGPU;
  20132. gl.attachShader( programGPU, fragmentShader );
  20133. gl.attachShader( programGPU, vertexShader );
  20134. gl.linkProgram( programGPU );
  20135. this.set( pipeline, {
  20136. programGPU,
  20137. fragmentShader,
  20138. vertexShader
  20139. } );
  20140. if ( promises !== null && this.parallel ) {
  20141. const p = new Promise( ( resolve /*, reject*/ ) => {
  20142. const parallel = this.parallel;
  20143. const checkStatus = () => {
  20144. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  20145. this._completeCompile( renderObject, pipeline );
  20146. resolve();
  20147. } else {
  20148. requestAnimationFrame( checkStatus );
  20149. }
  20150. };
  20151. checkStatus();
  20152. } );
  20153. promises.push( p );
  20154. return;
  20155. }
  20156. this._completeCompile( renderObject, pipeline );
  20157. }
  20158. _handleSource( string, errorLine ) {
  20159. const lines = string.split( '\n' );
  20160. const lines2 = [];
  20161. const from = Math.max( errorLine - 6, 0 );
  20162. const to = Math.min( errorLine + 6, lines.length );
  20163. for ( let i = from; i < to; i ++ ) {
  20164. const line = i + 1;
  20165. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  20166. }
  20167. return lines2.join( '\n' );
  20168. }
  20169. _getShaderErrors( gl, shader, type ) {
  20170. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  20171. const errors = gl.getShaderInfoLog( shader ).trim();
  20172. if ( status && errors === '' ) return '';
  20173. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  20174. if ( errorMatches ) {
  20175. const errorLine = parseInt( errorMatches[ 1 ] );
  20176. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  20177. } else {
  20178. return errors;
  20179. }
  20180. }
  20181. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  20182. if ( this.renderer.debug.checkShaderErrors ) {
  20183. const gl = this.gl;
  20184. const programLog = gl.getProgramInfoLog( programGPU ).trim();
  20185. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  20186. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  20187. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  20188. } else {
  20189. // default error reporting
  20190. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  20191. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  20192. console.error(
  20193. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  20194. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  20195. 'Program Info Log: ' + programLog + '\n' +
  20196. vertexErrors + '\n' +
  20197. fragmentErrors
  20198. );
  20199. }
  20200. } else if ( programLog !== '' ) {
  20201. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  20202. }
  20203. }
  20204. }
  20205. _completeCompile( renderObject, pipeline ) {
  20206. const { state, gl } = this;
  20207. const pipelineData = this.get( pipeline );
  20208. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  20209. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  20210. this._logProgramError( programGPU, fragmentShader, vertexShader );
  20211. }
  20212. state.useProgram( programGPU );
  20213. // Bindings
  20214. const bindings = renderObject.getBindings();
  20215. this._setupBindings( bindings, programGPU );
  20216. //
  20217. this.set( pipeline, {
  20218. programGPU
  20219. } );
  20220. }
  20221. createComputePipeline( computePipeline, bindings ) {
  20222. const { state, gl } = this;
  20223. // Program
  20224. const fragmentProgram = {
  20225. stage: 'fragment',
  20226. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  20227. };
  20228. this.createProgram( fragmentProgram );
  20229. const { computeProgram } = computePipeline;
  20230. const programGPU = gl.createProgram();
  20231. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  20232. const vertexShader = this.get( computeProgram ).shaderGPU;
  20233. const transforms = computeProgram.transforms;
  20234. const transformVaryingNames = [];
  20235. const transformAttributeNodes = [];
  20236. for ( let i = 0; i < transforms.length; i ++ ) {
  20237. const transform = transforms[ i ];
  20238. transformVaryingNames.push( transform.varyingName );
  20239. transformAttributeNodes.push( transform.attributeNode );
  20240. }
  20241. gl.attachShader( programGPU, fragmentShader );
  20242. gl.attachShader( programGPU, vertexShader );
  20243. gl.transformFeedbackVaryings(
  20244. programGPU,
  20245. transformVaryingNames,
  20246. gl.SEPARATE_ATTRIBS
  20247. );
  20248. gl.linkProgram( programGPU );
  20249. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  20250. this._logProgramError( programGPU, fragmentShader, vertexShader );
  20251. }
  20252. state.useProgram( programGPU );
  20253. // Bindings
  20254. this._setupBindings( bindings, programGPU );
  20255. const attributeNodes = computeProgram.attributes;
  20256. const attributes = [];
  20257. const transformBuffers = [];
  20258. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  20259. const attribute = attributeNodes[ i ].node.attribute;
  20260. attributes.push( attribute );
  20261. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  20262. }
  20263. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  20264. const attribute = transformAttributeNodes[ i ].attribute;
  20265. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  20266. const attributeData = this.get( attribute );
  20267. transformBuffers.push( attributeData );
  20268. }
  20269. //
  20270. this.set( computePipeline, {
  20271. programGPU,
  20272. transformBuffers,
  20273. attributes
  20274. } );
  20275. }
  20276. createBindings( bindGroup, bindings ) {
  20277. if ( this._knownBindings.has( bindings ) === false ) {
  20278. this._knownBindings.add( bindings );
  20279. let uniformBuffers = 0;
  20280. let textures = 0;
  20281. for ( const bindGroup of bindings ) {
  20282. this.set( bindGroup, {
  20283. textures: textures,
  20284. uniformBuffers: uniformBuffers
  20285. } );
  20286. for ( const binding of bindGroup.bindings ) {
  20287. if ( binding.isUniformBuffer ) uniformBuffers ++;
  20288. if ( binding.isSampledTexture ) textures ++;
  20289. }
  20290. }
  20291. }
  20292. this.updateBindings( bindGroup, bindings );
  20293. }
  20294. updateBindings( bindGroup /*, bindings*/ ) {
  20295. const { gl } = this;
  20296. const bindGroupData = this.get( bindGroup );
  20297. let i = bindGroupData.uniformBuffers;
  20298. let t = bindGroupData.textures;
  20299. for ( const binding of bindGroup.bindings ) {
  20300. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  20301. const data = binding.buffer;
  20302. const bufferGPU = gl.createBuffer();
  20303. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  20304. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  20305. this.set( binding, {
  20306. index: i ++,
  20307. bufferGPU
  20308. } );
  20309. } else if ( binding.isSampledTexture ) {
  20310. const { textureGPU, glTextureType } = this.get( binding.texture );
  20311. this.set( binding, {
  20312. index: t ++,
  20313. textureGPU,
  20314. glTextureType
  20315. } );
  20316. }
  20317. }
  20318. }
  20319. updateBinding( binding ) {
  20320. const gl = this.gl;
  20321. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  20322. const bindingData = this.get( binding );
  20323. const bufferGPU = bindingData.bufferGPU;
  20324. const data = binding.buffer;
  20325. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  20326. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  20327. }
  20328. }
  20329. // attributes
  20330. createIndexAttribute( attribute ) {
  20331. const gl = this.gl;
  20332. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  20333. }
  20334. createAttribute( attribute ) {
  20335. if ( this.has( attribute ) ) return;
  20336. const gl = this.gl;
  20337. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  20338. }
  20339. createStorageAttribute( attribute ) {
  20340. if ( this.has( attribute ) ) return;
  20341. const gl = this.gl;
  20342. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  20343. }
  20344. updateAttribute( attribute ) {
  20345. this.attributeUtils.updateAttribute( attribute );
  20346. }
  20347. destroyAttribute( attribute ) {
  20348. this.attributeUtils.destroyAttribute( attribute );
  20349. }
  20350. updateSize() {
  20351. //console.warn( 'Abstract class.' );
  20352. }
  20353. hasFeature( name ) {
  20354. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  20355. const extensions = this.extensions;
  20356. for ( let i = 0; i < keysMatching.length; i ++ ) {
  20357. if ( extensions.has( keysMatching[ i ] ) ) return true;
  20358. }
  20359. return false;
  20360. }
  20361. getMaxAnisotropy() {
  20362. return this.capabilities.getMaxAnisotropy();
  20363. }
  20364. copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level ) {
  20365. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  20366. }
  20367. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  20368. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  20369. }
  20370. _setFramebuffer( descriptor ) {
  20371. const { gl, state } = this;
  20372. let currentFrameBuffer = null;
  20373. if ( descriptor.textures !== null ) {
  20374. const renderTarget = descriptor.renderTarget;
  20375. const renderTargetContextData = this.get( renderTarget );
  20376. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  20377. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  20378. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  20379. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  20380. const cacheKey = getCacheKey( descriptor );
  20381. let fb;
  20382. if ( isCube ) {
  20383. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  20384. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  20385. } else {
  20386. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  20387. fb = renderTargetContextData.framebuffers[ cacheKey ];
  20388. }
  20389. if ( fb === undefined ) {
  20390. fb = gl.createFramebuffer();
  20391. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  20392. const textures = descriptor.textures;
  20393. if ( isCube ) {
  20394. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  20395. const { textureGPU } = this.get( textures[ 0 ] );
  20396. const cubeFace = this.renderer._activeCubeFace;
  20397. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  20398. } else {
  20399. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  20400. for ( let i = 0; i < textures.length; i ++ ) {
  20401. const texture = textures[ i ];
  20402. const textureData = this.get( texture );
  20403. textureData.renderTarget = descriptor.renderTarget;
  20404. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  20405. const attachment = gl.COLOR_ATTACHMENT0 + i;
  20406. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  20407. }
  20408. state.drawBuffers( descriptor, fb );
  20409. }
  20410. if ( descriptor.depthTexture !== null ) {
  20411. const textureData = this.get( descriptor.depthTexture );
  20412. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  20413. textureData.renderTarget = descriptor.renderTarget;
  20414. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  20415. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  20416. }
  20417. }
  20418. if ( samples > 0 ) {
  20419. if ( msaaFb === undefined ) {
  20420. const invalidationArray = [];
  20421. msaaFb = gl.createFramebuffer();
  20422. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  20423. const msaaRenderbuffers = [];
  20424. const textures = descriptor.textures;
  20425. for ( let i = 0; i < textures.length; i ++ ) {
  20426. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  20427. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  20428. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  20429. if ( depthBuffer ) {
  20430. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  20431. invalidationArray.push( depthStyle );
  20432. }
  20433. const texture = descriptor.textures[ i ];
  20434. const textureData = this.get( texture );
  20435. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  20436. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  20437. }
  20438. renderTargetContextData.msaaFrameBuffer = msaaFb;
  20439. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  20440. if ( depthRenderbuffer === undefined ) {
  20441. depthRenderbuffer = gl.createRenderbuffer();
  20442. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor );
  20443. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  20444. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  20445. invalidationArray.push( depthStyle );
  20446. }
  20447. renderTargetContextData.invalidationArray = invalidationArray;
  20448. }
  20449. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  20450. } else {
  20451. currentFrameBuffer = fb;
  20452. }
  20453. }
  20454. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  20455. }
  20456. _getVaoKey( index, attributes ) {
  20457. let key = [];
  20458. if ( index !== null ) {
  20459. const indexData = this.get( index );
  20460. key += ':' + indexData.id;
  20461. }
  20462. for ( let i = 0; i < attributes.length; i ++ ) {
  20463. const attributeData = this.get( attributes[ i ] );
  20464. key += ':' + attributeData.id;
  20465. }
  20466. return key;
  20467. }
  20468. _createVao( index, attributes ) {
  20469. const { gl } = this;
  20470. const vaoGPU = gl.createVertexArray();
  20471. let key = '';
  20472. let staticVao = true;
  20473. gl.bindVertexArray( vaoGPU );
  20474. if ( index !== null ) {
  20475. const indexData = this.get( index );
  20476. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexData.bufferGPU );
  20477. key += ':' + indexData.id;
  20478. }
  20479. for ( let i = 0; i < attributes.length; i ++ ) {
  20480. const attribute = attributes[ i ];
  20481. const attributeData = this.get( attribute );
  20482. key += ':' + attributeData.id;
  20483. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  20484. gl.enableVertexAttribArray( i );
  20485. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false;
  20486. let stride, offset;
  20487. if ( attribute.isInterleavedBufferAttribute === true ) {
  20488. stride = attribute.data.stride * attributeData.bytesPerElement;
  20489. offset = attribute.offset * attributeData.bytesPerElement;
  20490. } else {
  20491. stride = 0;
  20492. offset = 0;
  20493. }
  20494. if ( attributeData.isInteger ) {
  20495. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  20496. } else {
  20497. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  20498. }
  20499. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  20500. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  20501. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  20502. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  20503. }
  20504. }
  20505. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  20506. this.vaoCache[ key ] = vaoGPU;
  20507. return { vaoGPU, staticVao };
  20508. }
  20509. _getTransformFeedback( transformBuffers ) {
  20510. let key = '';
  20511. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  20512. key += ':' + transformBuffers[ i ].id;
  20513. }
  20514. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  20515. if ( transformFeedbackGPU !== undefined ) {
  20516. return transformFeedbackGPU;
  20517. }
  20518. const { gl } = this;
  20519. transformFeedbackGPU = gl.createTransformFeedback();
  20520. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  20521. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  20522. const attributeData = transformBuffers[ i ];
  20523. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  20524. }
  20525. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  20526. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  20527. return transformFeedbackGPU;
  20528. }
  20529. _setupBindings( bindings, programGPU ) {
  20530. const gl = this.gl;
  20531. for ( const bindGroup of bindings ) {
  20532. for ( const binding of bindGroup.bindings ) {
  20533. const bindingData = this.get( binding );
  20534. const index = bindingData.index;
  20535. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  20536. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  20537. gl.uniformBlockBinding( programGPU, location, index );
  20538. } else if ( binding.isSampledTexture ) {
  20539. const location = gl.getUniformLocation( programGPU, binding.name );
  20540. gl.uniform1i( location, index );
  20541. }
  20542. }
  20543. }
  20544. }
  20545. _bindUniforms( bindings ) {
  20546. const { gl, state } = this;
  20547. for ( const bindGroup of bindings ) {
  20548. for ( const binding of bindGroup.bindings ) {
  20549. const bindingData = this.get( binding );
  20550. const index = bindingData.index;
  20551. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  20552. // TODO USE bindBufferRange to group multiple uniform buffers
  20553. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  20554. } else if ( binding.isSampledTexture ) {
  20555. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  20556. }
  20557. }
  20558. }
  20559. }
  20560. dispose() {
  20561. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  20562. }
  20563. }
  20564. class Sampler extends Binding {
  20565. constructor( name, texture ) {
  20566. super( name );
  20567. this.texture = texture;
  20568. this.version = texture ? texture.version : 0;
  20569. this.isSampler = true;
  20570. }
  20571. }
  20572. class NodeSampler extends Sampler {
  20573. constructor( name, textureNode, groupNode ) {
  20574. super( name, textureNode ? textureNode.value : null );
  20575. this.textureNode = textureNode;
  20576. this.groupNode = groupNode;
  20577. }
  20578. update() {
  20579. this.texture = this.textureNode.value;
  20580. }
  20581. }
  20582. class StorageBuffer extends Buffer {
  20583. constructor( name, attribute ) {
  20584. super( name, attribute ? attribute.array : null );
  20585. this.attribute = attribute;
  20586. this.isStorageBuffer = true;
  20587. }
  20588. }
  20589. let _id = 0;
  20590. class NodeStorageBuffer extends StorageBuffer {
  20591. constructor( nodeUniform, groupNode ) {
  20592. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  20593. this.nodeUniform = nodeUniform;
  20594. this.access = nodeUniform ? nodeUniform.access : GPUBufferBindingType.Storage;
  20595. this.groupNode = groupNode;
  20596. }
  20597. get buffer() {
  20598. return this.nodeUniform.value;
  20599. }
  20600. }
  20601. class WebGPUTexturePassUtils extends DataMap {
  20602. constructor( device ) {
  20603. super();
  20604. this.device = device;
  20605. const mipmapVertexSource = `
  20606. struct VarysStruct {
  20607. @builtin( position ) Position: vec4<f32>,
  20608. @location( 0 ) vTex : vec2<f32>
  20609. };
  20610. @vertex
  20611. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  20612. var Varys : VarysStruct;
  20613. var pos = array< vec2<f32>, 4 >(
  20614. vec2<f32>( -1.0, 1.0 ),
  20615. vec2<f32>( 1.0, 1.0 ),
  20616. vec2<f32>( -1.0, -1.0 ),
  20617. vec2<f32>( 1.0, -1.0 )
  20618. );
  20619. var tex = array< vec2<f32>, 4 >(
  20620. vec2<f32>( 0.0, 0.0 ),
  20621. vec2<f32>( 1.0, 0.0 ),
  20622. vec2<f32>( 0.0, 1.0 ),
  20623. vec2<f32>( 1.0, 1.0 )
  20624. );
  20625. Varys.vTex = tex[ vertexIndex ];
  20626. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  20627. return Varys;
  20628. }
  20629. `;
  20630. const mipmapFragmentSource = `
  20631. @group( 0 ) @binding( 0 )
  20632. var imgSampler : sampler;
  20633. @group( 0 ) @binding( 1 )
  20634. var img : texture_2d<f32>;
  20635. @fragment
  20636. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  20637. return textureSample( img, imgSampler, vTex );
  20638. }
  20639. `;
  20640. const flipYFragmentSource = `
  20641. @group( 0 ) @binding( 0 )
  20642. var imgSampler : sampler;
  20643. @group( 0 ) @binding( 1 )
  20644. var img : texture_2d<f32>;
  20645. @fragment
  20646. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  20647. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  20648. }
  20649. `;
  20650. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  20651. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  20652. // We'll need a new pipeline for every texture format used.
  20653. this.transferPipelines = {};
  20654. this.flipYPipelines = {};
  20655. this.mipmapVertexShaderModule = device.createShaderModule( {
  20656. label: 'mipmapVertex',
  20657. code: mipmapVertexSource
  20658. } );
  20659. this.mipmapFragmentShaderModule = device.createShaderModule( {
  20660. label: 'mipmapFragment',
  20661. code: mipmapFragmentSource
  20662. } );
  20663. this.flipYFragmentShaderModule = device.createShaderModule( {
  20664. label: 'flipYFragment',
  20665. code: flipYFragmentSource
  20666. } );
  20667. }
  20668. getTransferPipeline( format ) {
  20669. let pipeline = this.transferPipelines[ format ];
  20670. if ( pipeline === undefined ) {
  20671. pipeline = this.device.createRenderPipeline( {
  20672. label: `mipmap-${ format }`,
  20673. vertex: {
  20674. module: this.mipmapVertexShaderModule,
  20675. entryPoint: 'main'
  20676. },
  20677. fragment: {
  20678. module: this.mipmapFragmentShaderModule,
  20679. entryPoint: 'main',
  20680. targets: [ { format } ]
  20681. },
  20682. primitive: {
  20683. topology: GPUPrimitiveTopology.TriangleStrip,
  20684. stripIndexFormat: GPUIndexFormat.Uint32
  20685. },
  20686. layout: 'auto'
  20687. } );
  20688. this.transferPipelines[ format ] = pipeline;
  20689. }
  20690. return pipeline;
  20691. }
  20692. getFlipYPipeline( format ) {
  20693. let pipeline = this.flipYPipelines[ format ];
  20694. if ( pipeline === undefined ) {
  20695. pipeline = this.device.createRenderPipeline( {
  20696. label: `flipY-${ format }`,
  20697. vertex: {
  20698. module: this.mipmapVertexShaderModule,
  20699. entryPoint: 'main'
  20700. },
  20701. fragment: {
  20702. module: this.flipYFragmentShaderModule,
  20703. entryPoint: 'main',
  20704. targets: [ { format } ]
  20705. },
  20706. primitive: {
  20707. topology: GPUPrimitiveTopology.TriangleStrip,
  20708. stripIndexFormat: GPUIndexFormat.Uint32
  20709. },
  20710. layout: 'auto'
  20711. } );
  20712. this.flipYPipelines[ format ] = pipeline;
  20713. }
  20714. return pipeline;
  20715. }
  20716. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  20717. const format = textureGPUDescriptor.format;
  20718. const { width, height } = textureGPUDescriptor.size;
  20719. const transferPipeline = this.getTransferPipeline( format );
  20720. const flipYPipeline = this.getFlipYPipeline( format );
  20721. const tempTexture = this.device.createTexture( {
  20722. size: { width, height, depthOrArrayLayers: 1 },
  20723. format,
  20724. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  20725. } );
  20726. const srcView = textureGPU.createView( {
  20727. baseMipLevel: 0,
  20728. mipLevelCount: 1,
  20729. dimension: GPUTextureViewDimension.TwoD,
  20730. baseArrayLayer
  20731. } );
  20732. const dstView = tempTexture.createView( {
  20733. baseMipLevel: 0,
  20734. mipLevelCount: 1,
  20735. dimension: GPUTextureViewDimension.TwoD,
  20736. baseArrayLayer: 0
  20737. } );
  20738. const commandEncoder = this.device.createCommandEncoder( {} );
  20739. const pass = ( pipeline, sourceView, destinationView ) => {
  20740. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  20741. const bindGroup = this.device.createBindGroup( {
  20742. layout: bindGroupLayout,
  20743. entries: [ {
  20744. binding: 0,
  20745. resource: this.flipYSampler
  20746. }, {
  20747. binding: 1,
  20748. resource: sourceView
  20749. } ]
  20750. } );
  20751. const passEncoder = commandEncoder.beginRenderPass( {
  20752. colorAttachments: [ {
  20753. view: destinationView,
  20754. loadOp: GPULoadOp.Clear,
  20755. storeOp: GPUStoreOp.Store,
  20756. clearValue: [ 0, 0, 0, 0 ]
  20757. } ]
  20758. } );
  20759. passEncoder.setPipeline( pipeline );
  20760. passEncoder.setBindGroup( 0, bindGroup );
  20761. passEncoder.draw( 4, 1, 0, 0 );
  20762. passEncoder.end();
  20763. };
  20764. pass( transferPipeline, srcView, dstView );
  20765. pass( flipYPipeline, dstView, srcView );
  20766. this.device.queue.submit( [ commandEncoder.finish() ] );
  20767. tempTexture.destroy();
  20768. }
  20769. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  20770. const textureData = this.get( textureGPU );
  20771. if ( textureData.useCount === undefined ) {
  20772. textureData.useCount = 0;
  20773. textureData.layers = [];
  20774. }
  20775. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  20776. const commandEncoder = this.device.createCommandEncoder( {} );
  20777. this._mipmapRunBundles( commandEncoder, passes );
  20778. this.device.queue.submit( [ commandEncoder.finish() ] );
  20779. if ( textureData.useCount !== 0 ) textureData.layers[ baseArrayLayer ] = passes;
  20780. textureData.useCount ++;
  20781. }
  20782. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  20783. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  20784. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  20785. let srcView = textureGPU.createView( {
  20786. baseMipLevel: 0,
  20787. mipLevelCount: 1,
  20788. dimension: GPUTextureViewDimension.TwoD,
  20789. baseArrayLayer
  20790. } );
  20791. const passes = [];
  20792. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  20793. const bindGroup = this.device.createBindGroup( {
  20794. layout: bindGroupLayout,
  20795. entries: [ {
  20796. binding: 0,
  20797. resource: this.mipmapSampler
  20798. }, {
  20799. binding: 1,
  20800. resource: srcView
  20801. } ]
  20802. } );
  20803. const dstView = textureGPU.createView( {
  20804. baseMipLevel: i,
  20805. mipLevelCount: 1,
  20806. dimension: GPUTextureViewDimension.TwoD,
  20807. baseArrayLayer
  20808. } );
  20809. const passDescriptor = {
  20810. colorAttachments: [ {
  20811. view: dstView,
  20812. loadOp: GPULoadOp.Clear,
  20813. storeOp: GPUStoreOp.Store,
  20814. clearValue: [ 0, 0, 0, 0 ]
  20815. } ]
  20816. };
  20817. const passEncoder = this.device.createRenderBundleEncoder( {
  20818. colorFormats: [ textureGPUDescriptor.format ]
  20819. } );
  20820. passEncoder.setPipeline( pipeline );
  20821. passEncoder.setBindGroup( 0, bindGroup );
  20822. passEncoder.draw( 4, 1, 0, 0 );
  20823. passes.push( {
  20824. renderBundles: [ passEncoder.finish() ],
  20825. passDescriptor
  20826. } );
  20827. srcView = dstView;
  20828. }
  20829. return passes;
  20830. }
  20831. _mipmapRunBundles( commandEncoder, passes ) {
  20832. const levels = passes.length;
  20833. for ( let i = 0; i < levels; i ++ ) {
  20834. const pass = passes[ i ];
  20835. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  20836. passEncoder.executeBundles( pass.renderBundles );
  20837. passEncoder.end();
  20838. }
  20839. }
  20840. }
  20841. const _compareToWebGPU = {
  20842. [ NeverCompare ]: 'never',
  20843. [ LessCompare ]: 'less',
  20844. [ EqualCompare ]: 'equal',
  20845. [ LessEqualCompare ]: 'less-equal',
  20846. [ GreaterCompare ]: 'greater',
  20847. [ GreaterEqualCompare ]: 'greater-equal',
  20848. [ AlwaysCompare ]: 'always',
  20849. [ NotEqualCompare ]: 'not-equal'
  20850. };
  20851. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  20852. class WebGPUTextureUtils {
  20853. constructor( backend ) {
  20854. this.backend = backend;
  20855. this._passUtils = null;
  20856. this.defaultTexture = {};
  20857. this.defaultCubeTexture = {};
  20858. this.defaultVideoFrame = null;
  20859. this.colorBuffer = null;
  20860. this.depthTexture = new DepthTexture();
  20861. this.depthTexture.name = 'depthBuffer';
  20862. }
  20863. createSampler( texture ) {
  20864. const backend = this.backend;
  20865. const device = backend.device;
  20866. const textureGPU = backend.get( texture );
  20867. const samplerDescriptorGPU = {
  20868. addressModeU: this._convertAddressMode( texture.wrapS ),
  20869. addressModeV: this._convertAddressMode( texture.wrapT ),
  20870. addressModeW: this._convertAddressMode( texture.wrapR ),
  20871. magFilter: this._convertFilterMode( texture.magFilter ),
  20872. minFilter: this._convertFilterMode( texture.minFilter ),
  20873. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  20874. maxAnisotropy: 1
  20875. };
  20876. // anisotropy can only be used when all filter modes are set to linear.
  20877. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  20878. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  20879. }
  20880. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  20881. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  20882. }
  20883. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  20884. }
  20885. createDefaultTexture( texture ) {
  20886. let textureGPU;
  20887. const format = getFormat( texture );
  20888. if ( texture.isCubeTexture ) {
  20889. textureGPU = this._getDefaultCubeTextureGPU( format );
  20890. } else if ( texture.isVideoTexture ) {
  20891. this.backend.get( texture ).externalTexture = this._getDefaultVideoFrame();
  20892. } else {
  20893. textureGPU = this._getDefaultTextureGPU( format );
  20894. }
  20895. this.backend.get( texture ).texture = textureGPU;
  20896. }
  20897. createTexture( texture, options = {} ) {
  20898. const backend = this.backend;
  20899. const textureData = backend.get( texture );
  20900. if ( textureData.initialized ) {
  20901. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  20902. }
  20903. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  20904. if ( options.levels === undefined ) options.levels = 1;
  20905. if ( options.depth === undefined ) options.depth = 1;
  20906. const { width, height, depth, levels } = options;
  20907. if ( texture.isFramebufferTexture ) {
  20908. if ( options.renderTarget ) {
  20909. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  20910. } else {
  20911. options.format = this.backend.utils.getPreferredCanvasFormat();
  20912. }
  20913. }
  20914. const dimension = this._getDimension( texture );
  20915. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  20916. textureData.format = format;
  20917. let sampleCount = options.sampleCount !== undefined ? options.sampleCount : 1;
  20918. sampleCount = backend.utils.getSampleCount( sampleCount );
  20919. const primarySampleCount = texture.isRenderTargetTexture && ! texture.isMultisampleRenderTargetTexture ? 1 : sampleCount;
  20920. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  20921. if ( texture.isStorageTexture === true ) {
  20922. usage |= GPUTextureUsage.STORAGE_BINDING;
  20923. }
  20924. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true ) {
  20925. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  20926. }
  20927. const textureDescriptorGPU = {
  20928. label: texture.name,
  20929. size: {
  20930. width: width,
  20931. height: height,
  20932. depthOrArrayLayers: depth,
  20933. },
  20934. mipLevelCount: levels,
  20935. sampleCount: primarySampleCount,
  20936. dimension: dimension,
  20937. format: format,
  20938. usage: usage
  20939. };
  20940. // texture creation
  20941. if ( texture.isVideoTexture ) {
  20942. const video = texture.source.data;
  20943. const videoFrame = new VideoFrame( video );
  20944. textureDescriptorGPU.size.width = videoFrame.displayWidth;
  20945. textureDescriptorGPU.size.height = videoFrame.displayHeight;
  20946. videoFrame.close();
  20947. textureData.externalTexture = video;
  20948. } else {
  20949. if ( format === undefined ) {
  20950. console.warn( 'WebGPURenderer: Texture format not supported.' );
  20951. return this.createDefaultTexture( texture );
  20952. }
  20953. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  20954. }
  20955. if ( texture.isRenderTargetTexture && sampleCount > 1 && ! texture.isMultisampleRenderTargetTexture ) {
  20956. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  20957. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  20958. msaaTextureDescriptorGPU.sampleCount = sampleCount;
  20959. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  20960. }
  20961. textureData.initialized = true;
  20962. textureData.textureDescriptorGPU = textureDescriptorGPU;
  20963. }
  20964. destroyTexture( texture ) {
  20965. const backend = this.backend;
  20966. const textureData = backend.get( texture );
  20967. textureData.texture.destroy();
  20968. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  20969. backend.delete( texture );
  20970. }
  20971. destroySampler( texture ) {
  20972. const backend = this.backend;
  20973. const textureData = backend.get( texture );
  20974. delete textureData.sampler;
  20975. }
  20976. generateMipmaps( texture ) {
  20977. const textureData = this.backend.get( texture );
  20978. if ( texture.isCubeTexture ) {
  20979. for ( let i = 0; i < 6; i ++ ) {
  20980. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  20981. }
  20982. } else {
  20983. const depth = texture.image.depth || 1;
  20984. for ( let i = 0; i < depth; i ++ ) {
  20985. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  20986. }
  20987. }
  20988. }
  20989. getColorBuffer() {
  20990. if ( this.colorBuffer ) this.colorBuffer.destroy();
  20991. const backend = this.backend;
  20992. const { width, height } = backend.getDrawingBufferSize();
  20993. this.colorBuffer = backend.device.createTexture( {
  20994. label: 'colorBuffer',
  20995. size: {
  20996. width: width,
  20997. height: height,
  20998. depthOrArrayLayers: 1
  20999. },
  21000. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  21001. format: backend.utils.getPreferredCanvasFormat(),
  21002. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  21003. } );
  21004. return this.colorBuffer;
  21005. }
  21006. getDepthBuffer( depth = true, stencil = false ) {
  21007. const backend = this.backend;
  21008. const { width, height } = backend.getDrawingBufferSize();
  21009. const depthTexture = this.depthTexture;
  21010. const depthTextureGPU = backend.get( depthTexture ).texture;
  21011. let format, type;
  21012. if ( stencil ) {
  21013. format = DepthStencilFormat;
  21014. type = UnsignedInt248Type;
  21015. } else if ( depth ) {
  21016. format = DepthFormat;
  21017. type = UnsignedIntType;
  21018. }
  21019. if ( depthTextureGPU !== undefined ) {
  21020. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  21021. return depthTextureGPU;
  21022. }
  21023. this.destroyTexture( depthTexture );
  21024. }
  21025. depthTexture.name = 'depthBuffer';
  21026. depthTexture.format = format;
  21027. depthTexture.type = type;
  21028. depthTexture.image.width = width;
  21029. depthTexture.image.height = height;
  21030. this.createTexture( depthTexture, { sampleCount: backend.utils.getSampleCount( backend.renderer.samples ), width, height } );
  21031. return backend.get( depthTexture ).texture;
  21032. }
  21033. updateTexture( texture, options ) {
  21034. const textureData = this.backend.get( texture );
  21035. const { textureDescriptorGPU } = textureData;
  21036. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  21037. return;
  21038. // transfer texture data
  21039. if ( texture.isDataTexture ) {
  21040. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  21041. } else if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  21042. for ( let i = 0; i < options.image.depth; i ++ ) {
  21043. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  21044. }
  21045. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  21046. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  21047. } else if ( texture.isCubeTexture ) {
  21048. this._copyCubeMapToTexture( options.images, textureData.texture, textureDescriptorGPU, texture.flipY );
  21049. } else if ( texture.isVideoTexture ) {
  21050. const video = texture.source.data;
  21051. textureData.externalTexture = video;
  21052. } else {
  21053. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  21054. }
  21055. //
  21056. textureData.version = texture.version;
  21057. if ( texture.onUpdate ) texture.onUpdate( texture );
  21058. }
  21059. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  21060. const device = this.backend.device;
  21061. const textureData = this.backend.get( texture );
  21062. const textureGPU = textureData.texture;
  21063. const format = textureData.textureDescriptorGPU.format;
  21064. const bytesPerTexel = this._getBytesPerTexel( format );
  21065. let bytesPerRow = width * bytesPerTexel;
  21066. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  21067. const readBuffer = device.createBuffer(
  21068. {
  21069. size: width * height * bytesPerTexel,
  21070. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  21071. }
  21072. );
  21073. const encoder = device.createCommandEncoder();
  21074. encoder.copyTextureToBuffer(
  21075. {
  21076. texture: textureGPU,
  21077. origin: { x, y, z: faceIndex },
  21078. },
  21079. {
  21080. buffer: readBuffer,
  21081. bytesPerRow: bytesPerRow
  21082. },
  21083. {
  21084. width: width,
  21085. height: height
  21086. }
  21087. );
  21088. const typedArrayType = this._getTypedArrayType( format );
  21089. device.queue.submit( [ encoder.finish() ] );
  21090. await readBuffer.mapAsync( GPUMapMode.READ );
  21091. const buffer = readBuffer.getMappedRange();
  21092. return new typedArrayType( buffer );
  21093. }
  21094. _isEnvironmentTexture( texture ) {
  21095. const mapping = texture.mapping;
  21096. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  21097. }
  21098. _getDefaultTextureGPU( format ) {
  21099. let defaultTexture = this.defaultTexture[ format ];
  21100. if ( defaultTexture === undefined ) {
  21101. const texture = new Texture();
  21102. texture.minFilter = NearestFilter;
  21103. texture.magFilter = NearestFilter;
  21104. this.createTexture( texture, { width: 1, height: 1, format } );
  21105. this.defaultTexture[ format ] = defaultTexture = texture;
  21106. }
  21107. return this.backend.get( defaultTexture ).texture;
  21108. }
  21109. _getDefaultCubeTextureGPU( format ) {
  21110. let defaultCubeTexture = this.defaultTexture[ format ];
  21111. if ( defaultCubeTexture === undefined ) {
  21112. const texture = new CubeTexture();
  21113. texture.minFilter = NearestFilter;
  21114. texture.magFilter = NearestFilter;
  21115. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  21116. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  21117. }
  21118. return this.backend.get( defaultCubeTexture ).texture;
  21119. }
  21120. _getDefaultVideoFrame() {
  21121. let defaultVideoFrame = this.defaultVideoFrame;
  21122. if ( defaultVideoFrame === null ) {
  21123. const init = {
  21124. timestamp: 0,
  21125. codedWidth: 1,
  21126. codedHeight: 1,
  21127. format: 'RGBA',
  21128. };
  21129. this.defaultVideoFrame = defaultVideoFrame = new VideoFrame( new Uint8Array( [ 0, 0, 0, 0xff ] ), init );
  21130. }
  21131. return defaultVideoFrame;
  21132. }
  21133. _copyCubeMapToTexture( images, textureGPU, textureDescriptorGPU, flipY ) {
  21134. for ( let i = 0; i < 6; i ++ ) {
  21135. const image = images[ i ];
  21136. const flipIndex = flipY === true ? _flipMap[ i ] : i;
  21137. if ( image.isDataTexture ) {
  21138. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  21139. } else {
  21140. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  21141. }
  21142. }
  21143. }
  21144. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY ) {
  21145. const device = this.backend.device;
  21146. device.queue.copyExternalImageToTexture(
  21147. {
  21148. source: image
  21149. }, {
  21150. texture: textureGPU,
  21151. mipLevel: 0,
  21152. origin: { x: 0, y: 0, z: originDepth }
  21153. }, {
  21154. width: image.width,
  21155. height: image.height,
  21156. depthOrArrayLayers: 1
  21157. }
  21158. );
  21159. if ( flipY === true ) {
  21160. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  21161. }
  21162. }
  21163. _getPassUtils() {
  21164. let passUtils = this._passUtils;
  21165. if ( passUtils === null ) {
  21166. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  21167. }
  21168. return passUtils;
  21169. }
  21170. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  21171. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  21172. }
  21173. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  21174. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  21175. }
  21176. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0 ) {
  21177. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  21178. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  21179. const device = this.backend.device;
  21180. const data = image.data;
  21181. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  21182. const bytesPerRow = image.width * bytesPerTexel;
  21183. device.queue.writeTexture(
  21184. {
  21185. texture: textureGPU,
  21186. mipLevel: 0,
  21187. origin: { x: 0, y: 0, z: originDepth }
  21188. },
  21189. data,
  21190. {
  21191. offset: image.width * image.height * bytesPerTexel * depth,
  21192. bytesPerRow
  21193. },
  21194. {
  21195. width: image.width,
  21196. height: image.height,
  21197. depthOrArrayLayers: 1
  21198. } );
  21199. if ( flipY === true ) {
  21200. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  21201. }
  21202. }
  21203. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  21204. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  21205. const device = this.backend.device;
  21206. const blockData = this._getBlockData( textureDescriptorGPU.format );
  21207. const isTextureArray = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  21208. for ( let i = 0; i < mipmaps.length; i ++ ) {
  21209. const mipmap = mipmaps[ i ];
  21210. const width = mipmap.width;
  21211. const height = mipmap.height;
  21212. const depth = isTextureArray ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  21213. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  21214. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  21215. for ( let j = 0; j < depth; j ++ ) {
  21216. device.queue.writeTexture(
  21217. {
  21218. texture: textureGPU,
  21219. mipLevel: i,
  21220. origin: { x: 0, y: 0, z: j }
  21221. },
  21222. mipmap.data,
  21223. {
  21224. offset: j * bytesPerImage,
  21225. bytesPerRow,
  21226. rowsPerImage: Math.ceil( height / blockData.height )
  21227. },
  21228. {
  21229. width: Math.ceil( width / blockData.width ) * blockData.width,
  21230. height: Math.ceil( height / blockData.height ) * blockData.height,
  21231. depthOrArrayLayers: 1
  21232. }
  21233. );
  21234. }
  21235. }
  21236. }
  21237. _getBlockData( format ) {
  21238. // this method is only relevant for compressed texture formats
  21239. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  21240. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  21241. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  21242. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSNorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  21243. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  21244. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  21245. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  21246. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  21247. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  21248. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  21249. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  21250. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  21251. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  21252. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  21253. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  21254. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  21255. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  21256. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  21257. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  21258. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  21259. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  21260. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  21261. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  21262. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  21263. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  21264. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  21265. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  21266. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  21267. }
  21268. _convertAddressMode( value ) {
  21269. let addressMode = GPUAddressMode.ClampToEdge;
  21270. if ( value === RepeatWrapping ) {
  21271. addressMode = GPUAddressMode.Repeat;
  21272. } else if ( value === MirroredRepeatWrapping ) {
  21273. addressMode = GPUAddressMode.MirrorRepeat;
  21274. }
  21275. return addressMode;
  21276. }
  21277. _convertFilterMode( value ) {
  21278. let filterMode = GPUFilterMode.Linear;
  21279. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  21280. filterMode = GPUFilterMode.Nearest;
  21281. }
  21282. return filterMode;
  21283. }
  21284. _getBytesPerTexel( format ) {
  21285. // 8-bit formats
  21286. if ( format === GPUTextureFormat.R8Unorm ||
  21287. format === GPUTextureFormat.R8Snorm ||
  21288. format === GPUTextureFormat.R8Uint ||
  21289. format === GPUTextureFormat.R8Sint ) return 1;
  21290. // 16-bit formats
  21291. if ( format === GPUTextureFormat.R16Uint ||
  21292. format === GPUTextureFormat.R16Sint ||
  21293. format === GPUTextureFormat.R16Float ||
  21294. format === GPUTextureFormat.RG8Unorm ||
  21295. format === GPUTextureFormat.RG8Snorm ||
  21296. format === GPUTextureFormat.RG8Uint ||
  21297. format === GPUTextureFormat.RG8Sint ) return 2;
  21298. // 32-bit formats
  21299. if ( format === GPUTextureFormat.R32Uint ||
  21300. format === GPUTextureFormat.R32Sint ||
  21301. format === GPUTextureFormat.R32Float ||
  21302. format === GPUTextureFormat.RG16Uint ||
  21303. format === GPUTextureFormat.RG16Sint ||
  21304. format === GPUTextureFormat.RG16Float ||
  21305. format === GPUTextureFormat.RGBA8Unorm ||
  21306. format === GPUTextureFormat.RGBA8UnormSRGB ||
  21307. format === GPUTextureFormat.RGBA8Snorm ||
  21308. format === GPUTextureFormat.RGBA8Uint ||
  21309. format === GPUTextureFormat.RGBA8Sint ||
  21310. format === GPUTextureFormat.BGRA8Unorm ||
  21311. format === GPUTextureFormat.BGRA8UnormSRGB ||
  21312. // Packed 32-bit formats
  21313. format === GPUTextureFormat.RGB9E5UFloat ||
  21314. format === GPUTextureFormat.RGB10A2Unorm ||
  21315. format === GPUTextureFormat.RG11B10UFloat ||
  21316. format === GPUTextureFormat.Depth32Float ||
  21317. format === GPUTextureFormat.Depth24Plus ||
  21318. format === GPUTextureFormat.Depth24PlusStencil8 ||
  21319. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  21320. // 64-bit formats
  21321. if ( format === GPUTextureFormat.RG32Uint ||
  21322. format === GPUTextureFormat.RG32Sint ||
  21323. format === GPUTextureFormat.RG32Float ||
  21324. format === GPUTextureFormat.RGBA16Uint ||
  21325. format === GPUTextureFormat.RGBA16Sint ||
  21326. format === GPUTextureFormat.RGBA16Float ) return 8;
  21327. // 128-bit formats
  21328. if ( format === GPUTextureFormat.RGBA32Uint ||
  21329. format === GPUTextureFormat.RGBA32Sint ||
  21330. format === GPUTextureFormat.RGBA32Float ) return 16;
  21331. }
  21332. _getTypedArrayType( format ) {
  21333. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  21334. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  21335. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  21336. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  21337. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  21338. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  21339. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  21340. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  21341. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  21342. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  21343. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  21344. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  21345. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  21346. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  21347. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  21348. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  21349. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  21350. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  21351. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  21352. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  21353. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  21354. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  21355. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  21356. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  21357. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  21358. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  21359. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  21360. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  21361. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  21362. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  21363. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  21364. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  21365. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  21366. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  21367. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  21368. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  21369. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  21370. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  21371. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  21372. }
  21373. _getDimension( texture ) {
  21374. let dimension;
  21375. if ( texture.isData3DTexture ) {
  21376. dimension = GPUTextureDimension.ThreeD;
  21377. } else {
  21378. dimension = GPUTextureDimension.TwoD;
  21379. }
  21380. return dimension;
  21381. }
  21382. }
  21383. function getFormat( texture, device = null ) {
  21384. const format = texture.format;
  21385. const type = texture.type;
  21386. const colorSpace = texture.colorSpace;
  21387. let formatGPU;
  21388. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  21389. switch ( format ) {
  21390. case RGBA_S3TC_DXT1_Format:
  21391. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  21392. break;
  21393. case RGBA_S3TC_DXT3_Format:
  21394. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  21395. break;
  21396. case RGBA_S3TC_DXT5_Format:
  21397. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  21398. break;
  21399. case RGB_ETC2_Format:
  21400. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  21401. break;
  21402. case RGBA_ETC2_EAC_Format:
  21403. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  21404. break;
  21405. case RGBA_ASTC_4x4_Format:
  21406. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  21407. break;
  21408. case RGBA_ASTC_5x4_Format:
  21409. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  21410. break;
  21411. case RGBA_ASTC_5x5_Format:
  21412. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  21413. break;
  21414. case RGBA_ASTC_6x5_Format:
  21415. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  21416. break;
  21417. case RGBA_ASTC_6x6_Format:
  21418. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  21419. break;
  21420. case RGBA_ASTC_8x5_Format:
  21421. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  21422. break;
  21423. case RGBA_ASTC_8x6_Format:
  21424. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  21425. break;
  21426. case RGBA_ASTC_8x8_Format:
  21427. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  21428. break;
  21429. case RGBA_ASTC_10x5_Format:
  21430. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  21431. break;
  21432. case RGBA_ASTC_10x6_Format:
  21433. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  21434. break;
  21435. case RGBA_ASTC_10x8_Format:
  21436. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  21437. break;
  21438. case RGBA_ASTC_10x10_Format:
  21439. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  21440. break;
  21441. case RGBA_ASTC_12x10_Format:
  21442. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  21443. break;
  21444. case RGBA_ASTC_12x12_Format:
  21445. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  21446. break;
  21447. case RGBAFormat:
  21448. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  21449. break;
  21450. default:
  21451. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  21452. }
  21453. } else {
  21454. switch ( format ) {
  21455. case RGBAFormat:
  21456. switch ( type ) {
  21457. case ByteType:
  21458. formatGPU = GPUTextureFormat.RGBA8Snorm;
  21459. break;
  21460. case ShortType:
  21461. formatGPU = GPUTextureFormat.RGBA16Sint;
  21462. break;
  21463. case UnsignedShortType:
  21464. formatGPU = GPUTextureFormat.RGBA16Uint;
  21465. break;
  21466. case UnsignedIntType:
  21467. formatGPU = GPUTextureFormat.RGBA32Uint;
  21468. break;
  21469. case IntType:
  21470. formatGPU = GPUTextureFormat.RGBA32Sint;
  21471. break;
  21472. case UnsignedByteType:
  21473. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  21474. break;
  21475. case HalfFloatType:
  21476. formatGPU = GPUTextureFormat.RGBA16Float;
  21477. break;
  21478. case FloatType:
  21479. formatGPU = GPUTextureFormat.RGBA32Float;
  21480. break;
  21481. default:
  21482. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  21483. }
  21484. break;
  21485. case RGBFormat:
  21486. switch ( type ) {
  21487. case UnsignedInt5999Type:
  21488. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  21489. break;
  21490. default:
  21491. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  21492. }
  21493. break;
  21494. case RedFormat:
  21495. switch ( type ) {
  21496. case ByteType:
  21497. formatGPU = GPUTextureFormat.R8Snorm;
  21498. break;
  21499. case ShortType:
  21500. formatGPU = GPUTextureFormat.R16Sint;
  21501. break;
  21502. case UnsignedShortType:
  21503. formatGPU = GPUTextureFormat.R16Uint;
  21504. break;
  21505. case UnsignedIntType:
  21506. formatGPU = GPUTextureFormat.R32Uint;
  21507. break;
  21508. case IntType:
  21509. formatGPU = GPUTextureFormat.R32Sint;
  21510. break;
  21511. case UnsignedByteType:
  21512. formatGPU = GPUTextureFormat.R8Unorm;
  21513. break;
  21514. case HalfFloatType:
  21515. formatGPU = GPUTextureFormat.R16Float;
  21516. break;
  21517. case FloatType:
  21518. formatGPU = GPUTextureFormat.R32Float;
  21519. break;
  21520. default:
  21521. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  21522. }
  21523. break;
  21524. case RGFormat:
  21525. switch ( type ) {
  21526. case ByteType:
  21527. formatGPU = GPUTextureFormat.RG8Snorm;
  21528. break;
  21529. case ShortType:
  21530. formatGPU = GPUTextureFormat.RG16Sint;
  21531. break;
  21532. case UnsignedShortType:
  21533. formatGPU = GPUTextureFormat.RG16Uint;
  21534. break;
  21535. case UnsignedIntType:
  21536. formatGPU = GPUTextureFormat.RG32Uint;
  21537. break;
  21538. case IntType:
  21539. formatGPU = GPUTextureFormat.RG32Sint;
  21540. break;
  21541. case UnsignedByteType:
  21542. formatGPU = GPUTextureFormat.RG8Unorm;
  21543. break;
  21544. case HalfFloatType:
  21545. formatGPU = GPUTextureFormat.RG16Float;
  21546. break;
  21547. case FloatType:
  21548. formatGPU = GPUTextureFormat.RG32Float;
  21549. break;
  21550. default:
  21551. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  21552. }
  21553. break;
  21554. case DepthFormat:
  21555. switch ( type ) {
  21556. case UnsignedShortType:
  21557. formatGPU = GPUTextureFormat.Depth16Unorm;
  21558. break;
  21559. case UnsignedIntType:
  21560. formatGPU = GPUTextureFormat.Depth24Plus;
  21561. break;
  21562. case FloatType:
  21563. formatGPU = GPUTextureFormat.Depth32Float;
  21564. break;
  21565. default:
  21566. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  21567. }
  21568. break;
  21569. case DepthStencilFormat:
  21570. switch ( type ) {
  21571. case UnsignedInt248Type:
  21572. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  21573. break;
  21574. case FloatType:
  21575. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  21576. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  21577. }
  21578. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  21579. break;
  21580. default:
  21581. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  21582. }
  21583. break;
  21584. case RedIntegerFormat:
  21585. switch ( type ) {
  21586. case IntType:
  21587. formatGPU = GPUTextureFormat.R32Sint;
  21588. break;
  21589. case UnsignedIntType:
  21590. formatGPU = GPUTextureFormat.R32Uint;
  21591. break;
  21592. default:
  21593. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  21594. }
  21595. break;
  21596. case RGIntegerFormat:
  21597. switch ( type ) {
  21598. case IntType:
  21599. formatGPU = GPUTextureFormat.RG32Sint;
  21600. break;
  21601. case UnsignedIntType:
  21602. formatGPU = GPUTextureFormat.RG32Uint;
  21603. break;
  21604. default:
  21605. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  21606. }
  21607. break;
  21608. case RGBAIntegerFormat:
  21609. switch ( type ) {
  21610. case IntType:
  21611. formatGPU = GPUTextureFormat.RGBA32Sint;
  21612. break;
  21613. case UnsignedIntType:
  21614. formatGPU = GPUTextureFormat.RGBA32Uint;
  21615. break;
  21616. default:
  21617. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  21618. }
  21619. break;
  21620. default:
  21621. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  21622. }
  21623. }
  21624. return formatGPU;
  21625. }
  21626. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  21627. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  21628. const wgslTypeLib$1 = {
  21629. 'f32': 'float',
  21630. 'i32': 'int',
  21631. 'u32': 'uint',
  21632. 'bool': 'bool',
  21633. 'vec2<f32>': 'vec2',
  21634. 'vec2<i32>': 'ivec2',
  21635. 'vec2<u32>': 'uvec2',
  21636. 'vec2<bool>': 'bvec2',
  21637. 'vec2f': 'vec2',
  21638. 'vec2i': 'ivec2',
  21639. 'vec2u': 'uvec2',
  21640. 'vec2b': 'bvec2',
  21641. 'vec3<f32>': 'vec3',
  21642. 'vec3<i32>': 'ivec3',
  21643. 'vec3<u32>': 'uvec3',
  21644. 'vec3<bool>': 'bvec3',
  21645. 'vec3f': 'vec3',
  21646. 'vec3i': 'ivec3',
  21647. 'vec3u': 'uvec3',
  21648. 'vec3b': 'bvec3',
  21649. 'vec4<f32>': 'vec4',
  21650. 'vec4<i32>': 'ivec4',
  21651. 'vec4<u32>': 'uvec4',
  21652. 'vec4<bool>': 'bvec4',
  21653. 'vec4f': 'vec4',
  21654. 'vec4i': 'ivec4',
  21655. 'vec4u': 'uvec4',
  21656. 'vec4b': 'bvec4',
  21657. 'mat2x2<f32>': 'mat2',
  21658. 'mat2x2f': 'mat2',
  21659. 'mat3x3<f32>': 'mat3',
  21660. 'mat3x3f': 'mat3',
  21661. 'mat4x4<f32>': 'mat4',
  21662. 'mat4x4f': 'mat4',
  21663. 'sampler': 'sampler',
  21664. 'texture_1d': 'texture',
  21665. 'texture_2d': 'texture',
  21666. 'texture_2d_array': 'texture',
  21667. 'texture_multisampled_2d': 'cubeTexture',
  21668. 'texture_depth_2d': 'depthTexture',
  21669. 'texture_3d': 'texture3D',
  21670. 'texture_cube': 'cubeTexture',
  21671. 'texture_cube_array': 'cubeTexture',
  21672. 'texture_storage_1d': 'storageTexture',
  21673. 'texture_storage_2d': 'storageTexture',
  21674. 'texture_storage_2d_array': 'storageTexture',
  21675. 'texture_storage_3d': 'storageTexture'
  21676. };
  21677. const parse = ( source ) => {
  21678. source = source.trim();
  21679. const declaration = source.match( declarationRegexp );
  21680. if ( declaration !== null && declaration.length === 4 ) {
  21681. const inputsCode = declaration[ 2 ];
  21682. const propsMatches = [];
  21683. let match = null;
  21684. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  21685. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  21686. }
  21687. // Process matches to correctly pair names and types
  21688. const inputs = [];
  21689. for ( let i = 0; i < propsMatches.length; i ++ ) {
  21690. const { name, type } = propsMatches[ i ];
  21691. let resolvedType = type;
  21692. if ( resolvedType.startsWith( 'ptr' ) ) {
  21693. resolvedType = 'pointer';
  21694. } else {
  21695. if ( resolvedType.startsWith( 'texture' ) ) {
  21696. resolvedType = type.split( '<' )[ 0 ];
  21697. }
  21698. resolvedType = wgslTypeLib$1[ resolvedType ];
  21699. }
  21700. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  21701. }
  21702. const blockCode = source.substring( declaration[ 0 ].length );
  21703. const outputType = declaration[ 3 ] || 'void';
  21704. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  21705. const type = wgslTypeLib$1[ outputType ] || outputType;
  21706. return {
  21707. type,
  21708. inputs,
  21709. name,
  21710. inputsCode,
  21711. blockCode,
  21712. outputType
  21713. };
  21714. } else {
  21715. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  21716. }
  21717. };
  21718. class WGSLNodeFunction extends NodeFunction {
  21719. constructor( source ) {
  21720. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  21721. super( type, inputs, name );
  21722. this.inputsCode = inputsCode;
  21723. this.blockCode = blockCode;
  21724. this.outputType = outputType;
  21725. }
  21726. getCode( name = this.name ) {
  21727. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  21728. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  21729. }
  21730. }
  21731. class WGSLNodeParser extends NodeParser {
  21732. parseFunction( source ) {
  21733. return new WGSLNodeFunction( source );
  21734. }
  21735. }
  21736. // GPUShaderStage is not defined in browsers not supporting WebGPU
  21737. const GPUShaderStage = self.GPUShaderStage;
  21738. const wrapNames = {
  21739. [ RepeatWrapping ]: 'repeat',
  21740. [ ClampToEdgeWrapping ]: 'clamp',
  21741. [ MirroredRepeatWrapping ]: 'mirror'
  21742. };
  21743. const gpuShaderStageLib = {
  21744. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  21745. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  21746. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  21747. };
  21748. const supports = {
  21749. instance: true,
  21750. swizzleAssign: false,
  21751. storageBuffer: true
  21752. };
  21753. const wgslFnOpLib = {
  21754. '^^': 'tsl_xor'
  21755. };
  21756. const wgslTypeLib = {
  21757. float: 'f32',
  21758. int: 'i32',
  21759. uint: 'u32',
  21760. bool: 'bool',
  21761. color: 'vec3<f32>',
  21762. vec2: 'vec2<f32>',
  21763. ivec2: 'vec2<i32>',
  21764. uvec2: 'vec2<u32>',
  21765. bvec2: 'vec2<bool>',
  21766. vec3: 'vec3<f32>',
  21767. ivec3: 'vec3<i32>',
  21768. uvec3: 'vec3<u32>',
  21769. bvec3: 'vec3<bool>',
  21770. vec4: 'vec4<f32>',
  21771. ivec4: 'vec4<i32>',
  21772. uvec4: 'vec4<u32>',
  21773. bvec4: 'vec4<bool>',
  21774. mat2: 'mat2x2<f32>',
  21775. mat3: 'mat3x3<f32>',
  21776. mat4: 'mat4x4<f32>'
  21777. };
  21778. const wgslCodeCache = {};
  21779. const wgslPolyfill = {
  21780. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  21781. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  21782. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  21783. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  21784. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  21785. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  21786. 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 ); }' ),
  21787. 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 ); }' ),
  21788. 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 ); }' ),
  21789. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  21790. 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 ); }' ),
  21791. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  21792. biquadraticTexture: new CodeNode( /* wgsl */`
  21793. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  21794. let res = vec2f( iRes );
  21795. let uvScaled = coord * res;
  21796. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  21797. // https://www.shadertoy.com/view/WtyXRy
  21798. let uv = uvWrapping - 0.5;
  21799. let iuv = floor( uv );
  21800. let f = fract( uv );
  21801. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  21802. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  21803. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  21804. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  21805. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  21806. }
  21807. ` )
  21808. };
  21809. const wgslMethods = {
  21810. dFdx: 'dpdx',
  21811. dFdy: '- dpdy',
  21812. mod_float: 'tsl_mod_float',
  21813. mod_vec2: 'tsl_mod_vec2',
  21814. mod_vec3: 'tsl_mod_vec3',
  21815. mod_vec4: 'tsl_mod_vec4',
  21816. equals_bool: 'tsl_equals_bool',
  21817. equals_bvec2: 'tsl_equals_bvec2',
  21818. equals_bvec3: 'tsl_equals_bvec3',
  21819. equals_bvec4: 'tsl_equals_bvec4',
  21820. inversesqrt: 'inverseSqrt',
  21821. bitcast: 'bitcast<f32>'
  21822. };
  21823. // WebGPU issue: does not support pow() with negative base on Windows
  21824. if ( /Windows/g.test( navigator.userAgent ) ) {
  21825. 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 ); }' );
  21826. 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 ] );
  21827. 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 ] );
  21828. 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 ] );
  21829. wgslMethods.pow_float = 'tsl_pow_float';
  21830. wgslMethods.pow_vec2 = 'tsl_pow_vec2';
  21831. wgslMethods.pow_vec3 = 'tsl_pow_vec3';
  21832. wgslMethods.pow_vec4 = 'tsl_pow_vec4';
  21833. }
  21834. //
  21835. let diagnostics = '';
  21836. if ( /Firefox|Deno/g.test( navigator.userAgent ) !== true ) {
  21837. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  21838. }
  21839. //
  21840. class WGSLNodeBuilder extends NodeBuilder {
  21841. constructor( object, renderer ) {
  21842. super( object, renderer, new WGSLNodeParser() );
  21843. this.uniformGroups = {};
  21844. this.builtins = {};
  21845. this.directives = {};
  21846. this.scopedArrays = new Map();
  21847. }
  21848. needsToWorkingColorSpace( texture ) {
  21849. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  21850. }
  21851. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  21852. if ( shaderStage === 'fragment' ) {
  21853. if ( depthSnippet ) {
  21854. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  21855. } else {
  21856. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  21857. }
  21858. } else if ( this.isFilteredTexture( texture ) ) {
  21859. return this.generateFilteredTexture( texture, textureProperty, uvSnippet );
  21860. } else {
  21861. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0' );
  21862. }
  21863. }
  21864. _generateVideoSample( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  21865. if ( shaderStage === 'fragment' ) {
  21866. return `textureSampleBaseClampToEdge( ${ textureProperty }, ${ textureProperty }_sampler, vec2<f32>( ${ uvSnippet }.x, 1.0 - ${ uvSnippet }.y ) )`;
  21867. } else {
  21868. console.error( `WebGPURenderer: THREE.VideoTexture does not support ${ shaderStage } shader.` );
  21869. }
  21870. }
  21871. _generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  21872. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false ) {
  21873. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  21874. } else if ( this.isFilteredTexture( texture ) ) {
  21875. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  21876. } else {
  21877. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet );
  21878. }
  21879. }
  21880. generateWrapFunction( texture ) {
  21881. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }T`;
  21882. let nodeCode = wgslCodeCache[ functionName ];
  21883. if ( nodeCode === undefined ) {
  21884. const includes = [];
  21885. let code = `fn ${ functionName }( coord : vec2f ) -> vec2f {\n\n\treturn vec2f(\n`;
  21886. const addWrapSnippet = ( wrap, axis ) => {
  21887. if ( wrap === RepeatWrapping ) {
  21888. includes.push( wgslPolyfill.repeatWrapping_float );
  21889. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  21890. } else if ( wrap === ClampToEdgeWrapping ) {
  21891. includes.push( wgslPolyfill.clampWrapping_float );
  21892. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  21893. } else if ( wrap === MirroredRepeatWrapping ) {
  21894. includes.push( wgslPolyfill.mirrorWrapping_float );
  21895. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  21896. } else {
  21897. code += `\t\tcoord.${ axis }`;
  21898. console.warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  21899. }
  21900. };
  21901. addWrapSnippet( texture.wrapS, 'x' );
  21902. code += ',\n';
  21903. addWrapSnippet( texture.wrapT, 'y' );
  21904. code += '\n\t);\n\n}\n';
  21905. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  21906. }
  21907. nodeCode.build( this );
  21908. return functionName;
  21909. }
  21910. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  21911. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  21912. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  21913. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  21914. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  21915. let textureDimensionsParams;
  21916. if ( texture.isMultisampleRenderTargetTexture === true ) {
  21917. textureDimensionsParams = textureProperty;
  21918. } else {
  21919. textureDimensionsParams = `${ textureProperty }, u32( ${ levelSnippet } )`;
  21920. }
  21921. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, 'uvec2' ) );
  21922. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  21923. }
  21924. return textureDimensionNode.build( this );
  21925. }
  21926. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0u' ) {
  21927. this._include( 'biquadraticTexture' );
  21928. const wrapFunction = this.generateWrapFunction( texture );
  21929. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  21930. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  21931. }
  21932. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet = '0u' ) {
  21933. const wrapFunction = this.generateWrapFunction( texture );
  21934. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  21935. const coordSnippet = `vec2u( ${ wrapFunction }( ${ uvSnippet } ) * vec2f( ${ textureDimension } ) )`;
  21936. return this.generateTextureLoad( texture, textureProperty, coordSnippet, depthSnippet, levelSnippet );
  21937. }
  21938. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  21939. if ( depthSnippet ) {
  21940. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  21941. } else {
  21942. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  21943. }
  21944. }
  21945. generateTextureStore( texture, textureProperty, uvIndexSnippet, valueSnippet ) {
  21946. return `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  21947. }
  21948. isSampleCompare( texture ) {
  21949. return texture.isDepthTexture === true && texture.compareFunction !== null;
  21950. }
  21951. isUnfilterable( texture ) {
  21952. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  21953. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  21954. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  21955. texture.isMultisampleRenderTargetTexture === true;
  21956. }
  21957. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  21958. let snippet = null;
  21959. if ( texture.isVideoTexture === true ) {
  21960. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  21961. } else if ( this.isUnfilterable( texture ) ) {
  21962. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0', shaderStage );
  21963. } else {
  21964. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  21965. }
  21966. return snippet;
  21967. }
  21968. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  21969. if ( shaderStage === 'fragment' ) {
  21970. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  21971. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  21972. } else {
  21973. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  21974. }
  21975. }
  21976. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  21977. if ( shaderStage === 'fragment' ) {
  21978. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  21979. } else {
  21980. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  21981. }
  21982. }
  21983. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  21984. let snippet = null;
  21985. if ( texture.isVideoTexture === true ) {
  21986. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  21987. } else {
  21988. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage );
  21989. }
  21990. return snippet;
  21991. }
  21992. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  21993. if ( shaderStage === 'fragment' ) {
  21994. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  21995. } else {
  21996. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  21997. }
  21998. }
  21999. getPropertyName( node, shaderStage = this.shaderStage ) {
  22000. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  22001. if ( shaderStage === 'vertex' ) {
  22002. return `varyings.${ node.name }`;
  22003. }
  22004. } else if ( node.isNodeUniform === true ) {
  22005. const name = node.name;
  22006. const type = node.type;
  22007. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  22008. return name;
  22009. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  22010. return `NodeBuffer_${ node.id }.${name}`;
  22011. } else {
  22012. return node.groupNode.name + '.' + name;
  22013. }
  22014. }
  22015. return super.getPropertyName( node );
  22016. }
  22017. getOutputStructName() {
  22018. return 'output';
  22019. }
  22020. _getUniformGroupCount( shaderStage ) {
  22021. return Object.keys( this.uniforms[ shaderStage ] ).length;
  22022. }
  22023. getFunctionOperator( op ) {
  22024. const fnOp = wgslFnOpLib[ op ];
  22025. if ( fnOp !== undefined ) {
  22026. this._include( fnOp );
  22027. return fnOp;
  22028. }
  22029. return null;
  22030. }
  22031. getStorageAccess( node ) {
  22032. if ( node.isStorageTextureNode ) {
  22033. switch ( node.access ) {
  22034. case GPUStorageTextureAccess.ReadOnly:
  22035. return 'read';
  22036. case GPUStorageTextureAccess.WriteOnly:
  22037. return 'write';
  22038. default:
  22039. return 'read_write';
  22040. }
  22041. } else {
  22042. switch ( node.access ) {
  22043. case GPUBufferBindingType.Storage:
  22044. return 'read_write';
  22045. case GPUBufferBindingType.ReadOnlyStorage:
  22046. return 'read';
  22047. default:
  22048. return 'write';
  22049. }
  22050. }
  22051. }
  22052. getUniformFromNode( node, type, shaderStage, name = null ) {
  22053. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  22054. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  22055. if ( nodeData.uniformGPU === undefined ) {
  22056. let uniformGPU;
  22057. const group = node.groupNode;
  22058. const groupName = group.name;
  22059. const bindings = this.getBindGroupArray( groupName, shaderStage );
  22060. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  22061. let texture = null;
  22062. if ( type === 'texture' || type === 'storageTexture' ) {
  22063. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  22064. } else if ( type === 'cubeTexture' ) {
  22065. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  22066. } else if ( type === 'texture3D' ) {
  22067. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  22068. }
  22069. texture.store = node.isStorageTextureNode === true;
  22070. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  22071. if ( shaderStage === 'fragment' && this.isUnfilterable( node.value ) === false && texture.store === false ) {
  22072. const sampler = new NodeSampler( `${uniformNode.name}_sampler`, uniformNode.node, group );
  22073. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  22074. bindings.push( sampler, texture );
  22075. uniformGPU = [ sampler, texture ];
  22076. } else {
  22077. bindings.push( texture );
  22078. uniformGPU = [ texture ];
  22079. }
  22080. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  22081. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  22082. const buffer = new bufferClass( node, group );
  22083. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  22084. bindings.push( buffer );
  22085. uniformGPU = buffer;
  22086. } else {
  22087. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  22088. let uniformsGroup = uniformsStage[ groupName ];
  22089. if ( uniformsGroup === undefined ) {
  22090. uniformsGroup = new NodeUniformsGroup( groupName, group );
  22091. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  22092. uniformsStage[ groupName ] = uniformsGroup;
  22093. bindings.push( uniformsGroup );
  22094. }
  22095. uniformGPU = this.getNodeUniform( uniformNode, type );
  22096. uniformsGroup.addUniform( uniformGPU );
  22097. }
  22098. nodeData.uniformGPU = uniformGPU;
  22099. }
  22100. return uniformNode;
  22101. }
  22102. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  22103. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  22104. if ( map.has( name ) === false ) {
  22105. map.set( name, {
  22106. name,
  22107. property,
  22108. type
  22109. } );
  22110. }
  22111. return property;
  22112. }
  22113. hasBuiltin( name, shaderStage = this.shaderStage ) {
  22114. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  22115. }
  22116. getVertexIndex() {
  22117. if ( this.shaderStage === 'vertex' ) {
  22118. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  22119. }
  22120. return 'vertexIndex';
  22121. }
  22122. buildFunctionCode( shaderNode ) {
  22123. const layout = shaderNode.layout;
  22124. const flowData = this.flowShaderNode( shaderNode );
  22125. const parameters = [];
  22126. for ( const input of layout.inputs ) {
  22127. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  22128. }
  22129. //
  22130. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  22131. ${ flowData.vars }
  22132. ${ flowData.code }
  22133. `;
  22134. if ( flowData.result ) {
  22135. code += `\treturn ${ flowData.result };\n`;
  22136. }
  22137. code += '\n}\n';
  22138. //
  22139. return code;
  22140. }
  22141. getInstanceIndex() {
  22142. if ( this.shaderStage === 'vertex' ) {
  22143. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  22144. }
  22145. return 'instanceIndex';
  22146. }
  22147. getInvocationLocalIndex() {
  22148. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  22149. }
  22150. getSubgroupSize() {
  22151. this.enableSubGroups();
  22152. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  22153. }
  22154. getInvocationSubgroupIndex() {
  22155. this.enableSubGroups();
  22156. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  22157. }
  22158. getSubgroupIndex() {
  22159. this.enableSubGroups();
  22160. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  22161. }
  22162. getDrawIndex() {
  22163. return null;
  22164. }
  22165. getFrontFacing() {
  22166. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  22167. }
  22168. getFragCoord() {
  22169. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  22170. }
  22171. getFragDepth() {
  22172. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  22173. }
  22174. getClipDistance() {
  22175. return 'varyings.hw_clip_distances';
  22176. }
  22177. isFlipY() {
  22178. return false;
  22179. }
  22180. enableDirective( name, shaderStage = this.shaderStage ) {
  22181. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  22182. stage.add( name );
  22183. }
  22184. getDirectives( shaderStage ) {
  22185. const snippets = [];
  22186. const directives = this.directives[ shaderStage ];
  22187. if ( directives !== undefined ) {
  22188. for ( const directive of directives ) {
  22189. snippets.push( `enable ${directive};` );
  22190. }
  22191. }
  22192. return snippets.join( '\n' );
  22193. }
  22194. enableSubGroups() {
  22195. this.enableDirective( 'subgroups' );
  22196. }
  22197. enableSubgroupsF16() {
  22198. this.enableDirective( 'subgroups-f16' );
  22199. }
  22200. enableClipDistances() {
  22201. this.enableDirective( 'clip_distances' );
  22202. }
  22203. enableShaderF16() {
  22204. this.enableDirective( 'f16' );
  22205. }
  22206. enableDualSourceBlending() {
  22207. this.enableDirective( 'dual_source_blending' );
  22208. }
  22209. enableHardwareClipping( planeCount ) {
  22210. this.enableClipDistances();
  22211. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  22212. }
  22213. getBuiltins( shaderStage ) {
  22214. const snippets = [];
  22215. const builtins = this.builtins[ shaderStage ];
  22216. if ( builtins !== undefined ) {
  22217. for ( const { name, property, type } of builtins.values() ) {
  22218. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  22219. }
  22220. }
  22221. return snippets.join( ',\n\t' );
  22222. }
  22223. getScopedArray( name, scope, bufferType, bufferCount ) {
  22224. if ( this.scopedArrays.has( name ) === false ) {
  22225. this.scopedArrays.set( name, {
  22226. name,
  22227. scope,
  22228. bufferType,
  22229. bufferCount
  22230. } );
  22231. }
  22232. return name;
  22233. }
  22234. getScopedArrays( shaderStage ) {
  22235. if ( shaderStage !== 'compute' ) {
  22236. return;
  22237. }
  22238. const snippets = [];
  22239. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  22240. const type = this.getType( bufferType );
  22241. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  22242. }
  22243. return snippets.join( '\n' );
  22244. }
  22245. getAttributes( shaderStage ) {
  22246. const snippets = [];
  22247. if ( shaderStage === 'compute' ) {
  22248. this.getBuiltin( 'global_invocation_id', 'id', 'vec3<u32>', 'attribute' );
  22249. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  22250. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  22251. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  22252. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  22253. this.enableDirective( 'subgroups', shaderStage );
  22254. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  22255. }
  22256. }
  22257. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  22258. const builtins = this.getBuiltins( 'attribute' );
  22259. if ( builtins ) snippets.push( builtins );
  22260. const attributes = this.getAttributesArray();
  22261. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  22262. const attribute = attributes[ index ];
  22263. const name = attribute.name;
  22264. const type = this.getType( attribute.type );
  22265. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  22266. }
  22267. }
  22268. return snippets.join( ',\n\t' );
  22269. }
  22270. getStructMembers( struct ) {
  22271. const snippets = [];
  22272. const members = struct.getMemberTypes();
  22273. for ( let i = 0; i < members.length; i ++ ) {
  22274. const member = members[ i ];
  22275. snippets.push( `\t@location( ${i} ) m${i} : ${ member }<f32>` );
  22276. }
  22277. const builtins = this.getBuiltins( 'output' );
  22278. if ( builtins ) snippets.push( '\t' + builtins );
  22279. return snippets.join( ',\n' );
  22280. }
  22281. getStructs( shaderStage ) {
  22282. const snippets = [];
  22283. const structs = this.structs[ shaderStage ];
  22284. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  22285. const struct = structs[ index ];
  22286. const name = struct.name;
  22287. let snippet = `\struct ${ name } {\n`;
  22288. snippet += this.getStructMembers( struct );
  22289. snippet += '\n}';
  22290. snippets.push( snippet );
  22291. snippets.push( `\nvar<private> output : ${ name };\n\n` );
  22292. }
  22293. return snippets.join( '\n\n' );
  22294. }
  22295. getVar( type, name ) {
  22296. return `var ${ name } : ${ this.getType( type ) }`;
  22297. }
  22298. getVars( shaderStage ) {
  22299. const snippets = [];
  22300. const vars = this.vars[ shaderStage ];
  22301. if ( vars !== undefined ) {
  22302. for ( const variable of vars ) {
  22303. snippets.push( `\t${ this.getVar( variable.type, variable.name ) };` );
  22304. }
  22305. }
  22306. return `\n${ snippets.join( '\n' ) }\n`;
  22307. }
  22308. getVaryings( shaderStage ) {
  22309. const snippets = [];
  22310. if ( shaderStage === 'vertex' ) {
  22311. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  22312. }
  22313. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  22314. const varyings = this.varyings;
  22315. const vars = this.vars[ shaderStage ];
  22316. for ( let index = 0; index < varyings.length; index ++ ) {
  22317. const varying = varyings[ index ];
  22318. if ( varying.needsInterpolation ) {
  22319. let attributesSnippet = `@location( ${index} )`;
  22320. if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  22321. attributesSnippet += ' @interpolate( flat )';
  22322. }
  22323. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  22324. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  22325. vars.push( varying );
  22326. }
  22327. }
  22328. }
  22329. const builtins = this.getBuiltins( shaderStage );
  22330. if ( builtins ) snippets.push( builtins );
  22331. const code = snippets.join( ',\n\t' );
  22332. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  22333. }
  22334. getUniforms( shaderStage ) {
  22335. const uniforms = this.uniforms[ shaderStage ];
  22336. const bindingSnippets = [];
  22337. const bufferSnippets = [];
  22338. const structSnippets = [];
  22339. const uniformGroups = {};
  22340. for ( const uniform of uniforms ) {
  22341. const groupName = uniform.groupNode.name;
  22342. const uniformIndexes = this.bindingsIndexes[ groupName ];
  22343. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  22344. const texture = uniform.node.value;
  22345. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  22346. if ( this.isSampleCompare( texture ) ) {
  22347. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  22348. } else {
  22349. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  22350. }
  22351. }
  22352. let textureType;
  22353. let multisampled = '';
  22354. if ( texture.isMultisampleRenderTargetTexture === true ) {
  22355. multisampled = '_multisampled';
  22356. }
  22357. if ( texture.isCubeTexture === true ) {
  22358. textureType = 'texture_cube<f32>';
  22359. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  22360. textureType = 'texture_2d_array<f32>';
  22361. } else if ( texture.isDepthTexture === true ) {
  22362. textureType = `texture_depth${multisampled}_2d`;
  22363. } else if ( texture.isVideoTexture === true ) {
  22364. textureType = 'texture_external';
  22365. } else if ( texture.isData3DTexture === true ) {
  22366. textureType = 'texture_3d<f32>';
  22367. } else if ( uniform.node.isStorageTextureNode === true ) {
  22368. const format = getFormat( texture );
  22369. const access = this.getStorageAccess( uniform.node );
  22370. textureType = `texture_storage_2d<${ format }, ${ access }>`;
  22371. } else {
  22372. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  22373. textureType = `texture${multisampled}_2d<${ componentPrefix }32>`;
  22374. }
  22375. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  22376. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  22377. const bufferNode = uniform.node;
  22378. const bufferType = this.getType( bufferNode.bufferType );
  22379. const bufferCount = bufferNode.bufferCount;
  22380. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  22381. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${bufferType}>` : `${bufferType}`;
  22382. const bufferSnippet = `\t${ uniform.name } : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >\n`;
  22383. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode ) }` : 'uniform';
  22384. bufferSnippets.push( this._getWGSLStructBinding( 'NodeBuffer_' + bufferNode.id, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  22385. } else {
  22386. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  22387. const groupName = uniform.groupNode.name;
  22388. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  22389. index: uniformIndexes.binding ++,
  22390. id: uniformIndexes.group,
  22391. snippets: []
  22392. } );
  22393. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  22394. }
  22395. }
  22396. for ( const name in uniformGroups ) {
  22397. const group = uniformGroups[ name ];
  22398. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  22399. }
  22400. let code = bindingSnippets.join( '\n' );
  22401. code += bufferSnippets.join( '\n' );
  22402. code += structSnippets.join( '\n' );
  22403. return code;
  22404. }
  22405. buildCode() {
  22406. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  22407. this.sortBindingGroups();
  22408. for ( const shaderStage in shadersData ) {
  22409. const stageData = shadersData[ shaderStage ];
  22410. stageData.uniforms = this.getUniforms( shaderStage );
  22411. stageData.attributes = this.getAttributes( shaderStage );
  22412. stageData.varyings = this.getVaryings( shaderStage );
  22413. stageData.structs = this.getStructs( shaderStage );
  22414. stageData.vars = this.getVars( shaderStage );
  22415. stageData.codes = this.getCodes( shaderStage );
  22416. stageData.directives = this.getDirectives( shaderStage );
  22417. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  22418. //
  22419. let flow = '// code\n\n';
  22420. flow += this.flowCode[ shaderStage ];
  22421. const flowNodes = this.flowNodes[ shaderStage ];
  22422. const mainNode = flowNodes[ flowNodes.length - 1 ];
  22423. const outputNode = mainNode.outputNode;
  22424. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  22425. for ( const node of flowNodes ) {
  22426. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  22427. const slotName = node.name;
  22428. if ( slotName ) {
  22429. if ( flow.length > 0 ) flow += '\n';
  22430. flow += `\t// flow -> ${ slotName }\n\t`;
  22431. }
  22432. flow += `${ flowSlotData.code }\n\t`;
  22433. if ( node === mainNode && shaderStage !== 'compute' ) {
  22434. flow += '// result\n\n\t';
  22435. if ( shaderStage === 'vertex' ) {
  22436. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  22437. } else if ( shaderStage === 'fragment' ) {
  22438. if ( isOutputStruct ) {
  22439. stageData.returnType = outputNode.nodeType;
  22440. flow += `return ${ flowSlotData.result };`;
  22441. } else {
  22442. let structSnippet = '\t@location(0) color: vec4<f32>';
  22443. const builtins = this.getBuiltins( 'output' );
  22444. if ( builtins ) structSnippet += ',\n\t' + builtins;
  22445. stageData.returnType = 'OutputStruct';
  22446. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  22447. stageData.structs += '\nvar<private> output : OutputStruct;\n\n';
  22448. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  22449. }
  22450. }
  22451. }
  22452. }
  22453. stageData.flow = flow;
  22454. }
  22455. if ( this.material !== null ) {
  22456. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  22457. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  22458. } else {
  22459. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  22460. }
  22461. }
  22462. getMethod( method, output = null ) {
  22463. let wgslMethod;
  22464. if ( output !== null ) {
  22465. wgslMethod = this._getWGSLMethod( method + '_' + output );
  22466. }
  22467. if ( wgslMethod === undefined ) {
  22468. wgslMethod = this._getWGSLMethod( method );
  22469. }
  22470. return wgslMethod || method;
  22471. }
  22472. getType( type ) {
  22473. return wgslTypeLib[ type ] || type;
  22474. }
  22475. isAvailable( name ) {
  22476. let result = supports[ name ];
  22477. if ( result === undefined ) {
  22478. if ( name === 'float32Filterable' ) {
  22479. result = this.renderer.hasFeature( 'float32-filterable' );
  22480. } else if ( name === 'clipDistance' ) {
  22481. result = this.renderer.hasFeature( 'clip-distances' );
  22482. }
  22483. supports[ name ] = result;
  22484. }
  22485. return result;
  22486. }
  22487. _getWGSLMethod( method ) {
  22488. if ( wgslPolyfill[ method ] !== undefined ) {
  22489. this._include( method );
  22490. }
  22491. return wgslMethods[ method ];
  22492. }
  22493. _include( name ) {
  22494. const codeNode = wgslPolyfill[ name ];
  22495. codeNode.build( this );
  22496. if ( this.currentFunctionNode !== null ) {
  22497. this.currentFunctionNode.includes.push( codeNode );
  22498. }
  22499. return codeNode;
  22500. }
  22501. _getWGSLVertexCode( shaderData ) {
  22502. return `${ this.getSignature() }
  22503. // directives
  22504. ${shaderData.directives}
  22505. // uniforms
  22506. ${shaderData.uniforms}
  22507. // varyings
  22508. ${shaderData.varyings}
  22509. var<private> varyings : VaryingsStruct;
  22510. // codes
  22511. ${shaderData.codes}
  22512. @vertex
  22513. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  22514. // vars
  22515. ${shaderData.vars}
  22516. // flow
  22517. ${shaderData.flow}
  22518. return varyings;
  22519. }
  22520. `;
  22521. }
  22522. _getWGSLFragmentCode( shaderData ) {
  22523. return `${ this.getSignature() }
  22524. // global
  22525. ${ diagnostics }
  22526. // uniforms
  22527. ${shaderData.uniforms}
  22528. // structs
  22529. ${shaderData.structs}
  22530. // codes
  22531. ${shaderData.codes}
  22532. @fragment
  22533. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  22534. // vars
  22535. ${shaderData.vars}
  22536. // flow
  22537. ${shaderData.flow}
  22538. }
  22539. `;
  22540. }
  22541. _getWGSLComputeCode( shaderData, workgroupSize ) {
  22542. return `${ this.getSignature() }
  22543. // directives
  22544. ${shaderData.directives}
  22545. // system
  22546. var<private> instanceIndex : u32;
  22547. // locals
  22548. ${shaderData.scopedArrays}
  22549. // uniforms
  22550. ${shaderData.uniforms}
  22551. // codes
  22552. ${shaderData.codes}
  22553. @compute @workgroup_size( ${workgroupSize} )
  22554. fn main( ${shaderData.attributes} ) {
  22555. // system
  22556. instanceIndex = id.x + id.y * numWorkgroups.x * u32(${workgroupSize}) + id.z * numWorkgroups.x * numWorkgroups.y * u32(${workgroupSize});
  22557. // vars
  22558. ${shaderData.vars}
  22559. // flow
  22560. ${shaderData.flow}
  22561. }
  22562. `;
  22563. }
  22564. _getWGSLStruct( name, vars ) {
  22565. return `
  22566. struct ${name} {
  22567. ${vars}
  22568. };`;
  22569. }
  22570. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  22571. const structName = name + 'Struct';
  22572. const structSnippet = this._getWGSLStruct( structName, vars );
  22573. return `${structSnippet}
  22574. @binding( ${binding} ) @group( ${group} )
  22575. var<${access}> ${name} : ${structName};`;
  22576. }
  22577. }
  22578. class WebGPUUtils {
  22579. constructor( backend ) {
  22580. this.backend = backend;
  22581. }
  22582. getCurrentDepthStencilFormat( renderContext ) {
  22583. let format;
  22584. if ( renderContext.depthTexture !== null ) {
  22585. format = this.getTextureFormatGPU( renderContext.depthTexture );
  22586. } else if ( renderContext.depth && renderContext.stencil ) {
  22587. format = GPUTextureFormat.Depth24PlusStencil8;
  22588. } else if ( renderContext.depth ) {
  22589. format = GPUTextureFormat.Depth24Plus;
  22590. }
  22591. return format;
  22592. }
  22593. getTextureFormatGPU( texture ) {
  22594. return this.backend.get( texture ).format;
  22595. }
  22596. getCurrentColorFormat( renderContext ) {
  22597. let format;
  22598. if ( renderContext.textures !== null ) {
  22599. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  22600. } else {
  22601. format = this.getPreferredCanvasFormat(); // default context format
  22602. }
  22603. return format;
  22604. }
  22605. getCurrentColorSpace( renderContext ) {
  22606. if ( renderContext.textures !== null ) {
  22607. return renderContext.textures[ 0 ].colorSpace;
  22608. }
  22609. return this.backend.renderer.outputColorSpace;
  22610. }
  22611. getPrimitiveTopology( object, material ) {
  22612. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  22613. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  22614. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  22615. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  22616. }
  22617. getSampleCount( sampleCount ) {
  22618. let count = 1;
  22619. if ( sampleCount > 1 ) {
  22620. // WebGPU only supports power-of-two sample counts and 2 is not a valid value
  22621. count = Math.pow( 2, Math.floor( Math.log2( sampleCount ) ) );
  22622. if ( count === 2 ) {
  22623. count = 4;
  22624. }
  22625. }
  22626. return count;
  22627. }
  22628. getSampleCountRenderContext( renderContext ) {
  22629. if ( renderContext.textures !== null ) {
  22630. return this.getSampleCount( renderContext.sampleCount );
  22631. }
  22632. return this.getSampleCount( this.backend.renderer.samples );
  22633. }
  22634. getPreferredCanvasFormat() {
  22635. // TODO: Remove this check when Quest 34.5 is out
  22636. // https://github.com/mrdoob/three.js/pull/29221/files#r1731833949
  22637. if ( navigator.userAgent.includes( 'Quest' ) ) {
  22638. return GPUTextureFormat.BGRA8Unorm;
  22639. } else {
  22640. return navigator.gpu.getPreferredCanvasFormat();
  22641. }
  22642. }
  22643. }
  22644. const typedArraysToVertexFormatPrefix = new Map( [
  22645. [ Int8Array, [ 'sint8', 'snorm8' ]],
  22646. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  22647. [ Int16Array, [ 'sint16', 'snorm16' ]],
  22648. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  22649. [ Int32Array, [ 'sint32', 'snorm32' ]],
  22650. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  22651. [ Float32Array, [ 'float32', ]],
  22652. ] );
  22653. const typedAttributeToVertexFormatPrefix = new Map( [
  22654. [ Float16BufferAttribute, [ 'float16', ]],
  22655. ] );
  22656. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  22657. [ Int32Array, 'sint32' ],
  22658. [ Int16Array, 'sint32' ], // patch for INT16
  22659. [ Uint32Array, 'uint32' ],
  22660. [ Uint16Array, 'uint32' ], // patch for UINT16
  22661. [ Float32Array, 'float32' ]
  22662. ] );
  22663. class WebGPUAttributeUtils {
  22664. constructor( backend ) {
  22665. this.backend = backend;
  22666. }
  22667. createAttribute( attribute, usage ) {
  22668. const bufferAttribute = this._getBufferAttribute( attribute );
  22669. const backend = this.backend;
  22670. const bufferData = backend.get( bufferAttribute );
  22671. let buffer = bufferData.buffer;
  22672. if ( buffer === undefined ) {
  22673. const device = backend.device;
  22674. let array = bufferAttribute.array;
  22675. // patch for INT16 and UINT16
  22676. if ( attribute.normalized === false && ( array.constructor === Int16Array || array.constructor === Uint16Array ) ) {
  22677. const tempArray = new Uint32Array( array.length );
  22678. for ( let i = 0; i < array.length; i ++ ) {
  22679. tempArray[ i ] = array[ i ];
  22680. }
  22681. array = tempArray;
  22682. }
  22683. bufferAttribute.array = array;
  22684. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  22685. array = new array.constructor( bufferAttribute.count * 4 );
  22686. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  22687. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  22688. }
  22689. // Update BufferAttribute
  22690. bufferAttribute.itemSize = 4;
  22691. bufferAttribute.array = array;
  22692. }
  22693. const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441
  22694. buffer = device.createBuffer( {
  22695. label: bufferAttribute.name,
  22696. size: size,
  22697. usage: usage,
  22698. mappedAtCreation: true
  22699. } );
  22700. new array.constructor( buffer.getMappedRange() ).set( array );
  22701. buffer.unmap();
  22702. bufferData.buffer = buffer;
  22703. }
  22704. }
  22705. updateAttribute( attribute ) {
  22706. const bufferAttribute = this._getBufferAttribute( attribute );
  22707. const backend = this.backend;
  22708. const device = backend.device;
  22709. const buffer = backend.get( bufferAttribute ).buffer;
  22710. const array = bufferAttribute.array;
  22711. const updateRanges = bufferAttribute.updateRanges;
  22712. if ( updateRanges.length === 0 ) {
  22713. // Not using update ranges
  22714. device.queue.writeBuffer(
  22715. buffer,
  22716. 0,
  22717. array,
  22718. 0
  22719. );
  22720. } else {
  22721. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  22722. const range = updateRanges[ i ];
  22723. device.queue.writeBuffer(
  22724. buffer,
  22725. 0,
  22726. array,
  22727. range.start * array.BYTES_PER_ELEMENT,
  22728. range.count * array.BYTES_PER_ELEMENT
  22729. );
  22730. }
  22731. bufferAttribute.clearUpdateRanges();
  22732. }
  22733. }
  22734. createShaderVertexBuffers( renderObject ) {
  22735. const attributes = renderObject.getAttributes();
  22736. const vertexBuffers = new Map();
  22737. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  22738. const geometryAttribute = attributes[ slot ];
  22739. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  22740. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  22741. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  22742. if ( vertexBufferLayout === undefined ) {
  22743. let arrayStride, stepMode;
  22744. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  22745. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  22746. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  22747. } else {
  22748. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  22749. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  22750. }
  22751. // patch for INT16 and UINT16
  22752. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  22753. arrayStride = 4;
  22754. }
  22755. vertexBufferLayout = {
  22756. arrayStride,
  22757. attributes: [],
  22758. stepMode
  22759. };
  22760. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  22761. }
  22762. const format = this._getVertexFormat( geometryAttribute );
  22763. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  22764. vertexBufferLayout.attributes.push( {
  22765. shaderLocation: slot,
  22766. offset,
  22767. format
  22768. } );
  22769. }
  22770. return Array.from( vertexBuffers.values() );
  22771. }
  22772. destroyAttribute( attribute ) {
  22773. const backend = this.backend;
  22774. const data = backend.get( this._getBufferAttribute( attribute ) );
  22775. data.buffer.destroy();
  22776. backend.delete( attribute );
  22777. }
  22778. async getArrayBufferAsync( attribute ) {
  22779. const backend = this.backend;
  22780. const device = backend.device;
  22781. const data = backend.get( this._getBufferAttribute( attribute ) );
  22782. const bufferGPU = data.buffer;
  22783. const size = bufferGPU.size;
  22784. const readBufferGPU = device.createBuffer( {
  22785. label: attribute.name,
  22786. size,
  22787. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  22788. } );
  22789. const cmdEncoder = device.createCommandEncoder( {} );
  22790. cmdEncoder.copyBufferToBuffer(
  22791. bufferGPU,
  22792. 0,
  22793. readBufferGPU,
  22794. 0,
  22795. size
  22796. );
  22797. readBufferGPU.unmap();
  22798. const gpuCommands = cmdEncoder.finish();
  22799. device.queue.submit( [ gpuCommands ] );
  22800. await readBufferGPU.mapAsync( GPUMapMode.READ );
  22801. const arrayBuffer = readBufferGPU.getMappedRange();
  22802. return arrayBuffer;
  22803. }
  22804. _getVertexFormat( geometryAttribute ) {
  22805. const { itemSize, normalized } = geometryAttribute;
  22806. const ArrayType = geometryAttribute.array.constructor;
  22807. const AttributeType = geometryAttribute.constructor;
  22808. let format;
  22809. if ( itemSize == 1 ) {
  22810. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  22811. } else {
  22812. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  22813. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  22814. if ( prefix ) {
  22815. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  22816. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  22817. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  22818. if ( paddedItemSize % 1 ) {
  22819. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  22820. }
  22821. format = `${prefix}x${paddedItemSize}`;
  22822. }
  22823. }
  22824. if ( ! format ) {
  22825. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  22826. }
  22827. return format;
  22828. }
  22829. _getBufferAttribute( attribute ) {
  22830. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  22831. return attribute;
  22832. }
  22833. }
  22834. class WebGPUBindingUtils {
  22835. constructor( backend ) {
  22836. this.backend = backend;
  22837. this.bindGroupLayoutCache = new WeakMap();
  22838. }
  22839. createBindingsLayout( bindGroup ) {
  22840. const backend = this.backend;
  22841. const device = backend.device;
  22842. const entries = [];
  22843. let index = 0;
  22844. for ( const binding of bindGroup.bindings ) {
  22845. const bindingGPU = {
  22846. binding: index ++,
  22847. visibility: binding.visibility
  22848. };
  22849. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  22850. const buffer = {}; // GPUBufferBindingLayout
  22851. if ( binding.isStorageBuffer ) {
  22852. buffer.type = binding.access;
  22853. }
  22854. bindingGPU.buffer = buffer;
  22855. } else if ( binding.isSampler ) {
  22856. const sampler = {}; // GPUSamplerBindingLayout
  22857. if ( binding.texture.isDepthTexture ) {
  22858. if ( binding.texture.compareFunction !== null ) {
  22859. sampler.type = 'comparison';
  22860. }
  22861. }
  22862. bindingGPU.sampler = sampler;
  22863. } else if ( binding.isSampledTexture && binding.texture.isVideoTexture ) {
  22864. bindingGPU.externalTexture = {}; // GPUExternalTextureBindingLayout
  22865. } else if ( binding.isSampledTexture && binding.store ) {
  22866. const format = this.backend.get( binding.texture ).texture.format;
  22867. const access = binding.access;
  22868. bindingGPU.storageTexture = { format, access }; // GPUStorageTextureBindingLayout
  22869. } else if ( binding.isSampledTexture ) {
  22870. const texture = {}; // GPUTextureBindingLayout
  22871. if ( binding.texture.isMultisampleRenderTargetTexture === true ) {
  22872. texture.multisampled = true;
  22873. }
  22874. if ( binding.texture.isDepthTexture ) {
  22875. texture.sampleType = GPUTextureSampleType.Depth;
  22876. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  22877. const type = binding.texture.type;
  22878. if ( type === IntType ) {
  22879. texture.sampleType = GPUTextureSampleType.SInt;
  22880. } else if ( type === UnsignedIntType ) {
  22881. texture.sampleType = GPUTextureSampleType.UInt;
  22882. } else if ( type === FloatType ) {
  22883. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  22884. texture.sampleType = GPUTextureSampleType.Float;
  22885. } else {
  22886. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  22887. }
  22888. }
  22889. }
  22890. if ( binding.isSampledCubeTexture ) {
  22891. texture.viewDimension = GPUTextureViewDimension.Cube;
  22892. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  22893. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  22894. } else if ( binding.isSampledTexture3D ) {
  22895. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  22896. }
  22897. bindingGPU.texture = texture;
  22898. } else {
  22899. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  22900. }
  22901. entries.push( bindingGPU );
  22902. }
  22903. return device.createBindGroupLayout( { entries } );
  22904. }
  22905. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  22906. const { backend, bindGroupLayoutCache } = this;
  22907. const bindingsData = backend.get( bindGroup );
  22908. // setup (static) binding layout and (dynamic) binding group
  22909. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  22910. if ( bindLayoutGPU === undefined ) {
  22911. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  22912. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  22913. }
  22914. let bindGroupGPU;
  22915. if ( cacheIndex > 0 ) {
  22916. if ( bindingsData.groups === undefined ) {
  22917. bindingsData.groups = [];
  22918. bindingsData.versions = [];
  22919. }
  22920. if ( bindingsData.versions[ cacheIndex ] === version ) {
  22921. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  22922. }
  22923. }
  22924. if ( bindGroupGPU === undefined ) {
  22925. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  22926. if ( cacheIndex > 0 ) {
  22927. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  22928. bindingsData.versions[ cacheIndex ] = version;
  22929. }
  22930. }
  22931. bindingsData.group = bindGroupGPU;
  22932. bindingsData.layout = bindLayoutGPU;
  22933. }
  22934. updateBinding( binding ) {
  22935. const backend = this.backend;
  22936. const device = backend.device;
  22937. const buffer = binding.buffer;
  22938. const bufferGPU = backend.get( binding ).buffer;
  22939. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  22940. }
  22941. createBindGroup( bindGroup, layoutGPU ) {
  22942. const backend = this.backend;
  22943. const device = backend.device;
  22944. let bindingPoint = 0;
  22945. const entriesGPU = [];
  22946. for ( const binding of bindGroup.bindings ) {
  22947. if ( binding.isUniformBuffer ) {
  22948. const bindingData = backend.get( binding );
  22949. if ( bindingData.buffer === undefined ) {
  22950. const byteLength = binding.byteLength;
  22951. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  22952. const bufferGPU = device.createBuffer( {
  22953. label: 'bindingBuffer_' + binding.name,
  22954. size: byteLength,
  22955. usage: usage
  22956. } );
  22957. bindingData.buffer = bufferGPU;
  22958. }
  22959. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  22960. } else if ( binding.isStorageBuffer ) {
  22961. const bindingData = backend.get( binding );
  22962. if ( bindingData.buffer === undefined ) {
  22963. const attribute = binding.attribute;
  22964. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  22965. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  22966. bindingData.buffer = backend.get( attribute ).buffer;
  22967. }
  22968. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  22969. } else if ( binding.isSampler ) {
  22970. const textureGPU = backend.get( binding.texture );
  22971. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  22972. } else if ( binding.isSampledTexture ) {
  22973. const textureData = backend.get( binding.texture );
  22974. let resourceGPU;
  22975. if ( textureData.externalTexture !== undefined ) {
  22976. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  22977. } else {
  22978. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  22979. const propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }-${ mipLevelCount }`;
  22980. resourceGPU = textureData[ propertyName ];
  22981. if ( resourceGPU === undefined ) {
  22982. const aspectGPU = GPUTextureAspect.All;
  22983. let dimensionViewGPU;
  22984. if ( binding.isSampledCubeTexture ) {
  22985. dimensionViewGPU = GPUTextureViewDimension.Cube;
  22986. } else if ( binding.isSampledTexture3D ) {
  22987. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  22988. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  22989. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  22990. } else {
  22991. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  22992. }
  22993. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount } );
  22994. }
  22995. }
  22996. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  22997. }
  22998. bindingPoint ++;
  22999. }
  23000. return device.createBindGroup( {
  23001. label: 'bindGroup_' + bindGroup.name,
  23002. layout: layoutGPU,
  23003. entries: entriesGPU
  23004. } );
  23005. }
  23006. }
  23007. class WebGPUPipelineUtils {
  23008. constructor( backend ) {
  23009. this.backend = backend;
  23010. }
  23011. _getSampleCount( renderObjectContext ) {
  23012. return this.backend.utils.getSampleCountRenderContext( renderObjectContext );
  23013. }
  23014. createRenderPipeline( renderObject, promises ) {
  23015. const { object, material, geometry, pipeline } = renderObject;
  23016. const { vertexProgram, fragmentProgram } = pipeline;
  23017. const backend = this.backend;
  23018. const device = backend.device;
  23019. const utils = backend.utils;
  23020. const pipelineData = backend.get( pipeline );
  23021. // bind group layouts
  23022. const bindGroupLayouts = [];
  23023. for ( const bindGroup of renderObject.getBindings() ) {
  23024. const bindingsData = backend.get( bindGroup );
  23025. bindGroupLayouts.push( bindingsData.layout );
  23026. }
  23027. // vertex buffers
  23028. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  23029. // blending
  23030. let blending;
  23031. if ( material.transparent === true && material.blending !== NoBlending ) {
  23032. blending = this._getBlending( material );
  23033. }
  23034. // stencil
  23035. let stencilFront = {};
  23036. if ( material.stencilWrite === true ) {
  23037. stencilFront = {
  23038. compare: this._getStencilCompare( material ),
  23039. failOp: this._getStencilOperation( material.stencilFail ),
  23040. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  23041. passOp: this._getStencilOperation( material.stencilZPass )
  23042. };
  23043. }
  23044. const colorWriteMask = this._getColorWriteMask( material );
  23045. const targets = [];
  23046. if ( renderObject.context.textures !== null ) {
  23047. const textures = renderObject.context.textures;
  23048. for ( let i = 0; i < textures.length; i ++ ) {
  23049. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  23050. targets.push( {
  23051. format: colorFormat,
  23052. blend: blending,
  23053. writeMask: colorWriteMask
  23054. } );
  23055. }
  23056. } else {
  23057. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  23058. targets.push( {
  23059. format: colorFormat,
  23060. blend: blending,
  23061. writeMask: colorWriteMask
  23062. } );
  23063. }
  23064. const vertexModule = backend.get( vertexProgram ).module;
  23065. const fragmentModule = backend.get( fragmentProgram ).module;
  23066. const primitiveState = this._getPrimitiveState( object, geometry, material );
  23067. const depthCompare = this._getDepthCompare( material );
  23068. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  23069. const sampleCount = this._getSampleCount( renderObject.context );
  23070. const pipelineDescriptor = {
  23071. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  23072. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  23073. fragment: Object.assign( {}, fragmentModule, { targets } ),
  23074. primitive: primitiveState,
  23075. multisample: {
  23076. count: sampleCount,
  23077. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  23078. },
  23079. layout: device.createPipelineLayout( {
  23080. bindGroupLayouts
  23081. } )
  23082. };
  23083. const depthStencil = {};
  23084. const renderDepth = renderObject.context.depth;
  23085. const renderStencil = renderObject.context.stencil;
  23086. if ( renderDepth === true || renderStencil === true ) {
  23087. if ( renderDepth === true ) {
  23088. depthStencil.format = depthStencilFormat;
  23089. depthStencil.depthWriteEnabled = material.depthWrite;
  23090. depthStencil.depthCompare = depthCompare;
  23091. }
  23092. if ( renderStencil === true ) {
  23093. depthStencil.stencilFront = stencilFront;
  23094. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  23095. depthStencil.stencilReadMask = material.stencilFuncMask;
  23096. depthStencil.stencilWriteMask = material.stencilWriteMask;
  23097. }
  23098. pipelineDescriptor.depthStencil = depthStencil;
  23099. }
  23100. if ( promises === null ) {
  23101. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  23102. } else {
  23103. const p = new Promise( ( resolve /*, reject*/ ) => {
  23104. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  23105. pipelineData.pipeline = pipeline;
  23106. resolve();
  23107. } );
  23108. } );
  23109. promises.push( p );
  23110. }
  23111. }
  23112. createBundleEncoder( renderContext ) {
  23113. const backend = this.backend;
  23114. const { utils, device } = backend;
  23115. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  23116. const colorFormat = utils.getCurrentColorFormat( renderContext );
  23117. const sampleCount = this._getSampleCount( renderContext );
  23118. const descriptor = {
  23119. label: 'renderBundleEncoder',
  23120. colorFormats: [ colorFormat ],
  23121. depthStencilFormat,
  23122. sampleCount
  23123. };
  23124. return device.createRenderBundleEncoder( descriptor );
  23125. }
  23126. createComputePipeline( pipeline, bindings ) {
  23127. const backend = this.backend;
  23128. const device = backend.device;
  23129. const computeProgram = backend.get( pipeline.computeProgram ).module;
  23130. const pipelineGPU = backend.get( pipeline );
  23131. // bind group layouts
  23132. const bindGroupLayouts = [];
  23133. for ( const bindingsGroup of bindings ) {
  23134. const bindingsData = backend.get( bindingsGroup );
  23135. bindGroupLayouts.push( bindingsData.layout );
  23136. }
  23137. pipelineGPU.pipeline = device.createComputePipeline( {
  23138. compute: computeProgram,
  23139. layout: device.createPipelineLayout( {
  23140. bindGroupLayouts
  23141. } )
  23142. } );
  23143. }
  23144. _getBlending( material ) {
  23145. let color, alpha;
  23146. const blending = material.blending;
  23147. const blendSrc = material.blendSrc;
  23148. const blendDst = material.blendDst;
  23149. const blendEquation = material.blendEquation;
  23150. if ( blending === CustomBlending ) {
  23151. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  23152. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  23153. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  23154. color = {
  23155. srcFactor: this._getBlendFactor( blendSrc ),
  23156. dstFactor: this._getBlendFactor( blendDst ),
  23157. operation: this._getBlendOperation( blendEquation )
  23158. };
  23159. alpha = {
  23160. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  23161. dstFactor: this._getBlendFactor( blendDstAlpha ),
  23162. operation: this._getBlendOperation( blendEquationAlpha )
  23163. };
  23164. } else {
  23165. const premultipliedAlpha = material.premultipliedAlpha;
  23166. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  23167. color = {
  23168. srcFactor: srcRGB,
  23169. dstFactor: dstRGB,
  23170. operation: GPUBlendOperation.Add
  23171. };
  23172. alpha = {
  23173. srcFactor: srcAlpha,
  23174. dstFactor: dstAlpha,
  23175. operation: GPUBlendOperation.Add
  23176. };
  23177. };
  23178. if ( premultipliedAlpha ) {
  23179. switch ( blending ) {
  23180. case NormalBlending:
  23181. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  23182. break;
  23183. case AdditiveBlending:
  23184. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  23185. break;
  23186. case SubtractiveBlending:
  23187. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  23188. break;
  23189. case MultiplyBlending:
  23190. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.SrcAlpha );
  23191. break;
  23192. }
  23193. } else {
  23194. switch ( blending ) {
  23195. case NormalBlending:
  23196. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  23197. break;
  23198. case AdditiveBlending:
  23199. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.SrcAlpha, GPUBlendFactor.One );
  23200. break;
  23201. case SubtractiveBlending:
  23202. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  23203. break;
  23204. case MultiplyBlending:
  23205. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.Src );
  23206. break;
  23207. }
  23208. }
  23209. }
  23210. if ( color !== undefined && alpha !== undefined ) {
  23211. return { color, alpha };
  23212. } else {
  23213. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  23214. }
  23215. }
  23216. _getBlendFactor( blend ) {
  23217. let blendFactor;
  23218. switch ( blend ) {
  23219. case ZeroFactor:
  23220. blendFactor = GPUBlendFactor.Zero;
  23221. break;
  23222. case OneFactor:
  23223. blendFactor = GPUBlendFactor.One;
  23224. break;
  23225. case SrcColorFactor:
  23226. blendFactor = GPUBlendFactor.Src;
  23227. break;
  23228. case OneMinusSrcColorFactor:
  23229. blendFactor = GPUBlendFactor.OneMinusSrc;
  23230. break;
  23231. case SrcAlphaFactor:
  23232. blendFactor = GPUBlendFactor.SrcAlpha;
  23233. break;
  23234. case OneMinusSrcAlphaFactor:
  23235. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  23236. break;
  23237. case DstColorFactor:
  23238. blendFactor = GPUBlendFactor.Dst;
  23239. break;
  23240. case OneMinusDstColorFactor:
  23241. blendFactor = GPUBlendFactor.OneMinusDstColor;
  23242. break;
  23243. case DstAlphaFactor:
  23244. blendFactor = GPUBlendFactor.DstAlpha;
  23245. break;
  23246. case OneMinusDstAlphaFactor:
  23247. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  23248. break;
  23249. case SrcAlphaSaturateFactor:
  23250. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  23251. break;
  23252. case BlendColorFactor:
  23253. blendFactor = GPUBlendFactor.Constant;
  23254. break;
  23255. case OneMinusBlendColorFactor:
  23256. blendFactor = GPUBlendFactor.OneMinusConstant;
  23257. break;
  23258. default:
  23259. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  23260. }
  23261. return blendFactor;
  23262. }
  23263. _getStencilCompare( material ) {
  23264. let stencilCompare;
  23265. const stencilFunc = material.stencilFunc;
  23266. switch ( stencilFunc ) {
  23267. case NeverStencilFunc:
  23268. stencilCompare = GPUCompareFunction.Never;
  23269. break;
  23270. case AlwaysStencilFunc:
  23271. stencilCompare = GPUCompareFunction.Always;
  23272. break;
  23273. case LessStencilFunc:
  23274. stencilCompare = GPUCompareFunction.Less;
  23275. break;
  23276. case LessEqualStencilFunc:
  23277. stencilCompare = GPUCompareFunction.LessEqual;
  23278. break;
  23279. case EqualStencilFunc:
  23280. stencilCompare = GPUCompareFunction.Equal;
  23281. break;
  23282. case GreaterEqualStencilFunc:
  23283. stencilCompare = GPUCompareFunction.GreaterEqual;
  23284. break;
  23285. case GreaterStencilFunc:
  23286. stencilCompare = GPUCompareFunction.Greater;
  23287. break;
  23288. case NotEqualStencilFunc:
  23289. stencilCompare = GPUCompareFunction.NotEqual;
  23290. break;
  23291. default:
  23292. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  23293. }
  23294. return stencilCompare;
  23295. }
  23296. _getStencilOperation( op ) {
  23297. let stencilOperation;
  23298. switch ( op ) {
  23299. case KeepStencilOp:
  23300. stencilOperation = GPUStencilOperation.Keep;
  23301. break;
  23302. case ZeroStencilOp:
  23303. stencilOperation = GPUStencilOperation.Zero;
  23304. break;
  23305. case ReplaceStencilOp:
  23306. stencilOperation = GPUStencilOperation.Replace;
  23307. break;
  23308. case InvertStencilOp:
  23309. stencilOperation = GPUStencilOperation.Invert;
  23310. break;
  23311. case IncrementStencilOp:
  23312. stencilOperation = GPUStencilOperation.IncrementClamp;
  23313. break;
  23314. case DecrementStencilOp:
  23315. stencilOperation = GPUStencilOperation.DecrementClamp;
  23316. break;
  23317. case IncrementWrapStencilOp:
  23318. stencilOperation = GPUStencilOperation.IncrementWrap;
  23319. break;
  23320. case DecrementWrapStencilOp:
  23321. stencilOperation = GPUStencilOperation.DecrementWrap;
  23322. break;
  23323. default:
  23324. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  23325. }
  23326. return stencilOperation;
  23327. }
  23328. _getBlendOperation( blendEquation ) {
  23329. let blendOperation;
  23330. switch ( blendEquation ) {
  23331. case AddEquation:
  23332. blendOperation = GPUBlendOperation.Add;
  23333. break;
  23334. case SubtractEquation:
  23335. blendOperation = GPUBlendOperation.Subtract;
  23336. break;
  23337. case ReverseSubtractEquation:
  23338. blendOperation = GPUBlendOperation.ReverseSubtract;
  23339. break;
  23340. case MinEquation:
  23341. blendOperation = GPUBlendOperation.Min;
  23342. break;
  23343. case MaxEquation:
  23344. blendOperation = GPUBlendOperation.Max;
  23345. break;
  23346. default:
  23347. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  23348. }
  23349. return blendOperation;
  23350. }
  23351. _getPrimitiveState( object, geometry, material ) {
  23352. const descriptor = {};
  23353. const utils = this.backend.utils;
  23354. descriptor.topology = utils.getPrimitiveTopology( object, material );
  23355. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  23356. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  23357. }
  23358. switch ( material.side ) {
  23359. case FrontSide:
  23360. descriptor.frontFace = GPUFrontFace.CCW;
  23361. descriptor.cullMode = GPUCullMode.Back;
  23362. break;
  23363. case BackSide:
  23364. descriptor.frontFace = GPUFrontFace.CCW;
  23365. descriptor.cullMode = GPUCullMode.Front;
  23366. break;
  23367. case DoubleSide:
  23368. descriptor.frontFace = GPUFrontFace.CCW;
  23369. descriptor.cullMode = GPUCullMode.None;
  23370. break;
  23371. default:
  23372. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  23373. break;
  23374. }
  23375. return descriptor;
  23376. }
  23377. _getColorWriteMask( material ) {
  23378. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  23379. }
  23380. _getDepthCompare( material ) {
  23381. let depthCompare;
  23382. if ( material.depthTest === false ) {
  23383. depthCompare = GPUCompareFunction.Always;
  23384. } else {
  23385. const depthFunc = material.depthFunc;
  23386. switch ( depthFunc ) {
  23387. case NeverDepth:
  23388. depthCompare = GPUCompareFunction.Never;
  23389. break;
  23390. case AlwaysDepth:
  23391. depthCompare = GPUCompareFunction.Always;
  23392. break;
  23393. case LessDepth:
  23394. depthCompare = GPUCompareFunction.Less;
  23395. break;
  23396. case LessEqualDepth:
  23397. depthCompare = GPUCompareFunction.LessEqual;
  23398. break;
  23399. case EqualDepth:
  23400. depthCompare = GPUCompareFunction.Equal;
  23401. break;
  23402. case GreaterEqualDepth:
  23403. depthCompare = GPUCompareFunction.GreaterEqual;
  23404. break;
  23405. case GreaterDepth:
  23406. depthCompare = GPUCompareFunction.Greater;
  23407. break;
  23408. case NotEqualDepth:
  23409. depthCompare = GPUCompareFunction.NotEqual;
  23410. break;
  23411. default:
  23412. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  23413. }
  23414. }
  23415. return depthCompare;
  23416. }
  23417. }
  23418. /*// debugger tools
  23419. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  23420. //*/
  23421. //
  23422. class WebGPUBackend extends Backend {
  23423. constructor( parameters = {} ) {
  23424. super( parameters );
  23425. this.isWebGPUBackend = true;
  23426. // some parameters require default values other than "undefined"
  23427. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  23428. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  23429. this.trackTimestamp = ( parameters.trackTimestamp === true );
  23430. this.device = null;
  23431. this.context = null;
  23432. this.colorBuffer = null;
  23433. this.defaultRenderPassdescriptor = null;
  23434. this.utils = new WebGPUUtils( this );
  23435. this.attributeUtils = new WebGPUAttributeUtils( this );
  23436. this.bindingUtils = new WebGPUBindingUtils( this );
  23437. this.pipelineUtils = new WebGPUPipelineUtils( this );
  23438. this.textureUtils = new WebGPUTextureUtils( this );
  23439. this.occludedResolveCache = new Map();
  23440. }
  23441. async init( renderer ) {
  23442. await super.init( renderer );
  23443. //
  23444. const parameters = this.parameters;
  23445. // create the device if it is not passed with parameters
  23446. let device;
  23447. if ( parameters.device === undefined ) {
  23448. const adapterOptions = {
  23449. powerPreference: parameters.powerPreference
  23450. };
  23451. const adapter = await navigator.gpu.requestAdapter( adapterOptions );
  23452. if ( adapter === null ) {
  23453. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  23454. }
  23455. // feature support
  23456. const features = Object.values( GPUFeatureName );
  23457. const supportedFeatures = [];
  23458. for ( const name of features ) {
  23459. if ( adapter.features.has( name ) ) {
  23460. supportedFeatures.push( name );
  23461. }
  23462. }
  23463. const deviceDescriptor = {
  23464. requiredFeatures: supportedFeatures,
  23465. requiredLimits: parameters.requiredLimits
  23466. };
  23467. device = await adapter.requestDevice( deviceDescriptor );
  23468. } else {
  23469. device = parameters.device;
  23470. }
  23471. device.lost.then( ( info ) => {
  23472. const deviceLossInfo = {
  23473. api: 'WebGPU',
  23474. message: info.message || 'Unknown reason',
  23475. reason: info.reason || null,
  23476. originalEvent: info
  23477. };
  23478. renderer.onDeviceLost( deviceLossInfo );
  23479. } );
  23480. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  23481. this.device = device;
  23482. this.context = context;
  23483. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  23484. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  23485. this.context.configure( {
  23486. device: this.device,
  23487. format: this.utils.getPreferredCanvasFormat(),
  23488. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  23489. alphaMode: alphaMode
  23490. } );
  23491. this.updateSize();
  23492. }
  23493. get coordinateSystem() {
  23494. return WebGPUCoordinateSystem;
  23495. }
  23496. async getArrayBufferAsync( attribute ) {
  23497. return await this.attributeUtils.getArrayBufferAsync( attribute );
  23498. }
  23499. getContext() {
  23500. return this.context;
  23501. }
  23502. _getDefaultRenderPassDescriptor() {
  23503. let descriptor = this.defaultRenderPassdescriptor;
  23504. if ( descriptor === null ) {
  23505. const renderer = this.renderer;
  23506. descriptor = {
  23507. colorAttachments: [ {
  23508. view: null
  23509. } ],
  23510. };
  23511. if ( this.renderer.depth === true || this.renderer.stencil === true ) {
  23512. descriptor.depthStencilAttachment = {
  23513. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  23514. };
  23515. }
  23516. const colorAttachment = descriptor.colorAttachments[ 0 ];
  23517. if ( this.renderer.samples > 0 ) {
  23518. colorAttachment.view = this.colorBuffer.createView();
  23519. } else {
  23520. colorAttachment.resolveTarget = undefined;
  23521. }
  23522. this.defaultRenderPassdescriptor = descriptor;
  23523. }
  23524. const colorAttachment = descriptor.colorAttachments[ 0 ];
  23525. if ( this.renderer.samples > 0 ) {
  23526. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  23527. } else {
  23528. colorAttachment.view = this.context.getCurrentTexture().createView();
  23529. }
  23530. return descriptor;
  23531. }
  23532. _getRenderPassDescriptor( renderContext ) {
  23533. const renderTarget = renderContext.renderTarget;
  23534. const renderTargetData = this.get( renderTarget );
  23535. let descriptors = renderTargetData.descriptors;
  23536. if ( descriptors === undefined ||
  23537. renderTargetData.width !== renderTarget.width ||
  23538. renderTargetData.height !== renderTarget.height ||
  23539. renderTargetData.activeMipmapLevel !== renderTarget.activeMipmapLevel ||
  23540. renderTargetData.samples !== renderTarget.samples
  23541. ) {
  23542. descriptors = {};
  23543. renderTargetData.descriptors = descriptors;
  23544. // dispose
  23545. const onDispose = () => {
  23546. renderTarget.removeEventListener( 'dispose', onDispose );
  23547. this.delete( renderTarget );
  23548. };
  23549. renderTarget.addEventListener( 'dispose', onDispose );
  23550. }
  23551. const cacheKey = renderContext.getCacheKey();
  23552. let descriptor = descriptors[ cacheKey ];
  23553. if ( descriptor === undefined ) {
  23554. const textures = renderContext.textures;
  23555. const colorAttachments = [];
  23556. for ( let i = 0; i < textures.length; i ++ ) {
  23557. const textureData = this.get( textures[ i ] );
  23558. const textureView = textureData.texture.createView( {
  23559. baseMipLevel: renderContext.activeMipmapLevel,
  23560. mipLevelCount: 1,
  23561. baseArrayLayer: renderContext.activeCubeFace,
  23562. dimension: GPUTextureViewDimension.TwoD
  23563. } );
  23564. let view, resolveTarget;
  23565. if ( textureData.msaaTexture !== undefined ) {
  23566. view = textureData.msaaTexture.createView();
  23567. resolveTarget = textureView;
  23568. } else {
  23569. view = textureView;
  23570. resolveTarget = undefined;
  23571. }
  23572. colorAttachments.push( {
  23573. view,
  23574. resolveTarget,
  23575. loadOp: GPULoadOp.Load,
  23576. storeOp: GPUStoreOp.Store
  23577. } );
  23578. }
  23579. descriptor = {
  23580. colorAttachments,
  23581. };
  23582. if ( renderContext.depth ) {
  23583. const depthTextureData = this.get( renderContext.depthTexture );
  23584. const depthStencilAttachment = {
  23585. view: depthTextureData.texture.createView()
  23586. };
  23587. descriptor.depthStencilAttachment = depthStencilAttachment;
  23588. }
  23589. descriptors[ cacheKey ] = descriptor;
  23590. renderTargetData.width = renderTarget.width;
  23591. renderTargetData.height = renderTarget.height;
  23592. renderTargetData.samples = renderTarget.samples;
  23593. renderTargetData.activeMipmapLevel = renderTarget.activeMipmapLevel;
  23594. }
  23595. return descriptor;
  23596. }
  23597. beginRender( renderContext ) {
  23598. const renderContextData = this.get( renderContext );
  23599. const device = this.device;
  23600. const occlusionQueryCount = renderContext.occlusionQueryCount;
  23601. let occlusionQuerySet;
  23602. if ( occlusionQueryCount > 0 ) {
  23603. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  23604. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  23605. // Get a reference to the array of objects with queries. The renderContextData property
  23606. // can be changed by another render pass before the buffer.mapAsyc() completes.
  23607. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  23608. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  23609. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  23610. //
  23611. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  23612. renderContextData.occlusionQuerySet = occlusionQuerySet;
  23613. renderContextData.occlusionQueryIndex = 0;
  23614. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  23615. renderContextData.lastOcclusionObject = null;
  23616. }
  23617. let descriptor;
  23618. if ( renderContext.textures === null ) {
  23619. descriptor = this._getDefaultRenderPassDescriptor();
  23620. } else {
  23621. descriptor = this._getRenderPassDescriptor( renderContext );
  23622. }
  23623. this.initTimestampQuery( renderContext, descriptor );
  23624. descriptor.occlusionQuerySet = occlusionQuerySet;
  23625. const depthStencilAttachment = descriptor.depthStencilAttachment;
  23626. if ( renderContext.textures !== null ) {
  23627. const colorAttachments = descriptor.colorAttachments;
  23628. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  23629. const colorAttachment = colorAttachments[ i ];
  23630. if ( renderContext.clearColor ) {
  23631. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  23632. colorAttachment.loadOp = GPULoadOp.Clear;
  23633. colorAttachment.storeOp = GPUStoreOp.Store;
  23634. } else {
  23635. colorAttachment.loadOp = GPULoadOp.Load;
  23636. colorAttachment.storeOp = GPUStoreOp.Store;
  23637. }
  23638. }
  23639. } else {
  23640. const colorAttachment = descriptor.colorAttachments[ 0 ];
  23641. if ( renderContext.clearColor ) {
  23642. colorAttachment.clearValue = renderContext.clearColorValue;
  23643. colorAttachment.loadOp = GPULoadOp.Clear;
  23644. colorAttachment.storeOp = GPUStoreOp.Store;
  23645. } else {
  23646. colorAttachment.loadOp = GPULoadOp.Load;
  23647. colorAttachment.storeOp = GPUStoreOp.Store;
  23648. }
  23649. }
  23650. //
  23651. if ( renderContext.depth ) {
  23652. if ( renderContext.clearDepth ) {
  23653. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  23654. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  23655. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  23656. } else {
  23657. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  23658. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  23659. }
  23660. }
  23661. if ( renderContext.stencil ) {
  23662. if ( renderContext.clearStencil ) {
  23663. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  23664. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  23665. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  23666. } else {
  23667. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  23668. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  23669. }
  23670. }
  23671. //
  23672. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  23673. const currentPass = encoder.beginRenderPass( descriptor );
  23674. //
  23675. renderContextData.descriptor = descriptor;
  23676. renderContextData.encoder = encoder;
  23677. renderContextData.currentPass = currentPass;
  23678. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  23679. renderContextData.renderBundles = [];
  23680. //
  23681. if ( renderContext.viewport ) {
  23682. this.updateViewport( renderContext );
  23683. }
  23684. if ( renderContext.scissor ) {
  23685. const { x, y, width, height } = renderContext.scissorValue;
  23686. currentPass.setScissorRect( x, y, width, height );
  23687. }
  23688. }
  23689. finishRender( renderContext ) {
  23690. const renderContextData = this.get( renderContext );
  23691. const occlusionQueryCount = renderContext.occlusionQueryCount;
  23692. if ( renderContextData.renderBundles.length > 0 ) {
  23693. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  23694. }
  23695. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  23696. renderContextData.currentPass.endOcclusionQuery();
  23697. }
  23698. renderContextData.currentPass.end();
  23699. if ( occlusionQueryCount > 0 ) {
  23700. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  23701. //
  23702. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  23703. if ( queryResolveBuffer === undefined ) {
  23704. queryResolveBuffer = this.device.createBuffer(
  23705. {
  23706. size: bufferSize,
  23707. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  23708. }
  23709. );
  23710. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  23711. }
  23712. //
  23713. const readBuffer = this.device.createBuffer(
  23714. {
  23715. size: bufferSize,
  23716. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  23717. }
  23718. );
  23719. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  23720. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  23721. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  23722. renderContextData.occlusionQueryBuffer = readBuffer;
  23723. //
  23724. this.resolveOccludedAsync( renderContext );
  23725. }
  23726. this.prepareTimestampBuffer( renderContext, renderContextData.encoder );
  23727. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  23728. //
  23729. if ( renderContext.textures !== null ) {
  23730. const textures = renderContext.textures;
  23731. for ( let i = 0; i < textures.length; i ++ ) {
  23732. const texture = textures[ i ];
  23733. if ( texture.generateMipmaps === true ) {
  23734. this.textureUtils.generateMipmaps( texture );
  23735. }
  23736. }
  23737. }
  23738. }
  23739. isOccluded( renderContext, object ) {
  23740. const renderContextData = this.get( renderContext );
  23741. return renderContextData.occluded && renderContextData.occluded.has( object );
  23742. }
  23743. async resolveOccludedAsync( renderContext ) {
  23744. const renderContextData = this.get( renderContext );
  23745. // handle occlusion query results
  23746. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  23747. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  23748. const occluded = new WeakSet();
  23749. renderContextData.currentOcclusionQueryObjects = null;
  23750. renderContextData.currentOcclusionQueryBuffer = null;
  23751. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  23752. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  23753. const results = new BigUint64Array( buffer );
  23754. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  23755. if ( results[ i ] !== BigInt( 0 ) ) {
  23756. occluded.add( currentOcclusionQueryObjects[ i ] );
  23757. }
  23758. }
  23759. currentOcclusionQueryBuffer.destroy();
  23760. renderContextData.occluded = occluded;
  23761. }
  23762. }
  23763. updateViewport( renderContext ) {
  23764. const { currentPass } = this.get( renderContext );
  23765. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  23766. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  23767. }
  23768. clear( color, depth, stencil, renderTargetData = null ) {
  23769. const device = this.device;
  23770. const renderer = this.renderer;
  23771. let colorAttachments = [];
  23772. let depthStencilAttachment;
  23773. let clearValue;
  23774. let supportsDepth;
  23775. let supportsStencil;
  23776. if ( color ) {
  23777. const clearColor = this.getClearColor();
  23778. if ( this.renderer.alpha === true ) {
  23779. // premultiply alpha
  23780. const a = clearColor.a;
  23781. clearValue = { r: clearColor.r * a, g: clearColor.g * a, b: clearColor.b * a, a: a };
  23782. } else {
  23783. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  23784. }
  23785. }
  23786. if ( renderTargetData === null ) {
  23787. supportsDepth = renderer.depth;
  23788. supportsStencil = renderer.stencil;
  23789. const descriptor = this._getDefaultRenderPassDescriptor();
  23790. if ( color ) {
  23791. colorAttachments = descriptor.colorAttachments;
  23792. const colorAttachment = colorAttachments[ 0 ];
  23793. colorAttachment.clearValue = clearValue;
  23794. colorAttachment.loadOp = GPULoadOp.Clear;
  23795. colorAttachment.storeOp = GPUStoreOp.Store;
  23796. }
  23797. if ( supportsDepth || supportsStencil ) {
  23798. depthStencilAttachment = descriptor.depthStencilAttachment;
  23799. }
  23800. } else {
  23801. supportsDepth = renderTargetData.depth;
  23802. supportsStencil = renderTargetData.stencil;
  23803. if ( color ) {
  23804. for ( const texture of renderTargetData.textures ) {
  23805. const textureData = this.get( texture );
  23806. const textureView = textureData.texture.createView();
  23807. let view, resolveTarget;
  23808. if ( textureData.msaaTexture !== undefined ) {
  23809. view = textureData.msaaTexture.createView();
  23810. resolveTarget = textureView;
  23811. } else {
  23812. view = textureView;
  23813. resolveTarget = undefined;
  23814. }
  23815. colorAttachments.push( {
  23816. view,
  23817. resolveTarget,
  23818. clearValue,
  23819. loadOp: GPULoadOp.Clear,
  23820. storeOp: GPUStoreOp.Store
  23821. } );
  23822. }
  23823. }
  23824. if ( supportsDepth || supportsStencil ) {
  23825. const depthTextureData = this.get( renderTargetData.depthTexture );
  23826. depthStencilAttachment = {
  23827. view: depthTextureData.texture.createView()
  23828. };
  23829. }
  23830. }
  23831. //
  23832. if ( supportsDepth ) {
  23833. if ( depth ) {
  23834. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  23835. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  23836. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  23837. } else {
  23838. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  23839. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  23840. }
  23841. }
  23842. //
  23843. if ( supportsStencil ) {
  23844. if ( stencil ) {
  23845. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  23846. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  23847. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  23848. } else {
  23849. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  23850. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  23851. }
  23852. }
  23853. //
  23854. const encoder = device.createCommandEncoder( {} );
  23855. const currentPass = encoder.beginRenderPass( {
  23856. colorAttachments,
  23857. depthStencilAttachment
  23858. } );
  23859. currentPass.end();
  23860. device.queue.submit( [ encoder.finish() ] );
  23861. }
  23862. // compute
  23863. beginCompute( computeGroup ) {
  23864. const groupGPU = this.get( computeGroup );
  23865. const descriptor = {};
  23866. this.initTimestampQuery( computeGroup, descriptor );
  23867. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder();
  23868. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  23869. }
  23870. compute( computeGroup, computeNode, bindings, pipeline ) {
  23871. const { passEncoderGPU } = this.get( computeGroup );
  23872. // pipeline
  23873. const pipelineGPU = this.get( pipeline ).pipeline;
  23874. passEncoderGPU.setPipeline( pipelineGPU );
  23875. // bind groups
  23876. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  23877. const bindGroup = bindings[ i ];
  23878. const bindingsData = this.get( bindGroup );
  23879. passEncoderGPU.setBindGroup( i, bindingsData.group );
  23880. }
  23881. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  23882. const computeNodeData = this.get( computeNode );
  23883. if ( computeNodeData.dispatchSize === undefined ) computeNodeData.dispatchSize = { x: 0, y: 1, z: 1 };
  23884. const { dispatchSize } = computeNodeData;
  23885. if ( computeNode.dispatchCount > maxComputeWorkgroupsPerDimension ) {
  23886. dispatchSize.x = Math.min( computeNode.dispatchCount, maxComputeWorkgroupsPerDimension );
  23887. dispatchSize.y = Math.ceil( computeNode.dispatchCount / maxComputeWorkgroupsPerDimension );
  23888. } else {
  23889. dispatchSize.x = computeNode.dispatchCount;
  23890. }
  23891. passEncoderGPU.dispatchWorkgroups(
  23892. dispatchSize.x,
  23893. dispatchSize.y,
  23894. dispatchSize.z
  23895. );
  23896. }
  23897. finishCompute( computeGroup ) {
  23898. const groupData = this.get( computeGroup );
  23899. groupData.passEncoderGPU.end();
  23900. this.prepareTimestampBuffer( computeGroup, groupData.cmdEncoderGPU );
  23901. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  23902. }
  23903. async waitForGPU() {
  23904. await this.device.queue.onSubmittedWorkDone();
  23905. }
  23906. // render object
  23907. draw( renderObject, info ) {
  23908. const { object, context, pipeline } = renderObject;
  23909. const bindings = renderObject.getBindings();
  23910. const renderContextData = this.get( context );
  23911. const pipelineGPU = this.get( pipeline ).pipeline;
  23912. const currentSets = renderContextData.currentSets;
  23913. const passEncoderGPU = renderContextData.currentPass;
  23914. const drawParams = renderObject.getDrawParameters();
  23915. if ( drawParams === null ) return;
  23916. // pipeline
  23917. if ( currentSets.pipeline !== pipelineGPU ) {
  23918. passEncoderGPU.setPipeline( pipelineGPU );
  23919. currentSets.pipeline = pipelineGPU;
  23920. }
  23921. // bind groups
  23922. const currentBindingGroups = currentSets.bindingGroups;
  23923. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  23924. const bindGroup = bindings[ i ];
  23925. const bindingsData = this.get( bindGroup );
  23926. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  23927. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  23928. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  23929. }
  23930. }
  23931. // attributes
  23932. const index = renderObject.getIndex();
  23933. const hasIndex = ( index !== null );
  23934. // index
  23935. if ( hasIndex === true ) {
  23936. if ( currentSets.index !== index ) {
  23937. const buffer = this.get( index ).buffer;
  23938. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  23939. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  23940. currentSets.index = index;
  23941. }
  23942. }
  23943. // vertex buffers
  23944. const vertexBuffers = renderObject.getVertexBuffers();
  23945. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  23946. const vertexBuffer = vertexBuffers[ i ];
  23947. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  23948. const buffer = this.get( vertexBuffer ).buffer;
  23949. passEncoderGPU.setVertexBuffer( i, buffer );
  23950. currentSets.attributes[ i ] = vertexBuffer;
  23951. }
  23952. }
  23953. // occlusion queries - handle multiple consecutive draw calls for an object
  23954. if ( renderContextData.occlusionQuerySet !== undefined ) {
  23955. const lastObject = renderContextData.lastOcclusionObject;
  23956. if ( lastObject !== object ) {
  23957. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  23958. passEncoderGPU.endOcclusionQuery();
  23959. renderContextData.occlusionQueryIndex ++;
  23960. }
  23961. if ( object.occlusionTest === true ) {
  23962. passEncoderGPU.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  23963. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  23964. }
  23965. renderContextData.lastOcclusionObject = object;
  23966. }
  23967. }
  23968. // draw
  23969. if ( object.isBatchedMesh === true ) {
  23970. const starts = object._multiDrawStarts;
  23971. const counts = object._multiDrawCounts;
  23972. const drawCount = object._multiDrawCount;
  23973. const drawInstances = object._multiDrawInstances;
  23974. const bytesPerElement = hasIndex ? index.array.BYTES_PER_ELEMENT : 1;
  23975. for ( let i = 0; i < drawCount; i ++ ) {
  23976. const count = drawInstances ? drawInstances[ i ] : 1;
  23977. const firstInstance = count > 1 ? 0 : i;
  23978. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / bytesPerElement, 0, firstInstance );
  23979. }
  23980. } else if ( hasIndex === true ) {
  23981. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  23982. const indirect = renderObject.getIndirect();
  23983. if ( indirect !== null ) {
  23984. const buffer = this.get( indirect ).buffer;
  23985. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  23986. } else {
  23987. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  23988. }
  23989. info.update( object, indexCount, instanceCount );
  23990. } else {
  23991. const { vertexCount, instanceCount, firstVertex } = drawParams;
  23992. const indirect = renderObject.getIndirect();
  23993. if ( indirect !== null ) {
  23994. const buffer = this.get( indirect ).buffer;
  23995. passEncoderGPU.drawIndirect( buffer, 0 );
  23996. } else {
  23997. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  23998. }
  23999. info.update( object, vertexCount, instanceCount );
  24000. }
  24001. }
  24002. // cache key
  24003. needsRenderUpdate( renderObject ) {
  24004. const data = this.get( renderObject );
  24005. const { object, material } = renderObject;
  24006. const utils = this.utils;
  24007. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  24008. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  24009. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  24010. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  24011. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  24012. let needsUpdate = false;
  24013. if ( data.material !== material || data.materialVersion !== material.version ||
  24014. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  24015. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  24016. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  24017. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  24018. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  24019. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  24020. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  24021. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  24022. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  24023. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  24024. data.primitiveTopology !== primitiveTopology ||
  24025. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  24026. ) {
  24027. data.material = material; data.materialVersion = material.version;
  24028. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  24029. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  24030. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  24031. data.colorWrite = material.colorWrite;
  24032. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  24033. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  24034. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  24035. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  24036. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  24037. data.sampleCount = sampleCount;
  24038. data.colorSpace = colorSpace;
  24039. data.colorFormat = colorFormat;
  24040. data.depthStencilFormat = depthStencilFormat;
  24041. data.primitiveTopology = primitiveTopology;
  24042. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  24043. needsUpdate = true;
  24044. }
  24045. return needsUpdate;
  24046. }
  24047. getRenderCacheKey( renderObject ) {
  24048. const { object, material } = renderObject;
  24049. const utils = this.utils;
  24050. const renderContext = renderObject.context;
  24051. return [
  24052. material.transparent, material.blending, material.premultipliedAlpha,
  24053. material.blendSrc, material.blendDst, material.blendEquation,
  24054. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  24055. material.colorWrite,
  24056. material.depthWrite, material.depthTest, material.depthFunc,
  24057. material.stencilWrite, material.stencilFunc,
  24058. material.stencilFail, material.stencilZFail, material.stencilZPass,
  24059. material.stencilFuncMask, material.stencilWriteMask,
  24060. material.side,
  24061. utils.getSampleCountRenderContext( renderContext ),
  24062. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  24063. utils.getPrimitiveTopology( object, material ),
  24064. renderObject.getGeometryCacheKey(),
  24065. renderObject.clippingContextCacheKey
  24066. ].join();
  24067. }
  24068. // textures
  24069. createSampler( texture ) {
  24070. this.textureUtils.createSampler( texture );
  24071. }
  24072. destroySampler( texture ) {
  24073. this.textureUtils.destroySampler( texture );
  24074. }
  24075. createDefaultTexture( texture ) {
  24076. this.textureUtils.createDefaultTexture( texture );
  24077. }
  24078. createTexture( texture, options ) {
  24079. this.textureUtils.createTexture( texture, options );
  24080. }
  24081. updateTexture( texture, options ) {
  24082. this.textureUtils.updateTexture( texture, options );
  24083. }
  24084. generateMipmaps( texture ) {
  24085. this.textureUtils.generateMipmaps( texture );
  24086. }
  24087. destroyTexture( texture ) {
  24088. this.textureUtils.destroyTexture( texture );
  24089. }
  24090. copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  24091. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  24092. }
  24093. async initTimestampQuery( renderContext, descriptor ) {
  24094. if ( ! this.trackTimestamp ) return;
  24095. const renderContextData = this.get( renderContext );
  24096. if ( ! renderContextData.timeStampQuerySet ) {
  24097. // Push an error scope to catch any errors during query set creation
  24098. this.device.pushErrorScope( 'out-of-memory' );
  24099. const timeStampQuerySet = await this.device.createQuerySet( { type: 'timestamp', count: 2, label: `timestamp_renderContext_${renderContext.id}` } );
  24100. // Pop the error scope and check for errors
  24101. const error = await this.device.popErrorScope();
  24102. if ( error ) {
  24103. if ( ! renderContextData.attemptingTimeStampQuerySetFailed ) {
  24104. console.error( `[GPUOutOfMemoryError][renderContext_${renderContext.id}]:\nFailed to create timestamp query set. This may be because timestamp queries are already running in other tabs.` );
  24105. renderContextData.attemptingTimeStampQuerySetFailed = true;
  24106. }
  24107. renderContextData.timeStampQuerySet = null; // Mark as unavailable
  24108. return;
  24109. }
  24110. const timestampWrites = {
  24111. querySet: timeStampQuerySet,
  24112. beginningOfPassWriteIndex: 0, // Write timestamp in index 0 when pass begins.
  24113. endOfPassWriteIndex: 1, // Write timestamp in index 1 when pass ends.
  24114. };
  24115. Object.assign( descriptor, { timestampWrites } );
  24116. renderContextData.timeStampQuerySet = timeStampQuerySet;
  24117. }
  24118. }
  24119. // timestamp utils
  24120. prepareTimestampBuffer( renderContext, encoder ) {
  24121. if ( ! this.trackTimestamp ) return;
  24122. const renderContextData = this.get( renderContext );
  24123. if ( ! renderContextData.timeStampQuerySet ) return;
  24124. const size = 2 * BigInt64Array.BYTES_PER_ELEMENT;
  24125. if ( renderContextData.currentTimestampQueryBuffers === undefined ) {
  24126. renderContextData.currentTimestampQueryBuffers = {
  24127. resolveBuffer: this.device.createBuffer( {
  24128. label: 'timestamp resolve buffer',
  24129. size: size,
  24130. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC,
  24131. } ),
  24132. resultBuffer: this.device.createBuffer( {
  24133. label: 'timestamp result buffer',
  24134. size: size,
  24135. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
  24136. } ),
  24137. isMappingPending: false,
  24138. };
  24139. }
  24140. const { resolveBuffer, resultBuffer, isMappingPending } = renderContextData.currentTimestampQueryBuffers;
  24141. if ( isMappingPending === true ) return;
  24142. encoder.resolveQuerySet( renderContextData.timeStampQuerySet, 0, 2, resolveBuffer, 0 );
  24143. encoder.copyBufferToBuffer( resolveBuffer, 0, resultBuffer, 0, size );
  24144. }
  24145. async resolveTimestampAsync( renderContext, type = 'render' ) {
  24146. if ( ! this.trackTimestamp ) return;
  24147. const renderContextData = this.get( renderContext );
  24148. if ( ! renderContextData.timeStampQuerySet ) return;
  24149. if ( renderContextData.currentTimestampQueryBuffers === undefined ) return;
  24150. const { resultBuffer, isMappingPending } = renderContextData.currentTimestampQueryBuffers;
  24151. if ( isMappingPending === true ) return;
  24152. renderContextData.currentTimestampQueryBuffers.isMappingPending = true;
  24153. resultBuffer.mapAsync( GPUMapMode.READ ).then( () => {
  24154. const times = new BigUint64Array( resultBuffer.getMappedRange() );
  24155. const duration = Number( times[ 1 ] - times[ 0 ] ) / 1000000;
  24156. this.renderer.info.updateTimestamp( type, duration );
  24157. resultBuffer.unmap();
  24158. renderContextData.currentTimestampQueryBuffers.isMappingPending = false;
  24159. } );
  24160. }
  24161. // node builder
  24162. createNodeBuilder( object, renderer ) {
  24163. return new WGSLNodeBuilder( object, renderer );
  24164. }
  24165. // program
  24166. createProgram( program ) {
  24167. const programGPU = this.get( program );
  24168. programGPU.module = {
  24169. module: this.device.createShaderModule( { code: program.code, label: program.stage } ),
  24170. entryPoint: 'main'
  24171. };
  24172. }
  24173. destroyProgram( program ) {
  24174. this.delete( program );
  24175. }
  24176. // pipelines
  24177. createRenderPipeline( renderObject, promises ) {
  24178. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  24179. }
  24180. createComputePipeline( computePipeline, bindings ) {
  24181. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  24182. }
  24183. beginBundle( renderContext ) {
  24184. const renderContextData = this.get( renderContext );
  24185. renderContextData._currentPass = renderContextData.currentPass;
  24186. renderContextData._currentSets = renderContextData.currentSets;
  24187. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  24188. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  24189. }
  24190. finishBundle( renderContext, bundle ) {
  24191. const renderContextData = this.get( renderContext );
  24192. const bundleEncoder = renderContextData.currentPass;
  24193. const bundleGPU = bundleEncoder.finish();
  24194. this.get( bundle ).bundleGPU = bundleGPU;
  24195. // restore render pass state
  24196. renderContextData.currentSets = renderContextData._currentSets;
  24197. renderContextData.currentPass = renderContextData._currentPass;
  24198. }
  24199. addBundle( renderContext, bundle ) {
  24200. const renderContextData = this.get( renderContext );
  24201. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  24202. }
  24203. // bindings
  24204. createBindings( bindGroup, bindings, cacheIndex, version ) {
  24205. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  24206. }
  24207. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  24208. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  24209. }
  24210. updateBinding( binding ) {
  24211. this.bindingUtils.updateBinding( binding );
  24212. }
  24213. // attributes
  24214. createIndexAttribute( attribute ) {
  24215. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  24216. }
  24217. createAttribute( attribute ) {
  24218. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  24219. }
  24220. createStorageAttribute( attribute ) {
  24221. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  24222. }
  24223. createIndirectStorageAttribute( attribute ) {
  24224. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  24225. }
  24226. updateAttribute( attribute ) {
  24227. this.attributeUtils.updateAttribute( attribute );
  24228. }
  24229. destroyAttribute( attribute ) {
  24230. this.attributeUtils.destroyAttribute( attribute );
  24231. }
  24232. // canvas
  24233. updateSize() {
  24234. this.colorBuffer = this.textureUtils.getColorBuffer();
  24235. this.defaultRenderPassdescriptor = null;
  24236. }
  24237. // utils public
  24238. getMaxAnisotropy() {
  24239. return 16;
  24240. }
  24241. hasFeature( name ) {
  24242. return this.device.features.has( name );
  24243. }
  24244. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  24245. let dstX = 0;
  24246. let dstY = 0;
  24247. let dstLayer = 0;
  24248. let srcX = 0;
  24249. let srcY = 0;
  24250. let srcLayer = 0;
  24251. let srcWidth = srcTexture.image.width;
  24252. let srcHeight = srcTexture.image.height;
  24253. if ( srcRegion !== null ) {
  24254. srcX = srcRegion.x;
  24255. srcY = srcRegion.y;
  24256. srcLayer = srcRegion.z || 0;
  24257. srcWidth = srcRegion.width;
  24258. srcHeight = srcRegion.height;
  24259. }
  24260. if ( dstPosition !== null ) {
  24261. dstX = dstPosition.x;
  24262. dstY = dstPosition.y;
  24263. dstLayer = dstPosition.z || 0;
  24264. }
  24265. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  24266. const sourceGPU = this.get( srcTexture ).texture;
  24267. const destinationGPU = this.get( dstTexture ).texture;
  24268. encoder.copyTextureToTexture(
  24269. {
  24270. texture: sourceGPU,
  24271. mipLevel: level,
  24272. origin: { x: srcX, y: srcY, z: srcLayer }
  24273. },
  24274. {
  24275. texture: destinationGPU,
  24276. mipLevel: level,
  24277. origin: { x: dstX, y: dstY, z: dstLayer }
  24278. },
  24279. [
  24280. srcWidth,
  24281. srcHeight,
  24282. 1
  24283. ]
  24284. );
  24285. this.device.queue.submit( [ encoder.finish() ] );
  24286. }
  24287. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  24288. const renderContextData = this.get( renderContext );
  24289. let sourceGPU = null;
  24290. if ( renderContext.renderTarget ) {
  24291. if ( texture.isDepthTexture ) {
  24292. sourceGPU = this.get( renderContext.depthTexture ).texture;
  24293. } else {
  24294. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  24295. }
  24296. } else {
  24297. if ( texture.isDepthTexture ) {
  24298. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  24299. } else {
  24300. sourceGPU = this.context.getCurrentTexture();
  24301. }
  24302. }
  24303. const destinationGPU = this.get( texture ).texture;
  24304. if ( sourceGPU.format !== destinationGPU.format ) {
  24305. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  24306. return;
  24307. }
  24308. let encoder;
  24309. if ( renderContextData.currentPass ) {
  24310. renderContextData.currentPass.end();
  24311. encoder = renderContextData.encoder;
  24312. } else {
  24313. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  24314. }
  24315. encoder.copyTextureToTexture(
  24316. {
  24317. texture: sourceGPU,
  24318. origin: { x: rectangle.x, y: rectangle.y, z: 0 }
  24319. },
  24320. {
  24321. texture: destinationGPU
  24322. },
  24323. [
  24324. rectangle.z,
  24325. rectangle.w
  24326. ]
  24327. );
  24328. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  24329. if ( renderContextData.currentPass ) {
  24330. const { descriptor } = renderContextData;
  24331. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  24332. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  24333. }
  24334. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  24335. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  24336. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  24337. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  24338. } else {
  24339. this.device.queue.submit( [ encoder.finish() ] );
  24340. }
  24341. }
  24342. }
  24343. class IESSpotLight extends SpotLight {
  24344. constructor( color, intensity, distance, angle, penumbra, decay ) {
  24345. super( color, intensity, distance, angle, penumbra, decay );
  24346. this.iesMap = null;
  24347. }
  24348. copy( source, recursive ) {
  24349. super.copy( source, recursive );
  24350. this.iesMap = source.iesMap;
  24351. return this;
  24352. }
  24353. }
  24354. class BasicNodeLibrary extends NodeLibrary {
  24355. constructor() {
  24356. super();
  24357. this.addLight( PointLightNode, PointLight );
  24358. this.addLight( DirectionalLightNode, DirectionalLight );
  24359. this.addLight( RectAreaLightNode, RectAreaLight );
  24360. this.addLight( SpotLightNode, SpotLight );
  24361. this.addLight( AmbientLightNode, AmbientLight );
  24362. this.addLight( HemisphereLightNode, HemisphereLight );
  24363. this.addLight( LightProbeNode, LightProbe );
  24364. this.addLight( IESSpotLightNode, IESSpotLight );
  24365. this.addToneMapping( linearToneMapping, LinearToneMapping );
  24366. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  24367. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  24368. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  24369. this.addToneMapping( agxToneMapping, AgXToneMapping );
  24370. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  24371. }
  24372. }
  24373. class WebGPURenderer extends Renderer {
  24374. constructor( parameters = {} ) {
  24375. let BackendClass;
  24376. if ( parameters.forceWebGL ) {
  24377. BackendClass = WebGLBackend;
  24378. } else {
  24379. BackendClass = WebGPUBackend;
  24380. parameters.getFallback = () => {
  24381. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  24382. return new WebGLBackend( parameters );
  24383. };
  24384. }
  24385. const backend = new BackendClass( parameters );
  24386. super( backend, parameters );
  24387. this.library = new BasicNodeLibrary();
  24388. this.isWebGPURenderer = true;
  24389. }
  24390. }
  24391. class BundleGroup extends Group {
  24392. constructor() {
  24393. super();
  24394. this.isBundleGroup = true;
  24395. this.type = 'BundleGroup';
  24396. this.static = true;
  24397. this.version = 0;
  24398. }
  24399. set needsUpdate( value ) {
  24400. if ( value === true ) this.version ++;
  24401. }
  24402. }
  24403. const _material = /*@__PURE__*/ new NodeMaterial();
  24404. const _quadMesh = /*@__PURE__*/ new QuadMesh( _material );
  24405. class PostProcessing {
  24406. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  24407. this.renderer = renderer;
  24408. this.outputNode = outputNode;
  24409. this.outputColorTransform = true;
  24410. this.needsUpdate = true;
  24411. _material.name = 'PostProcessing';
  24412. }
  24413. render() {
  24414. this.update();
  24415. const renderer = this.renderer;
  24416. const toneMapping = renderer.toneMapping;
  24417. const outputColorSpace = renderer.outputColorSpace;
  24418. renderer.toneMapping = NoToneMapping;
  24419. renderer.outputColorSpace = LinearSRGBColorSpace;
  24420. //
  24421. _quadMesh.render( renderer );
  24422. //
  24423. renderer.toneMapping = toneMapping;
  24424. renderer.outputColorSpace = outputColorSpace;
  24425. }
  24426. update() {
  24427. if ( this.needsUpdate === true ) {
  24428. const renderer = this.renderer;
  24429. const toneMapping = renderer.toneMapping;
  24430. const outputColorSpace = renderer.outputColorSpace;
  24431. _quadMesh.material.fragmentNode = this.outputColorTransform === true ? renderOutput( this.outputNode, toneMapping, outputColorSpace ) : this.outputNode.context( { toneMapping, outputColorSpace } );
  24432. _quadMesh.material.needsUpdate = true;
  24433. this.needsUpdate = false;
  24434. }
  24435. }
  24436. async renderAsync() {
  24437. this.update();
  24438. const renderer = this.renderer;
  24439. const toneMapping = renderer.toneMapping;
  24440. const outputColorSpace = renderer.outputColorSpace;
  24441. renderer.toneMapping = NoToneMapping;
  24442. renderer.outputColorSpace = LinearSRGBColorSpace;
  24443. //
  24444. await _quadMesh.renderAsync( renderer );
  24445. //
  24446. renderer.toneMapping = toneMapping;
  24447. renderer.outputColorSpace = outputColorSpace;
  24448. }
  24449. }
  24450. // renderer state
  24451. function saveRendererState( renderer, state = {} ) {
  24452. state.toneMapping = renderer.toneMapping;
  24453. state.toneMappingExposure = renderer.toneMappingExposure;
  24454. state.outputColorSpace = renderer.outputColorSpace;
  24455. state.renderTarget = renderer.getRenderTarget();
  24456. state.activeCubeFace = renderer.getActiveCubeFace();
  24457. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  24458. state.renderObjectFunction = renderer.getRenderObjectFunction();
  24459. state.pixelRatio = renderer.getPixelRatio();
  24460. state.mrt = renderer.getMRT();
  24461. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  24462. state.clearAlpha = renderer.getClearAlpha();
  24463. state.autoClear = renderer.autoClear;
  24464. state.scissorTest = renderer.getScissorTest();
  24465. return state;
  24466. }
  24467. function resetRendererState( renderer, state ) {
  24468. state = saveRendererState( renderer, state );
  24469. renderer.setMRT( null );
  24470. renderer.setRenderObjectFunction( null );
  24471. renderer.setClearColor( 0x000000, 1 );
  24472. renderer.autoClear = true;
  24473. return state;
  24474. }
  24475. function restoreRendererState( renderer, state ) {
  24476. renderer.toneMapping = state.toneMapping;
  24477. renderer.toneMappingExposure = state.toneMappingExposure;
  24478. renderer.outputColorSpace = state.outputColorSpace;
  24479. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  24480. renderer.setRenderObjectFunction( state.renderObjectFunction );
  24481. renderer.setPixelRatio( state.pixelRatio );
  24482. renderer.setMRT( state.mrt );
  24483. renderer.setClearColor( state.clearColor, state.clearAlpha );
  24484. renderer.autoClear = state.autoClear;
  24485. renderer.setScissorTest( state.scissorTest );
  24486. }
  24487. // renderer and scene state
  24488. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  24489. state = saveRendererState( renderer, state );
  24490. state.background = scene.background;
  24491. state.backgroundNode = scene.backgroundNode;
  24492. state.overrideMaterial = scene.overrideMaterial;
  24493. return state;
  24494. }
  24495. function resetRendererAndSceneState( renderer, scene, state ) {
  24496. state = saveRendererAndSceneState( renderer, scene, state );
  24497. scene.background = null;
  24498. scene.backgroundNode = null;
  24499. scene.overrideMaterial = null;
  24500. return state;
  24501. }
  24502. function restoreRendererAndSceneState( renderer, scene, state ) {
  24503. restoreRendererState( renderer, state );
  24504. scene.background = state.background;
  24505. scene.backgroundNode = state.backgroundNode;
  24506. scene.overrideMaterial = state.overrideMaterial;
  24507. }
  24508. var PostProcessingUtils = /*#__PURE__*/Object.freeze({
  24509. __proto__: null,
  24510. resetRendererAndSceneState: resetRendererAndSceneState,
  24511. resetRendererState: resetRendererState,
  24512. restoreRendererAndSceneState: restoreRendererAndSceneState,
  24513. restoreRendererState: restoreRendererState,
  24514. saveRendererAndSceneState: saveRendererAndSceneState,
  24515. saveRendererState: saveRendererState
  24516. });
  24517. class StorageTexture extends Texture {
  24518. constructor( width = 1, height = 1 ) {
  24519. super();
  24520. this.image = { width, height };
  24521. this.magFilter = LinearFilter;
  24522. this.minFilter = LinearFilter;
  24523. this.isStorageTexture = true;
  24524. }
  24525. }
  24526. class StorageBufferAttribute extends BufferAttribute {
  24527. constructor( array, itemSize, typeClass = Float32Array ) {
  24528. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  24529. super( array, itemSize );
  24530. this.isStorageBufferAttribute = true;
  24531. }
  24532. }
  24533. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  24534. constructor( array, itemSize, typeClass = Float32Array ) {
  24535. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  24536. super( array, itemSize );
  24537. this.isStorageInstancedBufferAttribute = true;
  24538. }
  24539. }
  24540. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  24541. constructor( array, itemSize ) {
  24542. super( array, itemSize, Uint32Array );
  24543. this.isIndirectStorageBufferAttribute = true;
  24544. }
  24545. }
  24546. class NodeLoader extends Loader {
  24547. constructor( manager ) {
  24548. super( manager );
  24549. this.textures = {};
  24550. this.nodes = {};
  24551. }
  24552. load( url, onLoad, onProgress, onError ) {
  24553. const loader = new FileLoader( this.manager );
  24554. loader.setPath( this.path );
  24555. loader.setRequestHeader( this.requestHeader );
  24556. loader.setWithCredentials( this.withCredentials );
  24557. loader.load( url, ( text ) => {
  24558. try {
  24559. onLoad( this.parse( JSON.parse( text ) ) );
  24560. } catch ( e ) {
  24561. if ( onError ) {
  24562. onError( e );
  24563. } else {
  24564. console.error( e );
  24565. }
  24566. this.manager.itemError( url );
  24567. }
  24568. }, onProgress, onError );
  24569. }
  24570. parseNodes( json ) {
  24571. const nodes = {};
  24572. if ( json !== undefined ) {
  24573. for ( const nodeJSON of json ) {
  24574. const { uuid, type } = nodeJSON;
  24575. nodes[ uuid ] = this.createNodeFromType( type );
  24576. nodes[ uuid ].uuid = uuid;
  24577. }
  24578. const meta = { nodes, textures: this.textures };
  24579. for ( const nodeJSON of json ) {
  24580. nodeJSON.meta = meta;
  24581. const node = nodes[ nodeJSON.uuid ];
  24582. node.deserialize( nodeJSON );
  24583. delete nodeJSON.meta;
  24584. }
  24585. }
  24586. return nodes;
  24587. }
  24588. parse( json ) {
  24589. const node = this.createNodeFromType( json.type );
  24590. node.uuid = json.uuid;
  24591. const nodes = this.parseNodes( json.nodes );
  24592. const meta = { nodes, textures: this.textures };
  24593. json.meta = meta;
  24594. node.deserialize( json );
  24595. delete json.meta;
  24596. return node;
  24597. }
  24598. setTextures( value ) {
  24599. this.textures = value;
  24600. return this;
  24601. }
  24602. setNodes( value ) {
  24603. this.nodes = value;
  24604. return this;
  24605. }
  24606. createNodeFromType( type ) {
  24607. if ( this.nodes[ type ] === undefined ) {
  24608. console.error( 'THREE.NodeLoader: Node type not found:', type );
  24609. return float();
  24610. }
  24611. return nodeObject( new this.nodes[ type ]() );
  24612. }
  24613. }
  24614. class NodeMaterialLoader extends MaterialLoader {
  24615. constructor( manager ) {
  24616. super( manager );
  24617. this.nodes = {};
  24618. this.nodeMaterials = {};
  24619. }
  24620. parse( json ) {
  24621. const material = super.parse( json );
  24622. const nodes = this.nodes;
  24623. const inputNodes = json.inputNodes;
  24624. for ( const property in inputNodes ) {
  24625. const uuid = inputNodes[ property ];
  24626. material[ property ] = nodes[ uuid ];
  24627. }
  24628. return material;
  24629. }
  24630. setNodes( value ) {
  24631. this.nodes = value;
  24632. return this;
  24633. }
  24634. setNodeMaterials( value ) {
  24635. this.nodeMaterials = value;
  24636. return this;
  24637. }
  24638. createMaterialFromType( type ) {
  24639. const materialClass = this.nodeMaterials[ type ];
  24640. if ( materialClass !== undefined ) {
  24641. return new materialClass();
  24642. }
  24643. return super.createMaterialFromType( type );
  24644. }
  24645. }
  24646. class NodeObjectLoader extends ObjectLoader {
  24647. constructor( manager ) {
  24648. super( manager );
  24649. this.nodes = {};
  24650. this.nodeMaterials = {};
  24651. this._nodesJSON = null;
  24652. }
  24653. setNodes( value ) {
  24654. this.nodes = value;
  24655. return this;
  24656. }
  24657. setNodeMaterials( value ) {
  24658. this.nodeMaterials = value;
  24659. return this;
  24660. }
  24661. parse( json, onLoad ) {
  24662. this._nodesJSON = json.nodes;
  24663. const data = super.parse( json, onLoad );
  24664. this._nodesJSON = null; // dispose
  24665. return data;
  24666. }
  24667. parseNodes( json, textures ) {
  24668. if ( json !== undefined ) {
  24669. const loader = new NodeLoader();
  24670. loader.setNodes( this.nodes );
  24671. loader.setTextures( textures );
  24672. return loader.parseNodes( json );
  24673. }
  24674. return {};
  24675. }
  24676. parseMaterials( json, textures ) {
  24677. const materials = {};
  24678. if ( json !== undefined ) {
  24679. const nodes = this.parseNodes( this._nodesJSON, textures );
  24680. const loader = new NodeMaterialLoader();
  24681. loader.setTextures( textures );
  24682. loader.setNodes( nodes );
  24683. loader.setNodeMaterials( this.nodeMaterials );
  24684. for ( let i = 0, l = json.length; i < l; i ++ ) {
  24685. const data = json[ i ];
  24686. materials[ data.uuid ] = loader.parse( data );
  24687. }
  24688. }
  24689. return materials;
  24690. }
  24691. }
  24692. class ClippingGroup extends Group {
  24693. constructor() {
  24694. super();
  24695. this.isClippingGroup = true;
  24696. this.clippingPlanes = [];
  24697. this.enabled = true;
  24698. this.clipIntersection = false;
  24699. this.clipShadows = false;
  24700. }
  24701. }
  24702. export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnalyticLightNode, ArrayElementNode, AssignNode, AttributeNode, BRDF_GGX, BRDF_Lambert, BackSide, BasicEnvironmentNode, BasicShadowFilter, BasicShadowMap, BatchNode, BoxGeometry, Break, BufferAttribute, BufferAttributeNode, BufferGeometry, BufferNode, BumpMapNode, BundleGroup, BypassNode, ByteType, CacheNode, CineonToneMapping, ClampToEdgeWrapping, ClippingGroup, CodeNode, Color, ColorManagement, ColorSpaceNode, ComputeNode, ConstNode, ContextNode, Continue, ConvertNode, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureNode, CubeUVReflectionMapping, CullFaceBack, CullFaceFront, CullFaceNone, CustomBlending, DFGApprox, D_GGX, DataArrayTexture, DataTexture, DecrementStencilOp, DecrementWrapStencilOp, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DirectionalLightNode, Discard, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicDrawUsage, EPSILON, EnvironmentNode, EqualCompare, EqualDepth, EqualStencilFunc, EquirectUVNode, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExpressionNode, F_Schlick, FileLoader, Float16BufferAttribute, Float32BufferAttribute, FloatType, Fn, FogExp2Node, FogNode, FogRangeNode, FramebufferTexture, FrontFacingNode, FrontSide, Frustum, FunctionCallNode, FunctionNode, FunctionOverloadingNode, GLSLNodeParser, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, Group, HalfFloatType, HemisphereLight, HemisphereLightNode, IESSpotLight, IESSpotLightNode, INFINITY, If, 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, Loop, 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, 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, PCFShadowFilter, PCFShadowMap, PCFSoftShadowFilter, PI, PI2, 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, Return, ReverseSubtractEquation, RotateNode, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, Scene, SceneNode, Schlick_to_F0, ScreenNode, ScriptableNode, ScriptableNodeResources, ScriptableValueNode, SetNode, ShaderNode, 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, TBNViewMatrix, TangentSpaceNormalMap, TempNode, Texture, Texture3DNode, TextureNode, TextureSizeNode, ToneMappingNode, ToonOutlinePassNode, TriplanarTexturesNode, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, UniformArrayNode, UniformGroupNode, UniformNode, UnsignedByteType, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, UserDataNode, VSMShadowFilter, VSMShadowMap, V_GGX_SmithCorrelated, VarNode, VaryingNode, Vector2, Vector3, Vector4, VertexColorNode, ViewportDepthNode, ViewportDepthTextureNode, ViewportSharedTextureNode, ViewportTextureNode, VolumeNodeMaterial, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGPUCoordinateSystem, WebGPURenderer, ZeroFactor, ZeroStencilOp, abs, acesFilmicToneMapping, acos, add, addMethodChaining, addNodeElement, agxToneMapping, all, alphaT, and, anisotropy, anisotropyB, anisotropyT, any, append, arrayBuffer, asin, assign, atan, atan2, atomicAdd, atomicAnd, atomicFunc, atomicMax, atomicMin, atomicOr, atomicStore, atomicSub, atomicXor, attenuationColor, attenuationDistance, attribute, backgroundBlurriness, backgroundIntensity, backgroundRotation, batch, billboarding, bitAnd, bitNot, bitOr, bitXor, bitangentGeometry, bitangentLocal, bitangentView, bitangentWorld, bitcast, blendBurn, blendColor, blendDodge, blendOverlay, blendScreen, blur, bool, buffer, bufferAttribute, bumpMap, burn, bvec2, bvec3, bvec4, bypass, cache, call, cameraFar, cameraNear, cameraNormalMatrix, cameraPosition, cameraProjectionMatrix, cameraProjectionMatrixInverse, cameraViewMatrix, cameraWorldMatrix, cbrt, cdl, ceil, checker, cineonToneMapping, clamp, clearcoat, clearcoatRoughness, code, color, colorSpaceToWorking, colorToDirection, compute, cond, context, convert, convertColorSpace, convertToTexture, cos, createCanvasElement, cross, cubeTexture, dFdx, dFdy, dashSize, defaultBuildStages, defaultShaderStages, defined, degrees, deltaTime, densityFog, depth, depthPass, difference, diffuseColor, directPointLight, directionToColor, dispersion, distance, div, dodge, dot, drawIndex, dynamicBufferAttribute, element, emissive, equal, equals, equirectUV, exp, exp2, expression, faceDirection, faceForward, float, floor, fog, fract, frameGroup, frameId, frontFacing, fwidth, gain, gapSize, getConstNodeType, getCurrentStack, getDirection, getDistanceAttenuation, getGeometryRoughness, getNormalFromDepth, getParallaxCorrectNormal, getRoughness, getScreenPosition, getShIrradianceAt, getTextureIndex, getViewPosition, glsl, glslFn, grayscale, greaterThan, greaterThanEqual, hash, highPrecisionModelNormalViewMatrix, highPrecisionModelViewMatrix, hue, instance, instanceIndex, instancedBufferAttribute, instancedDynamicBufferAttribute, instancedMesh, int, inverseSqrt, invocationLocalIndex, invocationSubgroupIndex, ior, iridescence, iridescenceIOR, iridescenceThickness, ivec2, ivec3, ivec4, js, label, length, lengthSq, lessThan, lessThanEqual, lightPosition, lightTargetDirection, lightTargetPosition, lightViewPosition, lightingContext, lights, linearDepth, linearToneMapping, localId, log, log2, logarithmicDepthToViewZ, loop, luminance, mat2, mat3, mat4, matcapUV, materialAOMap, materialAlphaTest, materialAnisotropy, materialAnisotropyVector, materialAttenuationColor, materialAttenuationDistance, materialClearcoat, materialClearcoatNormal, materialClearcoatRoughness, materialColor, materialDispersion, materialEmissive, materialIOR, materialIridescence, materialIridescenceIOR, materialIridescenceThickness, materialLightMap, materialLineDashOffset, materialLineDashSize, materialLineGapSize, materialLineScale, materialLineWidth, materialMetalness, materialNormal, materialOpacity, materialPointWidth, materialReference, materialReflectivity, materialRefractionRatio, materialRotation, materialRoughness, materialSheen, materialSheenRoughness, materialShininess, materialSpecular, materialSpecularColor, materialSpecularIntensity, materialSpecularStrength, materialThickness, materialTransmission, max$1 as max, maxMipLevel, metalness, min$1 as min, mix, mixElement, mod, modInt, modelDirection, modelNormalMatrix, modelPosition, modelScale, modelViewMatrix, modelViewPosition, modelViewProjection, modelWorldMatrix, modelWorldMatrixInverse, morphReference, mrt, mul, mx_aastep, mx_cell_noise_float, mx_contrast, mx_fractal_noise_float, mx_fractal_noise_vec2, mx_fractal_noise_vec3, mx_fractal_noise_vec4, mx_hsvtorgb, mx_noise_float, mx_noise_vec3, mx_noise_vec4, mx_ramplr, mx_ramptb, mx_rgbtohsv, mx_safepower, mx_splitlr, mx_splittb, mx_srgb_texture_to_lin_rec709, mx_transform_uv, mx_worley_noise_float, mx_worley_noise_vec2, mx_worley_noise_vec3, negate, neutralToneMapping, nodeArray, nodeImmutable, nodeObject, nodeObjects, nodeProxy, normalFlat, normalGeometry, normalLocal, normalMap, normalView, normalWorld, normalize, not, notEqual, numWorkgroups, objectDirection, objectGroup, objectPosition, objectScale, objectViewPosition, objectWorldMatrix, oneMinus, or, orthographicDepthToViewZ, oscSawtooth, oscSine, oscSquare, oscTriangle, output, outputStruct, overlay, overloadingFn, parabola, parallaxDirection, parallaxUV, parameter, pass, passTexture, pcurve, perspectiveDepthToViewZ, pmremTexture, pointUV, pointWidth, positionGeometry, positionLocal, positionPrevious, positionView, positionViewDirection, positionWorld, positionWorldDirection, posterize, pow, pow2, pow3, pow4, property, radians, rand, range, rangeFog, reciprocal, reference, referenceBuffer, reflect, reflectVector, reflectView, reflector, refract, refractVector, refractView, reinhardToneMapping, remainder, remap, remapClamp, renderGroup, renderOutput, rendererReference, rotate, rotateUV, roughness, round, rtt, sRGBTransferEOTF, sRGBTransferOETF, sampler, saturate, saturation, screen, screenCoordinate, screenSize, screenUV, scriptable, scriptableValue, select, setCurrentStack, shaderStages, shadow, sharedUniformGroup, sheen, sheenRoughness, shiftLeft, shiftRight, shininess, sign, sin, sinc, skinning, skinningReference, smoothstep, smoothstepElement, specularColor, specularF90, spherizeUV, split, spritesheetUV, sqrt, stack, step, storage, storageBarrier, storageObject, storageTexture, string, sub, subgroupIndex, subgroupSize, tan, tangentGeometry, tangentLocal, tangentView, tangentWorld, temp, texture, texture3D, textureBarrier, textureBicubic, textureCubeUV, textureLoad, textureSize, textureStore, thickness, threshold, time, timerDelta, timerGlobal, timerLocal, toOutputColorSpace, toWorkingColorSpace, toneMapping, toneMappingExposure, toonOutlinePass, transformDirection, transformNormal, transformNormalToView, transformedBentNormalView, transformedBitangentView, transformedBitangentWorld, transformedClearcoatNormalView, transformedNormalView, transformedNormalWorld, transformedTangentView, transformedTangentWorld, transmission, transpose, tri, tri3, triNoise3D, triplanarTexture, triplanarTextures, trunc, tslFn, uint, uniform, uniformArray, uniformGroup, uniforms, userData, uv, uvec2, uvec3, uvec4, varying, varyingProperty, vec2, vec3, vec4, vectorComponents, velocity, vertexColor, vertexIndex, vibrance, viewZToLogarithmicDepth, viewZToOrthographicDepth, viewZToPerspectiveDepth, viewport, viewportBottomLeft, viewportCoordinate, viewportDepthTexture, viewportLinearDepth, viewportMipTexture, viewportResolution, viewportSafeUV, viewportSharedTexture, viewportSize, viewportTexture, viewportTopLeft, viewportUV, wgsl, wgslFn, workgroupArray, workgroupBarrier, workgroupId, workingToColorSpace, xor };
粤ICP备19079148号