three.webgpu.js 959 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481
  1. /**
  2. * @license
  3. * Copyright 2010-2024 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. import { Color, Vector2, Vector3, Vector4, Matrix3, Matrix4, EventDispatcher, MathUtils, ColorManagement, SRGBTransfer, NoToneMapping, StaticDrawUsage, InterleavedBuffer, DynamicDrawUsage, InterleavedBufferAttribute, NoColorSpace, UnsignedIntType, IntType, WebGLCoordinateSystem, BackSide, CubeReflectionMapping, CubeRefractionMapping, WebGPUCoordinateSystem, TangentSpaceNormalMap, ObjectSpaceNormalMap, InstancedInterleavedBuffer, InstancedBufferAttribute, DataArrayTexture, FloatType, FramebufferTexture, LinearMipmapLinearFilter, DepthTexture, Material, NormalBlending, PointsMaterial, LineBasicMaterial, LineDashedMaterial, NoBlending, MeshNormalMaterial, WebGLCubeRenderTarget, BoxGeometry, Mesh, Scene, LinearFilter, CubeCamera, CubeTexture, EquirectangularReflectionMapping, EquirectangularRefractionMapping, AddOperation, MixOperation, MultiplyOperation, MeshBasicMaterial, MeshLambertMaterial, MeshPhongMaterial, Texture, MeshStandardMaterial, MeshPhysicalMaterial, MeshToonMaterial, MeshMatcapMaterial, SpriteMaterial, ShadowMaterial, Uint32BufferAttribute, Uint16BufferAttribute, DoubleSide, DepthStencilFormat, DepthFormat, UnsignedInt248Type, UnsignedByteType, RenderTarget, Plane, Object3D, HalfFloatType, LinearMipMapLinearFilter, OrthographicCamera, BufferGeometry, Float32BufferAttribute, BufferAttribute, UVMapping, Euler, LinearSRGBColorSpace, LessCompare, VSMShadowMap, RGFormat, BasicShadowMap, SphereGeometry, CubeUVReflectionMapping, PerspectiveCamera, RGBAFormat, LinearMipmapNearestFilter, NearestMipmapLinearFilter, Float16BufferAttribute, REVISION, SRGBColorSpace, PCFShadowMap, FrontSide, Frustum, DataTexture, RedIntegerFormat, RedFormat, RGIntegerFormat, RGBIntegerFormat, RGBFormat, RGBAIntegerFormat, UnsignedShortType, ByteType, ShortType, createCanvasElement, AddEquation, SubtractEquation, ReverseSubtractEquation, ZeroFactor, OneFactor, SrcColorFactor, SrcAlphaFactor, SrcAlphaSaturateFactor, DstColorFactor, DstAlphaFactor, OneMinusSrcColorFactor, OneMinusSrcAlphaFactor, OneMinusDstColorFactor, OneMinusDstAlphaFactor, CullFaceNone, CullFaceBack, CullFaceFront, CustomBlending, MultiplyBlending, SubtractiveBlending, AdditiveBlending, NotEqualDepth, GreaterDepth, GreaterEqualDepth, EqualDepth, LessEqualDepth, LessDepth, AlwaysDepth, NeverDepth, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedInt5999Type, AlphaFormat, LuminanceFormat, LuminanceAlphaFormat, RGB_S3TC_DXT1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGB_PVRTC_4BPPV1_Format, RGB_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_PVRTC_2BPPV1_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGBA_ETC2_EAC_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_10x10_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_BPTC_Format, RED_RGTC1_Format, SIGNED_RED_RGTC1_Format, RED_GREEN_RGTC2_Format, SIGNED_RED_GREEN_RGTC2_Format, RepeatWrapping, ClampToEdgeWrapping, MirroredRepeatWrapping, NearestFilter, NearestMipmapNearestFilter, NeverCompare, AlwaysCompare, LessEqualCompare, EqualCompare, GreaterEqualCompare, GreaterCompare, NotEqualCompare, warnOnce, NotEqualStencilFunc, GreaterStencilFunc, GreaterEqualStencilFunc, EqualStencilFunc, LessEqualStencilFunc, LessStencilFunc, AlwaysStencilFunc, NeverStencilFunc, DecrementWrapStencilOp, IncrementWrapStencilOp, DecrementStencilOp, IncrementStencilOp, InvertStencilOp, ReplaceStencilOp, ZeroStencilOp, KeepStencilOp, MaxEquation, MinEquation, SpotLight, PointLight, DirectionalLight, RectAreaLight, AmbientLight, HemisphereLight, LightProbe, LinearToneMapping, ReinhardToneMapping, CineonToneMapping, ACESFilmicToneMapping, AgXToneMapping, NeutralToneMapping, Group, Loader, FileLoader, MaterialLoader, ObjectLoader } from './three.core.js';
  7. export { AdditiveAnimationBlendMode, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrowHelper, AttachedBindMode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BasicDepthPacking, BatchedMesh, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxHelper, BufferGeometryLoader, Cache, Camera, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CircleGeometry, Clock, ColorKeyframeTrack, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ConeGeometry, ConstantAlphaFactor, ConstantColorFactor, Controls, CubeTextureLoader, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceFrontBack, Curve, CurvePath, CustomToneMapping, CylinderGeometry, Cylindrical, Data3DTexture, DataTextureLoader, DataUtils, DefaultLoadingManager, DetachedBindMode, DirectionalLightHelper, DiscreteInterpolant, DodecahedronGeometry, DynamicCopyUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, ExtrudeGeometry, Fog, FogExp2, GLBufferAttribute, GLSL1, GLSL3, GridHelper, HemisphereLightHelper, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, InstancedBufferGeometry, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, KeyframeTrack, LOD, LatheGeometry, Layers, Light, Line, Line3, LineCurve, LineCurve3, LineLoop, LineSegments, LinearInterpolant, LinearMipMapNearestFilter, LinearTransfer, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, MOUSE, Matrix2, MeshDepthMaterial, MeshDistanceMaterial, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NormalAnimationBlendMode, NumberKeyframeTrack, OctahedronGeometry, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, PCFSoftShadowMap, Path, PlaneGeometry, PlaneHelper, PointLightHelper, Points, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RGBADepthPacking, RGBDepthPacking, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGDepthPacking, RawShaderMaterial, Ray, Raycaster, RingGeometry, ShaderMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, Skeleton, SkeletonHelper, SkinnedMesh, Source, Sphere, Spherical, SphericalHarmonics3, SplineCurve, SpotLightHelper, Sprite, StaticCopyUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, TOUCH, TetrahedronGeometry, TextureLoader, TextureUtils, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, VectorKeyframeTrack, VideoTexture, WebGL3DRenderTarget, WebGLArrayRenderTarget, 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. const typeFromLength = /*@__PURE__*/ new Map( [
  323. [ 1, 'float' ],
  324. [ 2, 'vec2' ],
  325. [ 3, 'vec3' ],
  326. [ 4, 'vec4' ],
  327. [ 9, 'mat3' ],
  328. [ 16, 'mat4' ]
  329. ] );
  330. function getTypeFromLength( length ) {
  331. return typeFromLength.get( length );
  332. }
  333. function getLengthFromType( type ) {
  334. if ( /float|int|uint/.test( type ) ) return 1;
  335. if ( /vec2/.test( type ) ) return 2;
  336. if ( /vec3/.test( type ) ) return 3;
  337. if ( /vec4/.test( type ) ) return 4;
  338. if ( /mat3/.test( type ) ) return 9;
  339. if ( /mat4/.test( type ) ) return 16;
  340. console.error( 'THREE.TSL: Unsupported type:', type );
  341. }
  342. function getValueType( value ) {
  343. if ( value === undefined || value === null ) return null;
  344. const typeOf = typeof value;
  345. if ( value.isNode === true ) {
  346. return 'node';
  347. } else if ( typeOf === 'number' ) {
  348. return 'float';
  349. } else if ( typeOf === 'boolean' ) {
  350. return 'bool';
  351. } else if ( typeOf === 'string' ) {
  352. return 'string';
  353. } else if ( typeOf === 'function' ) {
  354. return 'shader';
  355. } else if ( value.isVector2 === true ) {
  356. return 'vec2';
  357. } else if ( value.isVector3 === true ) {
  358. return 'vec3';
  359. } else if ( value.isVector4 === true ) {
  360. return 'vec4';
  361. } else if ( value.isMatrix3 === true ) {
  362. return 'mat3';
  363. } else if ( value.isMatrix4 === true ) {
  364. return 'mat4';
  365. } else if ( value.isColor === true ) {
  366. return 'color';
  367. } else if ( value instanceof ArrayBuffer ) {
  368. return 'ArrayBuffer';
  369. }
  370. return null;
  371. }
  372. function getValueFromType( type, ...params ) {
  373. const last4 = type ? type.slice( - 4 ) : undefined;
  374. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  375. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  376. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  377. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  378. }
  379. if ( type === 'color' ) {
  380. return new Color( ...params );
  381. } else if ( last4 === 'vec2' ) {
  382. return new Vector2( ...params );
  383. } else if ( last4 === 'vec3' ) {
  384. return new Vector3( ...params );
  385. } else if ( last4 === 'vec4' ) {
  386. return new Vector4( ...params );
  387. } else if ( last4 === 'mat3' ) {
  388. return new Matrix3( ...params );
  389. } else if ( last4 === 'mat4' ) {
  390. return new Matrix4( ...params );
  391. } else if ( type === 'bool' ) {
  392. return params[ 0 ] || false;
  393. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  394. return params[ 0 ] || 0;
  395. } else if ( type === 'string' ) {
  396. return params[ 0 ] || '';
  397. } else if ( type === 'ArrayBuffer' ) {
  398. return base64ToArrayBuffer( params[ 0 ] );
  399. }
  400. return null;
  401. }
  402. function arrayBufferToBase64( arrayBuffer ) {
  403. let chars = '';
  404. const array = new Uint8Array( arrayBuffer );
  405. for ( let i = 0; i < array.length; i ++ ) {
  406. chars += String.fromCharCode( array[ i ] );
  407. }
  408. return btoa( chars );
  409. }
  410. function base64ToArrayBuffer( base64 ) {
  411. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  412. }
  413. var NodeUtils = /*#__PURE__*/Object.freeze({
  414. __proto__: null,
  415. arrayBufferToBase64: arrayBufferToBase64,
  416. base64ToArrayBuffer: base64ToArrayBuffer,
  417. getCacheKey: getCacheKey$1,
  418. getLengthFromType: getLengthFromType,
  419. getNodeChildren: getNodeChildren,
  420. getTypeFromLength: getTypeFromLength,
  421. getValueFromType: getValueFromType,
  422. getValueType: getValueType,
  423. hash: hash$1,
  424. hashArray: hashArray,
  425. hashString: hashString
  426. });
  427. const NodeShaderStage = {
  428. VERTEX: 'vertex',
  429. FRAGMENT: 'fragment'
  430. };
  431. const NodeUpdateType = {
  432. NONE: 'none',
  433. FRAME: 'frame',
  434. RENDER: 'render',
  435. OBJECT: 'object'
  436. };
  437. const NodeType = {
  438. BOOLEAN: 'bool',
  439. INTEGER: 'int',
  440. FLOAT: 'float',
  441. VECTOR2: 'vec2',
  442. VECTOR3: 'vec3',
  443. VECTOR4: 'vec4',
  444. MATRIX2: 'mat2',
  445. MATRIX3: 'mat3',
  446. MATRIX4: 'mat4'
  447. };
  448. const NodeAccess = {
  449. READ_ONLY: 'readOnly',
  450. WRITE_ONLY: 'writeOnly',
  451. READ_WRITE: 'readWrite',
  452. };
  453. const defaultShaderStages = [ 'fragment', 'vertex' ];
  454. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  455. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  456. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  457. let _nodeId = 0;
  458. class Node extends EventDispatcher {
  459. static get type() {
  460. return 'Node';
  461. }
  462. constructor( nodeType = null ) {
  463. super();
  464. this.nodeType = nodeType;
  465. this.updateType = NodeUpdateType.NONE;
  466. this.updateBeforeType = NodeUpdateType.NONE;
  467. this.updateAfterType = NodeUpdateType.NONE;
  468. this.uuid = MathUtils.generateUUID();
  469. this.version = 0;
  470. this._cacheKey = null;
  471. this._cacheKeyVersion = 0;
  472. this.global = false;
  473. this.isNode = true;
  474. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  475. }
  476. set needsUpdate( value ) {
  477. if ( value === true ) {
  478. this.version ++;
  479. }
  480. }
  481. get type() {
  482. return this.constructor.type;
  483. }
  484. onUpdate( callback, updateType ) {
  485. this.updateType = updateType;
  486. this.update = callback.bind( this.getSelf() );
  487. return this;
  488. }
  489. onFrameUpdate( callback ) {
  490. return this.onUpdate( callback, NodeUpdateType.FRAME );
  491. }
  492. onRenderUpdate( callback ) {
  493. return this.onUpdate( callback, NodeUpdateType.RENDER );
  494. }
  495. onObjectUpdate( callback ) {
  496. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  497. }
  498. onReference( callback ) {
  499. this.updateReference = callback.bind( this.getSelf() );
  500. return this;
  501. }
  502. getSelf() {
  503. // Returns non-node object.
  504. return this.self || this;
  505. }
  506. updateReference( /*state*/ ) {
  507. return this;
  508. }
  509. isGlobal( /*builder*/ ) {
  510. return this.global;
  511. }
  512. * getChildren() {
  513. for ( const { childNode } of getNodeChildren( this ) ) {
  514. yield childNode;
  515. }
  516. }
  517. dispose() {
  518. this.dispatchEvent( { type: 'dispose' } );
  519. }
  520. traverse( callback ) {
  521. callback( this );
  522. for ( const childNode of this.getChildren() ) {
  523. childNode.traverse( callback );
  524. }
  525. }
  526. getCacheKey( force = false ) {
  527. force = force || this.version !== this._cacheKeyVersion;
  528. if ( force === true || this._cacheKey === null ) {
  529. this._cacheKey = getCacheKey$1( this, force );
  530. this._cacheKeyVersion = this.version;
  531. }
  532. return this._cacheKey;
  533. }
  534. getScope() {
  535. return this;
  536. }
  537. getHash( /*builder*/ ) {
  538. return this.uuid;
  539. }
  540. getUpdateType() {
  541. return this.updateType;
  542. }
  543. getUpdateBeforeType() {
  544. return this.updateBeforeType;
  545. }
  546. getUpdateAfterType() {
  547. return this.updateAfterType;
  548. }
  549. getElementType( builder ) {
  550. const type = this.getNodeType( builder );
  551. const elementType = builder.getElementType( type );
  552. return elementType;
  553. }
  554. getNodeType( builder ) {
  555. const nodeProperties = builder.getNodeProperties( this );
  556. if ( nodeProperties.outputNode ) {
  557. return nodeProperties.outputNode.getNodeType( builder );
  558. }
  559. return this.nodeType;
  560. }
  561. getShared( builder ) {
  562. const hash = this.getHash( builder );
  563. const nodeFromHash = builder.getNodeFromHash( hash );
  564. return nodeFromHash || this;
  565. }
  566. setup( builder ) {
  567. const nodeProperties = builder.getNodeProperties( this );
  568. let index = 0;
  569. for ( const childNode of this.getChildren() ) {
  570. nodeProperties[ 'node' + index ++ ] = childNode;
  571. }
  572. // return a outputNode if exists
  573. return null;
  574. }
  575. analyze( builder ) {
  576. const usageCount = builder.increaseUsage( this );
  577. if ( usageCount === 1 ) {
  578. // node flow children
  579. const nodeProperties = builder.getNodeProperties( this );
  580. for ( const childNode of Object.values( nodeProperties ) ) {
  581. if ( childNode && childNode.isNode === true ) {
  582. childNode.build( builder );
  583. }
  584. }
  585. }
  586. }
  587. generate( builder, output ) {
  588. const { outputNode } = builder.getNodeProperties( this );
  589. if ( outputNode && outputNode.isNode === true ) {
  590. return outputNode.build( builder, output );
  591. }
  592. }
  593. updateBefore( /*frame*/ ) {
  594. console.warn( 'Abstract function.' );
  595. }
  596. updateAfter( /*frame*/ ) {
  597. console.warn( 'Abstract function.' );
  598. }
  599. update( /*frame*/ ) {
  600. console.warn( 'Abstract function.' );
  601. }
  602. build( builder, output = null ) {
  603. const refNode = this.getShared( builder );
  604. if ( this !== refNode ) {
  605. return refNode.build( builder, output );
  606. }
  607. builder.addNode( this );
  608. builder.addChain( this );
  609. /* Build stages expected results:
  610. - "setup" -> Node
  611. - "analyze" -> null
  612. - "generate" -> String
  613. */
  614. let result = null;
  615. const buildStage = builder.getBuildStage();
  616. if ( buildStage === 'setup' ) {
  617. this.updateReference( builder );
  618. const properties = builder.getNodeProperties( this );
  619. if ( properties.initialized !== true ) {
  620. const stackNodesBeforeSetup = builder.stack.nodes.length;
  621. properties.initialized = true;
  622. properties.outputNode = this.setup( builder );
  623. if ( properties.outputNode !== null && builder.stack.nodes.length !== stackNodesBeforeSetup ) ;
  624. for ( const childNode of Object.values( properties ) ) {
  625. if ( childNode && childNode.isNode === true ) {
  626. childNode.build( builder );
  627. }
  628. }
  629. }
  630. } else if ( buildStage === 'analyze' ) {
  631. this.analyze( builder );
  632. } else if ( buildStage === 'generate' ) {
  633. const isGenerateOnce = this.generate.length === 1;
  634. if ( isGenerateOnce ) {
  635. const type = this.getNodeType( builder );
  636. const nodeData = builder.getDataFromNode( this );
  637. result = nodeData.snippet;
  638. if ( result === undefined ) {
  639. result = this.generate( builder ) || '';
  640. nodeData.snippet = result;
  641. } else if ( nodeData.flowCodes !== undefined && builder.context.nodeBlock !== undefined ) {
  642. builder.addFlowCodeHierarchy( this, builder.context.nodeBlock );
  643. }
  644. result = builder.format( result, type, output );
  645. } else {
  646. result = this.generate( builder, output ) || '';
  647. }
  648. }
  649. builder.removeChain( this );
  650. builder.addSequentialNode( this );
  651. return result;
  652. }
  653. getSerializeChildren() {
  654. return getNodeChildren( this );
  655. }
  656. serialize( json ) {
  657. const nodeChildren = this.getSerializeChildren();
  658. const inputNodes = {};
  659. for ( const { property, index, childNode } of nodeChildren ) {
  660. if ( index !== undefined ) {
  661. if ( inputNodes[ property ] === undefined ) {
  662. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  663. }
  664. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  665. } else {
  666. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  667. }
  668. }
  669. if ( Object.keys( inputNodes ).length > 0 ) {
  670. json.inputNodes = inputNodes;
  671. }
  672. }
  673. deserialize( json ) {
  674. if ( json.inputNodes !== undefined ) {
  675. const nodes = json.meta.nodes;
  676. for ( const property in json.inputNodes ) {
  677. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  678. const inputArray = [];
  679. for ( const uuid of json.inputNodes[ property ] ) {
  680. inputArray.push( nodes[ uuid ] );
  681. }
  682. this[ property ] = inputArray;
  683. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  684. const inputObject = {};
  685. for ( const subProperty in json.inputNodes[ property ] ) {
  686. const uuid = json.inputNodes[ property ][ subProperty ];
  687. inputObject[ subProperty ] = nodes[ uuid ];
  688. }
  689. this[ property ] = inputObject;
  690. } else {
  691. const uuid = json.inputNodes[ property ];
  692. this[ property ] = nodes[ uuid ];
  693. }
  694. }
  695. }
  696. }
  697. toJSON( meta ) {
  698. const { uuid, type } = this;
  699. const isRoot = ( meta === undefined || typeof meta === 'string' );
  700. if ( isRoot ) {
  701. meta = {
  702. textures: {},
  703. images: {},
  704. nodes: {}
  705. };
  706. }
  707. // serialize
  708. let data = meta.nodes[ uuid ];
  709. if ( data === undefined ) {
  710. data = {
  711. uuid,
  712. type,
  713. meta,
  714. metadata: {
  715. version: 4.6,
  716. type: 'Node',
  717. generator: 'Node.toJSON'
  718. }
  719. };
  720. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  721. this.serialize( data );
  722. delete data.meta;
  723. }
  724. // TODO: Copied from Object3D.toJSON
  725. function extractFromCache( cache ) {
  726. const values = [];
  727. for ( const key in cache ) {
  728. const data = cache[ key ];
  729. delete data.metadata;
  730. values.push( data );
  731. }
  732. return values;
  733. }
  734. if ( isRoot ) {
  735. const textures = extractFromCache( meta.textures );
  736. const images = extractFromCache( meta.images );
  737. const nodes = extractFromCache( meta.nodes );
  738. if ( textures.length > 0 ) data.textures = textures;
  739. if ( images.length > 0 ) data.images = images;
  740. if ( nodes.length > 0 ) data.nodes = nodes;
  741. }
  742. return data;
  743. }
  744. }
  745. class ArrayElementNode extends Node {
  746. static get type() {
  747. return 'ArrayElementNode';
  748. } // @TODO: If extending from TempNode it breaks webgpu_compute
  749. constructor( node, indexNode ) {
  750. super();
  751. this.node = node;
  752. this.indexNode = indexNode;
  753. this.isArrayElementNode = true;
  754. }
  755. getNodeType( builder ) {
  756. return this.node.getElementType( builder );
  757. }
  758. generate( builder ) {
  759. const nodeSnippet = this.node.build( builder );
  760. const indexSnippet = this.indexNode.build( builder, 'uint' );
  761. return `${nodeSnippet}[ ${indexSnippet} ]`;
  762. }
  763. }
  764. class ConvertNode extends Node {
  765. static get type() {
  766. return 'ConvertNode';
  767. }
  768. constructor( node, convertTo ) {
  769. super();
  770. this.node = node;
  771. this.convertTo = convertTo;
  772. }
  773. getNodeType( builder ) {
  774. const requestType = this.node.getNodeType( builder );
  775. let convertTo = null;
  776. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  777. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  778. convertTo = overloadingType;
  779. }
  780. }
  781. return convertTo;
  782. }
  783. serialize( data ) {
  784. super.serialize( data );
  785. data.convertTo = this.convertTo;
  786. }
  787. deserialize( data ) {
  788. super.deserialize( data );
  789. this.convertTo = data.convertTo;
  790. }
  791. generate( builder, output ) {
  792. const node = this.node;
  793. const type = this.getNodeType( builder );
  794. const snippet = node.build( builder, type );
  795. return builder.format( snippet, type, output );
  796. }
  797. }
  798. class TempNode extends Node {
  799. static get type() {
  800. return 'TempNode';
  801. }
  802. constructor( type ) {
  803. super( type );
  804. this.isTempNode = true;
  805. }
  806. hasDependencies( builder ) {
  807. return builder.getDataFromNode( this ).usageCount > 1;
  808. }
  809. build( builder, output ) {
  810. const buildStage = builder.getBuildStage();
  811. if ( buildStage === 'generate' ) {
  812. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  813. const nodeData = builder.getDataFromNode( this );
  814. if ( nodeData.propertyName !== undefined ) {
  815. return builder.format( nodeData.propertyName, type, output );
  816. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  817. const snippet = super.build( builder, type );
  818. const nodeVar = builder.getVarFromNode( this, null, type );
  819. const propertyName = builder.getPropertyName( nodeVar );
  820. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  821. nodeData.snippet = snippet;
  822. nodeData.propertyName = propertyName;
  823. return builder.format( nodeData.propertyName, type, output );
  824. }
  825. }
  826. return super.build( builder, output );
  827. }
  828. }
  829. class JoinNode extends TempNode {
  830. static get type() {
  831. return 'JoinNode';
  832. }
  833. constructor( nodes = [], nodeType = null ) {
  834. super( nodeType );
  835. this.nodes = nodes;
  836. }
  837. getNodeType( builder ) {
  838. if ( this.nodeType !== null ) {
  839. return builder.getVectorType( this.nodeType );
  840. }
  841. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  842. }
  843. generate( builder, output ) {
  844. const type = this.getNodeType( builder );
  845. const nodes = this.nodes;
  846. const primitiveType = builder.getComponentType( type );
  847. const snippetValues = [];
  848. for ( const input of nodes ) {
  849. let inputSnippet = input.build( builder );
  850. const inputPrimitiveType = builder.getComponentType( input.getNodeType( builder ) );
  851. if ( inputPrimitiveType !== primitiveType ) {
  852. inputSnippet = builder.format( inputSnippet, inputPrimitiveType, primitiveType );
  853. }
  854. snippetValues.push( inputSnippet );
  855. }
  856. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  857. return builder.format( snippet, type, output );
  858. }
  859. }
  860. const stringVectorComponents = vectorComponents.join( '' );
  861. class SplitNode extends Node {
  862. static get type() {
  863. return 'SplitNode';
  864. }
  865. constructor( node, components = 'x' ) {
  866. super();
  867. this.node = node;
  868. this.components = components;
  869. this.isSplitNode = true;
  870. }
  871. getVectorLength() {
  872. let vectorLength = this.components.length;
  873. for ( const c of this.components ) {
  874. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  875. }
  876. return vectorLength;
  877. }
  878. getComponentType( builder ) {
  879. return builder.getComponentType( this.node.getNodeType( builder ) );
  880. }
  881. getNodeType( builder ) {
  882. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  883. }
  884. generate( builder, output ) {
  885. const node = this.node;
  886. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  887. let snippet = null;
  888. if ( nodeTypeLength > 1 ) {
  889. let type = null;
  890. const componentsLength = this.getVectorLength();
  891. if ( componentsLength >= nodeTypeLength ) {
  892. // needed expand the input node
  893. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  894. }
  895. const nodeSnippet = node.build( builder, type );
  896. if ( this.components.length === nodeTypeLength && this.components === stringVectorComponents.slice( 0, this.components.length ) ) {
  897. // unnecessary swizzle
  898. snippet = builder.format( nodeSnippet, type, output );
  899. } else {
  900. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  901. }
  902. } else {
  903. // ignore .components if .node returns float/integer
  904. snippet = node.build( builder, output );
  905. }
  906. return snippet;
  907. }
  908. serialize( data ) {
  909. super.serialize( data );
  910. data.components = this.components;
  911. }
  912. deserialize( data ) {
  913. super.deserialize( data );
  914. this.components = data.components;
  915. }
  916. }
  917. class SetNode extends TempNode {
  918. static get type() {
  919. return 'SetNode';
  920. }
  921. constructor( sourceNode, components, targetNode ) {
  922. super();
  923. this.sourceNode = sourceNode;
  924. this.components = components;
  925. this.targetNode = targetNode;
  926. }
  927. getNodeType( builder ) {
  928. return this.sourceNode.getNodeType( builder );
  929. }
  930. generate( builder ) {
  931. const { sourceNode, components, targetNode } = this;
  932. const sourceType = this.getNodeType( builder );
  933. const targetType = builder.getTypeFromLength( components.length, targetNode.getNodeType( builder ) );
  934. const targetSnippet = targetNode.build( builder, targetType );
  935. const sourceSnippet = sourceNode.build( builder, sourceType );
  936. const length = builder.getTypeLength( sourceType );
  937. const snippetValues = [];
  938. for ( let i = 0; i < length; i ++ ) {
  939. const component = vectorComponents[ i ];
  940. if ( component === components[ 0 ] ) {
  941. snippetValues.push( targetSnippet );
  942. i += components.length - 1;
  943. } else {
  944. snippetValues.push( sourceSnippet + '.' + component );
  945. }
  946. }
  947. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  948. }
  949. }
  950. class FlipNode extends TempNode {
  951. static get type() {
  952. return 'FlipNode';
  953. }
  954. constructor( sourceNode, components ) {
  955. super();
  956. this.sourceNode = sourceNode;
  957. this.components = components;
  958. }
  959. getNodeType( builder ) {
  960. return this.sourceNode.getNodeType( builder );
  961. }
  962. generate( builder ) {
  963. const { components, sourceNode } = this;
  964. const sourceType = this.getNodeType( builder );
  965. const sourceSnippet = sourceNode.build( builder );
  966. const sourceCache = builder.getVarFromNode( this );
  967. const sourceProperty = builder.getPropertyName( sourceCache );
  968. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  969. const length = builder.getTypeLength( sourceType );
  970. const snippetValues = [];
  971. let componentIndex = 0;
  972. for ( let i = 0; i < length; i ++ ) {
  973. const component = vectorComponents[ i ];
  974. if ( component === components[ componentIndex ] ) {
  975. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  976. componentIndex ++;
  977. } else {
  978. snippetValues.push( sourceProperty + '.' + component );
  979. }
  980. }
  981. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  982. }
  983. }
  984. class InputNode extends Node {
  985. static get type() {
  986. return 'InputNode';
  987. }
  988. constructor( value, nodeType = null ) {
  989. super( nodeType );
  990. this.isInputNode = true;
  991. this.value = value;
  992. this.precision = null;
  993. }
  994. getNodeType( /*builder*/ ) {
  995. if ( this.nodeType === null ) {
  996. return getValueType( this.value );
  997. }
  998. return this.nodeType;
  999. }
  1000. getInputType( builder ) {
  1001. return this.getNodeType( builder );
  1002. }
  1003. setPrecision( precision ) {
  1004. this.precision = precision;
  1005. return this;
  1006. }
  1007. serialize( data ) {
  1008. super.serialize( data );
  1009. data.value = this.value;
  1010. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  1011. data.valueType = getValueType( this.value );
  1012. data.nodeType = this.nodeType;
  1013. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  1014. data.precision = this.precision;
  1015. }
  1016. deserialize( data ) {
  1017. super.deserialize( data );
  1018. this.nodeType = data.nodeType;
  1019. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  1020. this.precision = data.precision || null;
  1021. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  1022. }
  1023. generate( /*builder, output*/ ) {
  1024. console.warn( 'Abstract function.' );
  1025. }
  1026. }
  1027. class ConstNode extends InputNode {
  1028. static get type() {
  1029. return 'ConstNode';
  1030. }
  1031. constructor( value, nodeType = null ) {
  1032. super( value, nodeType );
  1033. this.isConstNode = true;
  1034. }
  1035. generateConst( builder ) {
  1036. return builder.generateConst( this.getNodeType( builder ), this.value );
  1037. }
  1038. generate( builder, output ) {
  1039. const type = this.getNodeType( builder );
  1040. return builder.format( this.generateConst( builder ), type, output );
  1041. }
  1042. }
  1043. //
  1044. let currentStack = null;
  1045. const NodeElements = new Map();
  1046. function addMethodChaining( name, nodeElement ) {
  1047. if ( NodeElements.has( name ) ) {
  1048. console.warn( `Redefinition of method chaining ${ name }` );
  1049. return;
  1050. }
  1051. if ( typeof nodeElement !== 'function' ) throw new Error( `Node element ${ name } is not a function` );
  1052. NodeElements.set( name, nodeElement );
  1053. }
  1054. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  1055. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  1056. const shaderNodeHandler = {
  1057. setup( NodeClosure, params ) {
  1058. const inputs = params.shift();
  1059. return NodeClosure( nodeObjects( inputs ), ...params );
  1060. },
  1061. get( node, prop, nodeObj ) {
  1062. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  1063. if ( node.isStackNode !== true && prop === 'assign' ) {
  1064. return ( ...params ) => {
  1065. currentStack.assign( nodeObj, ...params );
  1066. return nodeObj;
  1067. };
  1068. } else if ( NodeElements.has( prop ) ) {
  1069. const nodeElement = NodeElements.get( prop );
  1070. return node.isStackNode ? ( ...params ) => nodeObj.add( nodeElement( ...params ) ) : ( ...params ) => nodeElement( nodeObj, ...params );
  1071. } else if ( prop === 'self' ) {
  1072. return node;
  1073. } else if ( prop.endsWith( 'Assign' ) && NodeElements.has( prop.slice( 0, prop.length - 'Assign'.length ) ) ) {
  1074. const nodeElement = NodeElements.get( prop.slice( 0, prop.length - 'Assign'.length ) );
  1075. return node.isStackNode ? ( ...params ) => nodeObj.assign( params[ 0 ], nodeElement( ...params ) ) : ( ...params ) => nodeObj.assign( nodeElement( nodeObj, ...params ) );
  1076. } else if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true ) {
  1077. // accessing properties ( swizzle )
  1078. prop = parseSwizzle( prop );
  1079. return nodeObject( new SplitNode( nodeObj, prop ) );
  1080. } else if ( /^set[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  1081. // set properties ( swizzle ) and sort to xyzw sequence
  1082. prop = parseSwizzleAndSort( prop.slice( 3 ).toLowerCase() );
  1083. return ( value ) => nodeObject( new SetNode( node, prop, value ) );
  1084. } else if ( /^flip[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  1085. // set properties ( swizzle ) and sort to xyzw sequence
  1086. prop = parseSwizzleAndSort( prop.slice( 4 ).toLowerCase() );
  1087. return () => nodeObject( new FlipNode( nodeObject( node ), prop ) );
  1088. } else if ( prop === 'width' || prop === 'height' || prop === 'depth' ) {
  1089. // accessing property
  1090. if ( prop === 'width' ) prop = 'x';
  1091. else if ( prop === 'height' ) prop = 'y';
  1092. else if ( prop === 'depth' ) prop = 'z';
  1093. return nodeObject( new SplitNode( node, prop ) );
  1094. } else if ( /^\d+$/.test( prop ) === true ) {
  1095. // accessing array
  1096. return nodeObject( new ArrayElementNode( nodeObj, new ConstNode( Number( prop ), 'uint' ) ) );
  1097. }
  1098. }
  1099. return Reflect.get( node, prop, nodeObj );
  1100. },
  1101. set( node, prop, value, nodeObj ) {
  1102. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  1103. // setting properties
  1104. if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true || prop === 'width' || prop === 'height' || prop === 'depth' || /^\d+$/.test( prop ) === true ) {
  1105. nodeObj[ prop ].assign( value );
  1106. return true;
  1107. }
  1108. }
  1109. return Reflect.set( node, prop, value, nodeObj );
  1110. }
  1111. };
  1112. const nodeObjectsCacheMap = new WeakMap();
  1113. const nodeBuilderFunctionsCacheMap = new WeakMap();
  1114. const ShaderNodeObject = function ( obj, altType = null ) {
  1115. const type = getValueType( obj );
  1116. if ( type === 'node' ) {
  1117. let nodeObject = nodeObjectsCacheMap.get( obj );
  1118. if ( nodeObject === undefined ) {
  1119. nodeObject = new Proxy( obj, shaderNodeHandler );
  1120. nodeObjectsCacheMap.set( obj, nodeObject );
  1121. nodeObjectsCacheMap.set( nodeObject, nodeObject );
  1122. }
  1123. return nodeObject;
  1124. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  1125. return nodeObject( getConstNode( obj, altType ) );
  1126. } else if ( type === 'shader' ) {
  1127. return Fn( obj );
  1128. }
  1129. return obj;
  1130. };
  1131. const ShaderNodeObjects = function ( objects, altType = null ) {
  1132. for ( const name in objects ) {
  1133. objects[ name ] = nodeObject( objects[ name ], altType );
  1134. }
  1135. return objects;
  1136. };
  1137. const ShaderNodeArray = function ( array, altType = null ) {
  1138. const len = array.length;
  1139. for ( let i = 0; i < len; i ++ ) {
  1140. array[ i ] = nodeObject( array[ i ], altType );
  1141. }
  1142. return array;
  1143. };
  1144. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  1145. const assignNode = ( node ) => nodeObject( settings !== null ? Object.assign( node, settings ) : node );
  1146. if ( scope === null ) {
  1147. return ( ...params ) => {
  1148. return assignNode( new NodeClass( ...nodeArray( params ) ) );
  1149. };
  1150. } else if ( factor !== null ) {
  1151. factor = nodeObject( factor );
  1152. return ( ...params ) => {
  1153. return assignNode( new NodeClass( scope, ...nodeArray( params ), factor ) );
  1154. };
  1155. } else {
  1156. return ( ...params ) => {
  1157. return assignNode( new NodeClass( scope, ...nodeArray( params ) ) );
  1158. };
  1159. }
  1160. };
  1161. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  1162. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  1163. };
  1164. class ShaderCallNodeInternal extends Node {
  1165. constructor( shaderNode, inputNodes ) {
  1166. super();
  1167. this.shaderNode = shaderNode;
  1168. this.inputNodes = inputNodes;
  1169. }
  1170. getNodeType( builder ) {
  1171. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  1172. }
  1173. call( builder ) {
  1174. const { shaderNode, inputNodes } = this;
  1175. const properties = builder.getNodeProperties( shaderNode );
  1176. if ( properties.onceOutput ) return properties.onceOutput;
  1177. //
  1178. let result = null;
  1179. if ( shaderNode.layout ) {
  1180. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  1181. if ( functionNodesCacheMap === undefined ) {
  1182. functionNodesCacheMap = new WeakMap();
  1183. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  1184. }
  1185. let functionNode = functionNodesCacheMap.get( shaderNode );
  1186. if ( functionNode === undefined ) {
  1187. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  1188. functionNodesCacheMap.set( shaderNode, functionNode );
  1189. }
  1190. if ( builder.currentFunctionNode !== null ) {
  1191. builder.currentFunctionNode.includes.push( functionNode );
  1192. }
  1193. result = nodeObject( functionNode.call( inputNodes ) );
  1194. } else {
  1195. const jsFunc = shaderNode.jsFunc;
  1196. const outputNode = inputNodes !== null ? jsFunc( inputNodes, builder ) : jsFunc( builder );
  1197. result = nodeObject( outputNode );
  1198. }
  1199. if ( shaderNode.once ) {
  1200. properties.onceOutput = result;
  1201. }
  1202. return result;
  1203. }
  1204. getOutputNode( builder ) {
  1205. const properties = builder.getNodeProperties( this );
  1206. if ( properties.outputNode === null ) {
  1207. properties.outputNode = this.setupOutput( builder );
  1208. }
  1209. return properties.outputNode;
  1210. }
  1211. setup( builder ) {
  1212. return this.getOutputNode( builder );
  1213. }
  1214. setupOutput( builder ) {
  1215. builder.addStack();
  1216. builder.stack.outputNode = this.call( builder );
  1217. return builder.removeStack();
  1218. }
  1219. generate( builder, output ) {
  1220. const outputNode = this.getOutputNode( builder );
  1221. return outputNode.build( builder, output );
  1222. }
  1223. }
  1224. class ShaderNodeInternal extends Node {
  1225. constructor( jsFunc, nodeType ) {
  1226. super( nodeType );
  1227. this.jsFunc = jsFunc;
  1228. this.layout = null;
  1229. this.global = true;
  1230. this.once = false;
  1231. }
  1232. setLayout( layout ) {
  1233. this.layout = layout;
  1234. return this;
  1235. }
  1236. call( inputs = null ) {
  1237. nodeObjects( inputs );
  1238. return nodeObject( new ShaderCallNodeInternal( this, inputs ) );
  1239. }
  1240. setup() {
  1241. return this.call();
  1242. }
  1243. }
  1244. const bools = [ false, true ];
  1245. const uints = [ 0, 1, 2, 3 ];
  1246. const ints = [ - 1, - 2 ];
  1247. 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 ];
  1248. const boolsCacheMap = new Map();
  1249. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  1250. const uintsCacheMap = new Map();
  1251. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  1252. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  1253. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  1254. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  1255. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  1256. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  1257. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  1258. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  1259. const getConstNode = ( value, type ) => {
  1260. if ( constNodesCacheMap.has( value ) ) {
  1261. return constNodesCacheMap.get( value );
  1262. } else if ( value.isNode === true ) {
  1263. return value;
  1264. } else {
  1265. return new ConstNode( value, type );
  1266. }
  1267. };
  1268. const safeGetNodeType = ( node ) => {
  1269. try {
  1270. return node.getNodeType();
  1271. } catch ( _ ) {
  1272. return undefined;
  1273. }
  1274. };
  1275. const ConvertType = function ( type, cacheMap = null ) {
  1276. return ( ...params ) => {
  1277. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => typeof param !== 'object' ) ) ) {
  1278. params = [ getValueFromType( type, ...params ) ];
  1279. }
  1280. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  1281. return nodeObject( cacheMap.get( params[ 0 ] ) );
  1282. }
  1283. if ( params.length === 1 ) {
  1284. const node = getConstNode( params[ 0 ], type );
  1285. if ( safeGetNodeType( node ) === type ) return nodeObject( node );
  1286. return nodeObject( new ConvertNode( node, type ) );
  1287. }
  1288. const nodes = params.map( param => getConstNode( param ) );
  1289. return nodeObject( new JoinNode( nodes, type ) );
  1290. };
  1291. };
  1292. // exports
  1293. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  1294. // utils
  1295. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  1296. // shader node base
  1297. function ShaderNode( jsFunc, nodeType ) {
  1298. return new Proxy( new ShaderNodeInternal( jsFunc, nodeType ), shaderNodeHandler );
  1299. }
  1300. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  1301. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  1302. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  1303. const nodeProxy = ( ...params ) => new ShaderNodeProxy( ...params );
  1304. const nodeImmutable = ( ...params ) => new ShaderNodeImmutable( ...params );
  1305. const Fn = ( jsFunc, nodeType ) => {
  1306. const shaderNode = new ShaderNode( jsFunc, nodeType );
  1307. const fn = ( ...params ) => {
  1308. let inputs;
  1309. nodeObjects( params );
  1310. if ( params[ 0 ] && params[ 0 ].isNode ) {
  1311. inputs = [ ...params ];
  1312. } else {
  1313. inputs = params[ 0 ];
  1314. }
  1315. return shaderNode.call( inputs );
  1316. };
  1317. fn.shaderNode = shaderNode;
  1318. fn.setLayout = ( layout ) => {
  1319. shaderNode.setLayout( layout );
  1320. return fn;
  1321. };
  1322. fn.once = () => {
  1323. shaderNode.once = true;
  1324. return fn;
  1325. };
  1326. return fn;
  1327. };
  1328. const tslFn = ( ...params ) => { // @deprecated, r168
  1329. console.warn( 'TSL.ShaderNode: tslFn() has been renamed to Fn().' );
  1330. return Fn( ...params );
  1331. };
  1332. //
  1333. addMethodChaining( 'toGlobal', ( node ) => {
  1334. node.global = true;
  1335. return node;
  1336. } );
  1337. //
  1338. const setCurrentStack = ( stack ) => {
  1339. currentStack = stack;
  1340. };
  1341. const getCurrentStack = () => currentStack;
  1342. const If = ( ...params ) => currentStack.If( ...params );
  1343. function append( node ) {
  1344. if ( currentStack ) currentStack.add( node );
  1345. return node;
  1346. }
  1347. addMethodChaining( 'append', append );
  1348. // types
  1349. const color = new ConvertType( 'color' );
  1350. const float = new ConvertType( 'float', cacheMaps.float );
  1351. const int = new ConvertType( 'int', cacheMaps.ints );
  1352. const uint = new ConvertType( 'uint', cacheMaps.uint );
  1353. const bool = new ConvertType( 'bool', cacheMaps.bool );
  1354. const vec2 = new ConvertType( 'vec2' );
  1355. const ivec2 = new ConvertType( 'ivec2' );
  1356. const uvec2 = new ConvertType( 'uvec2' );
  1357. const bvec2 = new ConvertType( 'bvec2' );
  1358. const vec3 = new ConvertType( 'vec3' );
  1359. const ivec3 = new ConvertType( 'ivec3' );
  1360. const uvec3 = new ConvertType( 'uvec3' );
  1361. const bvec3 = new ConvertType( 'bvec3' );
  1362. const vec4 = new ConvertType( 'vec4' );
  1363. const ivec4 = new ConvertType( 'ivec4' );
  1364. const uvec4 = new ConvertType( 'uvec4' );
  1365. const bvec4 = new ConvertType( 'bvec4' );
  1366. const mat2 = new ConvertType( 'mat2' );
  1367. const mat3 = new ConvertType( 'mat3' );
  1368. const mat4 = new ConvertType( 'mat4' );
  1369. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  1370. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  1371. addMethodChaining( 'toColor', color );
  1372. addMethodChaining( 'toFloat', float );
  1373. addMethodChaining( 'toInt', int );
  1374. addMethodChaining( 'toUint', uint );
  1375. addMethodChaining( 'toBool', bool );
  1376. addMethodChaining( 'toVec2', vec2 );
  1377. addMethodChaining( 'toIVec2', ivec2 );
  1378. addMethodChaining( 'toUVec2', uvec2 );
  1379. addMethodChaining( 'toBVec2', bvec2 );
  1380. addMethodChaining( 'toVec3', vec3 );
  1381. addMethodChaining( 'toIVec3', ivec3 );
  1382. addMethodChaining( 'toUVec3', uvec3 );
  1383. addMethodChaining( 'toBVec3', bvec3 );
  1384. addMethodChaining( 'toVec4', vec4 );
  1385. addMethodChaining( 'toIVec4', ivec4 );
  1386. addMethodChaining( 'toUVec4', uvec4 );
  1387. addMethodChaining( 'toBVec4', bvec4 );
  1388. addMethodChaining( 'toMat2', mat2 );
  1389. addMethodChaining( 'toMat3', mat3 );
  1390. addMethodChaining( 'toMat4', mat4 );
  1391. // basic nodes
  1392. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode );
  1393. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  1394. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  1395. addMethodChaining( 'element', element );
  1396. addMethodChaining( 'convert', convert );
  1397. class UniformGroupNode extends Node {
  1398. static get type() {
  1399. return 'UniformGroupNode';
  1400. }
  1401. constructor( name, shared = false, order = 1 ) {
  1402. super( 'string' );
  1403. this.name = name;
  1404. this.version = 0;
  1405. this.shared = shared;
  1406. this.order = order;
  1407. this.isUniformGroup = true;
  1408. }
  1409. set needsUpdate( value ) {
  1410. if ( value === true ) this.version ++;
  1411. }
  1412. serialize( data ) {
  1413. super.serialize( data );
  1414. data.name = this.name;
  1415. data.version = this.version;
  1416. data.shared = this.shared;
  1417. }
  1418. deserialize( data ) {
  1419. super.deserialize( data );
  1420. this.name = data.name;
  1421. this.version = data.version;
  1422. this.shared = data.shared;
  1423. }
  1424. }
  1425. const uniformGroup = ( name ) => new UniformGroupNode( name );
  1426. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  1427. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  1428. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  1429. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  1430. class UniformNode extends InputNode {
  1431. static get type() {
  1432. return 'UniformNode';
  1433. }
  1434. constructor( value, nodeType = null ) {
  1435. super( value, nodeType );
  1436. this.isUniformNode = true;
  1437. this.name = '';
  1438. this.groupNode = objectGroup;
  1439. }
  1440. label( name ) {
  1441. this.name = name;
  1442. return this;
  1443. }
  1444. setGroup( group ) {
  1445. this.groupNode = group;
  1446. return this;
  1447. }
  1448. getGroup() {
  1449. return this.groupNode;
  1450. }
  1451. getUniformHash( builder ) {
  1452. return this.getHash( builder );
  1453. }
  1454. onUpdate( callback, updateType ) {
  1455. const self = this.getSelf();
  1456. callback = callback.bind( self );
  1457. return super.onUpdate( ( frame ) => {
  1458. const value = callback( frame, self );
  1459. if ( value !== undefined ) {
  1460. this.value = value;
  1461. }
  1462. }, updateType );
  1463. }
  1464. generate( builder, output ) {
  1465. const type = this.getNodeType( builder );
  1466. const hash = this.getUniformHash( builder );
  1467. let sharedNode = builder.getNodeFromHash( hash );
  1468. if ( sharedNode === undefined ) {
  1469. builder.setHashNode( this, hash );
  1470. sharedNode = this;
  1471. }
  1472. const sharedNodeType = sharedNode.getInputType( builder );
  1473. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.label );
  1474. const propertyName = builder.getPropertyName( nodeUniform );
  1475. if ( builder.context.label !== undefined ) delete builder.context.label;
  1476. return builder.format( propertyName, type, output );
  1477. }
  1478. }
  1479. const uniform = ( arg1, arg2 ) => {
  1480. const nodeType = getConstNodeType( arg2 || arg1 );
  1481. // @TODO: get ConstNode from .traverse() in the future
  1482. const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1;
  1483. return nodeObject( new UniformNode( value, nodeType ) );
  1484. };
  1485. class PropertyNode extends Node {
  1486. static get type() {
  1487. return 'PropertyNode';
  1488. }
  1489. constructor( nodeType, name = null, varying = false ) {
  1490. super( nodeType );
  1491. this.name = name;
  1492. this.varying = varying;
  1493. this.isPropertyNode = true;
  1494. }
  1495. getHash( builder ) {
  1496. return this.name || super.getHash( builder );
  1497. }
  1498. isGlobal( /*builder*/ ) {
  1499. return true;
  1500. }
  1501. generate( builder ) {
  1502. let nodeVar;
  1503. if ( this.varying === true ) {
  1504. nodeVar = builder.getVaryingFromNode( this, this.name );
  1505. nodeVar.needsInterpolation = true;
  1506. } else {
  1507. nodeVar = builder.getVarFromNode( this, this.name );
  1508. }
  1509. return builder.getPropertyName( nodeVar );
  1510. }
  1511. }
  1512. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  1513. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  1514. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  1515. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  1516. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  1517. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  1518. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  1519. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  1520. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  1521. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  1522. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  1523. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  1524. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  1525. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  1526. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  1527. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  1528. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  1529. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  1530. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  1531. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  1532. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  1533. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  1534. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  1535. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  1536. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  1537. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  1538. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  1539. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  1540. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  1541. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  1542. class AssignNode extends TempNode {
  1543. static get type() {
  1544. return 'AssignNode';
  1545. }
  1546. constructor( targetNode, sourceNode ) {
  1547. super();
  1548. this.targetNode = targetNode;
  1549. this.sourceNode = sourceNode;
  1550. }
  1551. hasDependencies() {
  1552. return false;
  1553. }
  1554. getNodeType( builder, output ) {
  1555. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  1556. }
  1557. needsSplitAssign( builder ) {
  1558. const { targetNode } = this;
  1559. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  1560. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  1561. const assignDiferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  1562. return assignDiferentVector;
  1563. }
  1564. return false;
  1565. }
  1566. generate( builder, output ) {
  1567. const { targetNode, sourceNode } = this;
  1568. const needsSplitAssign = this.needsSplitAssign( builder );
  1569. const targetType = targetNode.getNodeType( builder );
  1570. const target = targetNode.context( { assign: true } ).build( builder );
  1571. const source = sourceNode.build( builder, targetType );
  1572. const sourceType = sourceNode.getNodeType( builder );
  1573. const nodeData = builder.getDataFromNode( this );
  1574. //
  1575. let snippet;
  1576. if ( nodeData.initialized === true ) {
  1577. if ( output !== 'void' ) {
  1578. snippet = target;
  1579. }
  1580. } else if ( needsSplitAssign ) {
  1581. const sourceVar = builder.getVarFromNode( this, null, targetType );
  1582. const sourceProperty = builder.getPropertyName( sourceVar );
  1583. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  1584. const targetRoot = targetNode.node.context( { assign: true } ).build( builder );
  1585. for ( let i = 0; i < targetNode.components.length; i ++ ) {
  1586. const component = targetNode.components[ i ];
  1587. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  1588. }
  1589. if ( output !== 'void' ) {
  1590. snippet = target;
  1591. }
  1592. } else {
  1593. snippet = `${ target } = ${ source }`;
  1594. if ( output === 'void' || sourceType === 'void' ) {
  1595. builder.addLineFlowCode( snippet, this );
  1596. if ( output !== 'void' ) {
  1597. snippet = target;
  1598. }
  1599. }
  1600. }
  1601. nodeData.initialized = true;
  1602. return builder.format( snippet, targetType, output );
  1603. }
  1604. }
  1605. const assign = /*@__PURE__*/ nodeProxy( AssignNode );
  1606. addMethodChaining( 'assign', assign );
  1607. class FunctionCallNode extends TempNode {
  1608. static get type() {
  1609. return 'FunctionCallNode';
  1610. }
  1611. constructor( functionNode = null, parameters = {} ) {
  1612. super();
  1613. this.functionNode = functionNode;
  1614. this.parameters = parameters;
  1615. }
  1616. setParameters( parameters ) {
  1617. this.parameters = parameters;
  1618. return this;
  1619. }
  1620. getParameters() {
  1621. return this.parameters;
  1622. }
  1623. getNodeType( builder ) {
  1624. return this.functionNode.getNodeType( builder );
  1625. }
  1626. generate( builder ) {
  1627. const params = [];
  1628. const functionNode = this.functionNode;
  1629. const inputs = functionNode.getInputs( builder );
  1630. const parameters = this.parameters;
  1631. const generateInput = ( node, inputNode ) => {
  1632. const type = inputNode.type;
  1633. const pointer = type === 'pointer';
  1634. let output;
  1635. if ( pointer ) output = '&' + node.build( builder );
  1636. else output = node.build( builder, type );
  1637. return output;
  1638. };
  1639. if ( Array.isArray( parameters ) ) {
  1640. for ( let i = 0; i < parameters.length; i ++ ) {
  1641. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  1642. }
  1643. } else {
  1644. for ( const inputNode of inputs ) {
  1645. const node = parameters[ inputNode.name ];
  1646. if ( node !== undefined ) {
  1647. params.push( generateInput( node, inputNode ) );
  1648. } else {
  1649. throw new Error( `FunctionCallNode: Input '${inputNode.name}' not found in FunctionNode.` );
  1650. }
  1651. }
  1652. }
  1653. const functionName = functionNode.build( builder, 'property' );
  1654. return `${functionName}( ${params.join( ', ' )} )`;
  1655. }
  1656. }
  1657. const call = ( func, ...params ) => {
  1658. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  1659. return nodeObject( new FunctionCallNode( nodeObject( func ), params ) );
  1660. };
  1661. addMethodChaining( 'call', call );
  1662. class OperatorNode extends TempNode {
  1663. static get type() {
  1664. return 'OperatorNode';
  1665. }
  1666. constructor( op, aNode, bNode, ...params ) {
  1667. super();
  1668. if ( params.length > 0 ) {
  1669. let finalOp = new OperatorNode( op, aNode, bNode );
  1670. for ( let i = 0; i < params.length - 1; i ++ ) {
  1671. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  1672. }
  1673. aNode = finalOp;
  1674. bNode = params[ params.length - 1 ];
  1675. }
  1676. this.op = op;
  1677. this.aNode = aNode;
  1678. this.bNode = bNode;
  1679. }
  1680. getNodeType( builder, output ) {
  1681. const op = this.op;
  1682. const aNode = this.aNode;
  1683. const bNode = this.bNode;
  1684. const typeA = aNode.getNodeType( builder );
  1685. const typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  1686. if ( typeA === 'void' || typeB === 'void' ) {
  1687. return 'void';
  1688. } else if ( op === '%' ) {
  1689. return typeA;
  1690. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  1691. return builder.getIntegerType( typeA );
  1692. } else if ( op === '!' || op === '==' || op === '&&' || op === '||' || op === '^^' ) {
  1693. return 'bool';
  1694. } else if ( op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  1695. const typeLength = output ? builder.getTypeLength( output ) : Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  1696. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  1697. } else {
  1698. if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  1699. return typeB;
  1700. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  1701. // matrix x vector
  1702. return builder.getVectorFromMatrix( typeA );
  1703. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  1704. // vector x matrix
  1705. return builder.getVectorFromMatrix( typeB );
  1706. } else if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  1707. // anytype x anytype: use the greater length vector
  1708. return typeB;
  1709. }
  1710. return typeA;
  1711. }
  1712. }
  1713. generate( builder, output ) {
  1714. const op = this.op;
  1715. const aNode = this.aNode;
  1716. const bNode = this.bNode;
  1717. const type = this.getNodeType( builder, output );
  1718. let typeA = null;
  1719. let typeB = null;
  1720. if ( type !== 'void' ) {
  1721. typeA = aNode.getNodeType( builder );
  1722. typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  1723. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' ) {
  1724. if ( builder.isVector( typeA ) ) {
  1725. typeB = typeA;
  1726. } else if ( typeA !== typeB ) {
  1727. typeA = typeB = 'float';
  1728. }
  1729. } else if ( op === '>>' || op === '<<' ) {
  1730. typeA = type;
  1731. typeB = builder.changeComponentType( typeB, 'uint' );
  1732. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  1733. // matrix x vector
  1734. typeB = builder.getVectorFromMatrix( typeA );
  1735. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  1736. // vector x matrix
  1737. typeA = builder.getVectorFromMatrix( typeB );
  1738. } else {
  1739. // anytype x anytype
  1740. typeA = typeB = type;
  1741. }
  1742. } else {
  1743. typeA = typeB = type;
  1744. }
  1745. const a = aNode.build( builder, typeA );
  1746. const b = typeof bNode !== 'undefined' ? bNode.build( builder, typeB ) : null;
  1747. const outputLength = builder.getTypeLength( output );
  1748. const fnOpSnippet = builder.getFunctionOperator( op );
  1749. if ( output !== 'void' ) {
  1750. if ( op === '<' && outputLength > 1 ) {
  1751. if ( builder.useComparisonMethod ) {
  1752. return builder.format( `${ builder.getMethod( 'lessThan', output ) }( ${ a }, ${ b } )`, type, output );
  1753. } else {
  1754. return builder.format( `( ${ a } < ${ b } )`, type, output );
  1755. }
  1756. } else if ( op === '<=' && outputLength > 1 ) {
  1757. if ( builder.useComparisonMethod ) {
  1758. return builder.format( `${ builder.getMethod( 'lessThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  1759. } else {
  1760. return builder.format( `( ${ a } <= ${ b } )`, type, output );
  1761. }
  1762. } else if ( op === '>' && outputLength > 1 ) {
  1763. if ( builder.useComparisonMethod ) {
  1764. return builder.format( `${ builder.getMethod( 'greaterThan', output ) }( ${ a }, ${ b } )`, type, output );
  1765. } else {
  1766. return builder.format( `( ${ a } > ${ b } )`, type, output );
  1767. }
  1768. } else if ( op === '>=' && outputLength > 1 ) {
  1769. if ( builder.useComparisonMethod ) {
  1770. return builder.format( `${ builder.getMethod( 'greaterThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  1771. } else {
  1772. return builder.format( `( ${ a } >= ${ b } )`, type, output );
  1773. }
  1774. } else if ( op === '!' || op === '~' ) {
  1775. return builder.format( `(${op}${a})`, typeA, output );
  1776. } else if ( fnOpSnippet ) {
  1777. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  1778. } else {
  1779. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  1780. }
  1781. } else if ( typeA !== 'void' ) {
  1782. if ( fnOpSnippet ) {
  1783. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  1784. } else {
  1785. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  1786. }
  1787. }
  1788. }
  1789. serialize( data ) {
  1790. super.serialize( data );
  1791. data.op = this.op;
  1792. }
  1793. deserialize( data ) {
  1794. super.deserialize( data );
  1795. this.op = data.op;
  1796. }
  1797. }
  1798. const add = /*@__PURE__*/ nodeProxy( OperatorNode, '+' );
  1799. const sub = /*@__PURE__*/ nodeProxy( OperatorNode, '-' );
  1800. const mul = /*@__PURE__*/ nodeProxy( OperatorNode, '*' );
  1801. const div = /*@__PURE__*/ nodeProxy( OperatorNode, '/' );
  1802. const modInt = /*@__PURE__*/ nodeProxy( OperatorNode, '%' );
  1803. const equal = /*@__PURE__*/ nodeProxy( OperatorNode, '==' );
  1804. const notEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '!=' );
  1805. const lessThan = /*@__PURE__*/ nodeProxy( OperatorNode, '<' );
  1806. const greaterThan = /*@__PURE__*/ nodeProxy( OperatorNode, '>' );
  1807. const lessThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '<=' );
  1808. const greaterThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '>=' );
  1809. const and = /*@__PURE__*/ nodeProxy( OperatorNode, '&&' );
  1810. const or = /*@__PURE__*/ nodeProxy( OperatorNode, '||' );
  1811. const not = /*@__PURE__*/ nodeProxy( OperatorNode, '!' );
  1812. const xor = /*@__PURE__*/ nodeProxy( OperatorNode, '^^' );
  1813. const bitAnd = /*@__PURE__*/ nodeProxy( OperatorNode, '&' );
  1814. const bitNot = /*@__PURE__*/ nodeProxy( OperatorNode, '~' );
  1815. const bitOr = /*@__PURE__*/ nodeProxy( OperatorNode, '|' );
  1816. const bitXor = /*@__PURE__*/ nodeProxy( OperatorNode, '^' );
  1817. const shiftLeft = /*@__PURE__*/ nodeProxy( OperatorNode, '<<' );
  1818. const shiftRight = /*@__PURE__*/ nodeProxy( OperatorNode, '>>' );
  1819. addMethodChaining( 'add', add );
  1820. addMethodChaining( 'sub', sub );
  1821. addMethodChaining( 'mul', mul );
  1822. addMethodChaining( 'div', div );
  1823. addMethodChaining( 'modInt', modInt );
  1824. addMethodChaining( 'equal', equal );
  1825. addMethodChaining( 'notEqual', notEqual );
  1826. addMethodChaining( 'lessThan', lessThan );
  1827. addMethodChaining( 'greaterThan', greaterThan );
  1828. addMethodChaining( 'lessThanEqual', lessThanEqual );
  1829. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  1830. addMethodChaining( 'and', and );
  1831. addMethodChaining( 'or', or );
  1832. addMethodChaining( 'not', not );
  1833. addMethodChaining( 'xor', xor );
  1834. addMethodChaining( 'bitAnd', bitAnd );
  1835. addMethodChaining( 'bitNot', bitNot );
  1836. addMethodChaining( 'bitOr', bitOr );
  1837. addMethodChaining( 'bitXor', bitXor );
  1838. addMethodChaining( 'shiftLeft', shiftLeft );
  1839. addMethodChaining( 'shiftRight', shiftRight );
  1840. const remainder = ( ...params ) => { // @deprecated, r168
  1841. console.warn( 'TSL.OperatorNode: .remainder() has been renamed to .modInt().' );
  1842. return modInt( ...params );
  1843. };
  1844. addMethodChaining( 'remainder', remainder );
  1845. class MathNode extends TempNode {
  1846. static get type() {
  1847. return 'MathNode';
  1848. }
  1849. constructor( method, aNode, bNode = null, cNode = null ) {
  1850. super();
  1851. this.method = method;
  1852. this.aNode = aNode;
  1853. this.bNode = bNode;
  1854. this.cNode = cNode;
  1855. }
  1856. getInputType( builder ) {
  1857. const aType = this.aNode.getNodeType( builder );
  1858. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  1859. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  1860. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  1861. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  1862. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  1863. if ( aLen > bLen && aLen > cLen ) {
  1864. return aType;
  1865. } else if ( bLen > cLen ) {
  1866. return bType;
  1867. } else if ( cLen > aLen ) {
  1868. return cType;
  1869. }
  1870. return aType;
  1871. }
  1872. getNodeType( builder ) {
  1873. const method = this.method;
  1874. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  1875. return 'float';
  1876. } else if ( method === MathNode.CROSS ) {
  1877. return 'vec3';
  1878. } else if ( method === MathNode.ALL ) {
  1879. return 'bool';
  1880. } else if ( method === MathNode.EQUALS ) {
  1881. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  1882. } else if ( method === MathNode.MOD ) {
  1883. return this.aNode.getNodeType( builder );
  1884. } else {
  1885. return this.getInputType( builder );
  1886. }
  1887. }
  1888. generate( builder, output ) {
  1889. const method = this.method;
  1890. const type = this.getNodeType( builder );
  1891. const inputType = this.getInputType( builder );
  1892. const a = this.aNode;
  1893. const b = this.bNode;
  1894. const c = this.cNode;
  1895. const isWebGL = builder.renderer.isWebGLRenderer === true;
  1896. if ( method === MathNode.TRANSFORM_DIRECTION ) {
  1897. // dir can be either a direction vector or a normal vector
  1898. // upper-left 3x3 of matrix is assumed to be orthogonal
  1899. let tA = a;
  1900. let tB = b;
  1901. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  1902. tB = vec4( vec3( tB ), 0.0 );
  1903. } else {
  1904. tA = vec4( vec3( tA ), 0.0 );
  1905. }
  1906. const mulNode = mul( tA, tB ).xyz;
  1907. return normalize( mulNode ).build( builder, output );
  1908. } else if ( method === MathNode.NEGATE ) {
  1909. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  1910. } else if ( method === MathNode.ONE_MINUS ) {
  1911. return sub( 1.0, a ).build( builder, output );
  1912. } else if ( method === MathNode.RECIPROCAL ) {
  1913. return div( 1.0, a ).build( builder, output );
  1914. } else if ( method === MathNode.DIFFERENCE ) {
  1915. return abs( sub( a, b ) ).build( builder, output );
  1916. } else {
  1917. const params = [];
  1918. if ( method === MathNode.CROSS || method === MathNode.MOD ) {
  1919. params.push(
  1920. a.build( builder, type ),
  1921. b.build( builder, type )
  1922. );
  1923. } else if ( isWebGL && method === MathNode.STEP ) {
  1924. params.push(
  1925. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  1926. b.build( builder, inputType )
  1927. );
  1928. } else if ( ( isWebGL && ( method === MathNode.MIN || method === MathNode.MAX ) ) || method === MathNode.MOD ) {
  1929. params.push(
  1930. a.build( builder, inputType ),
  1931. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  1932. );
  1933. } else if ( method === MathNode.REFRACT ) {
  1934. params.push(
  1935. a.build( builder, inputType ),
  1936. b.build( builder, inputType ),
  1937. c.build( builder, 'float' )
  1938. );
  1939. } else if ( method === MathNode.MIX ) {
  1940. params.push(
  1941. a.build( builder, inputType ),
  1942. b.build( builder, inputType ),
  1943. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  1944. );
  1945. } else {
  1946. params.push( a.build( builder, inputType ) );
  1947. if ( b !== null ) params.push( b.build( builder, inputType ) );
  1948. if ( c !== null ) params.push( c.build( builder, inputType ) );
  1949. }
  1950. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  1951. }
  1952. }
  1953. serialize( data ) {
  1954. super.serialize( data );
  1955. data.method = this.method;
  1956. }
  1957. deserialize( data ) {
  1958. super.deserialize( data );
  1959. this.method = data.method;
  1960. }
  1961. }
  1962. // 1 input
  1963. MathNode.ALL = 'all';
  1964. MathNode.ANY = 'any';
  1965. MathNode.EQUALS = 'equals';
  1966. MathNode.RADIANS = 'radians';
  1967. MathNode.DEGREES = 'degrees';
  1968. MathNode.EXP = 'exp';
  1969. MathNode.EXP2 = 'exp2';
  1970. MathNode.LOG = 'log';
  1971. MathNode.LOG2 = 'log2';
  1972. MathNode.SQRT = 'sqrt';
  1973. MathNode.INVERSE_SQRT = 'inversesqrt';
  1974. MathNode.FLOOR = 'floor';
  1975. MathNode.CEIL = 'ceil';
  1976. MathNode.NORMALIZE = 'normalize';
  1977. MathNode.FRACT = 'fract';
  1978. MathNode.SIN = 'sin';
  1979. MathNode.COS = 'cos';
  1980. MathNode.TAN = 'tan';
  1981. MathNode.ASIN = 'asin';
  1982. MathNode.ACOS = 'acos';
  1983. MathNode.ATAN = 'atan';
  1984. MathNode.ABS = 'abs';
  1985. MathNode.SIGN = 'sign';
  1986. MathNode.LENGTH = 'length';
  1987. MathNode.NEGATE = 'negate';
  1988. MathNode.ONE_MINUS = 'oneMinus';
  1989. MathNode.DFDX = 'dFdx';
  1990. MathNode.DFDY = 'dFdy';
  1991. MathNode.ROUND = 'round';
  1992. MathNode.RECIPROCAL = 'reciprocal';
  1993. MathNode.TRUNC = 'trunc';
  1994. MathNode.FWIDTH = 'fwidth';
  1995. MathNode.BITCAST = 'bitcast';
  1996. MathNode.TRANSPOSE = 'transpose';
  1997. // 2 inputs
  1998. MathNode.ATAN2 = 'atan2';
  1999. MathNode.MIN = 'min';
  2000. MathNode.MAX = 'max';
  2001. MathNode.MOD = 'mod';
  2002. MathNode.STEP = 'step';
  2003. MathNode.REFLECT = 'reflect';
  2004. MathNode.DISTANCE = 'distance';
  2005. MathNode.DIFFERENCE = 'difference';
  2006. MathNode.DOT = 'dot';
  2007. MathNode.CROSS = 'cross';
  2008. MathNode.POW = 'pow';
  2009. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  2010. // 3 inputs
  2011. MathNode.MIX = 'mix';
  2012. MathNode.CLAMP = 'clamp';
  2013. MathNode.REFRACT = 'refract';
  2014. MathNode.SMOOTHSTEP = 'smoothstep';
  2015. MathNode.FACEFORWARD = 'faceforward';
  2016. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  2017. const INFINITY = /*@__PURE__*/ float( 1e6 );
  2018. const PI = /*@__PURE__*/ float( Math.PI );
  2019. const PI2 = /*@__PURE__*/ float( Math.PI * 2 );
  2020. const all = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ALL );
  2021. const any = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ANY );
  2022. const equals = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EQUALS );
  2023. const radians = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RADIANS );
  2024. const degrees = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DEGREES );
  2025. const exp = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP );
  2026. const exp2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP2 );
  2027. const log = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG );
  2028. const log2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG2 );
  2029. const sqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SQRT );
  2030. const inverseSqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.INVERSE_SQRT );
  2031. const floor = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FLOOR );
  2032. const ceil = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CEIL );
  2033. const normalize = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NORMALIZE );
  2034. const fract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FRACT );
  2035. const sin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIN );
  2036. const cos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.COS );
  2037. const tan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TAN );
  2038. const asin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ASIN );
  2039. const acos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ACOS );
  2040. const atan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN );
  2041. const abs = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ABS );
  2042. const sign = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIGN );
  2043. const length = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LENGTH );
  2044. const negate = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NEGATE );
  2045. const oneMinus = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ONE_MINUS );
  2046. const dFdx = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDX );
  2047. const dFdy = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDY );
  2048. const round = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ROUND );
  2049. const reciprocal = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RECIPROCAL );
  2050. const trunc = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRUNC );
  2051. const fwidth = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FWIDTH );
  2052. const bitcast = /*@__PURE__*/ nodeProxy( MathNode, MathNode.BITCAST );
  2053. const transpose = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSPOSE );
  2054. const atan2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN2 );
  2055. const min$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIN );
  2056. const max$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MAX );
  2057. const mod = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MOD );
  2058. const step = /*@__PURE__*/ nodeProxy( MathNode, MathNode.STEP );
  2059. const reflect = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFLECT );
  2060. const distance = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DISTANCE );
  2061. const difference = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DIFFERENCE );
  2062. const dot = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DOT );
  2063. const cross = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CROSS );
  2064. const pow = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW );
  2065. const pow2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 2 );
  2066. const pow3 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 3 );
  2067. const pow4 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 4 );
  2068. const transformDirection = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSFORM_DIRECTION );
  2069. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  2070. const lengthSq = ( a ) => dot( a, a );
  2071. const mix = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIX );
  2072. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  2073. const saturate = ( value ) => clamp( value );
  2074. const refract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFRACT );
  2075. const smoothstep = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SMOOTHSTEP );
  2076. const faceForward = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FACEFORWARD );
  2077. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  2078. const a = 12.9898, b = 78.233, c = 43758.5453;
  2079. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  2080. return fract( sin( sn ).mul( c ) );
  2081. } );
  2082. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  2083. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  2084. addMethodChaining( 'all', all );
  2085. addMethodChaining( 'any', any );
  2086. addMethodChaining( 'equals', equals );
  2087. addMethodChaining( 'radians', radians );
  2088. addMethodChaining( 'degrees', degrees );
  2089. addMethodChaining( 'exp', exp );
  2090. addMethodChaining( 'exp2', exp2 );
  2091. addMethodChaining( 'log', log );
  2092. addMethodChaining( 'log2', log2 );
  2093. addMethodChaining( 'sqrt', sqrt );
  2094. addMethodChaining( 'inverseSqrt', inverseSqrt );
  2095. addMethodChaining( 'floor', floor );
  2096. addMethodChaining( 'ceil', ceil );
  2097. addMethodChaining( 'normalize', normalize );
  2098. addMethodChaining( 'fract', fract );
  2099. addMethodChaining( 'sin', sin );
  2100. addMethodChaining( 'cos', cos );
  2101. addMethodChaining( 'tan', tan );
  2102. addMethodChaining( 'asin', asin );
  2103. addMethodChaining( 'acos', acos );
  2104. addMethodChaining( 'atan', atan );
  2105. addMethodChaining( 'abs', abs );
  2106. addMethodChaining( 'sign', sign );
  2107. addMethodChaining( 'length', length );
  2108. addMethodChaining( 'lengthSq', lengthSq );
  2109. addMethodChaining( 'negate', negate );
  2110. addMethodChaining( 'oneMinus', oneMinus );
  2111. addMethodChaining( 'dFdx', dFdx );
  2112. addMethodChaining( 'dFdy', dFdy );
  2113. addMethodChaining( 'round', round );
  2114. addMethodChaining( 'reciprocal', reciprocal );
  2115. addMethodChaining( 'trunc', trunc );
  2116. addMethodChaining( 'fwidth', fwidth );
  2117. addMethodChaining( 'atan2', atan2 );
  2118. addMethodChaining( 'min', min$1 );
  2119. addMethodChaining( 'max', max$1 );
  2120. addMethodChaining( 'mod', mod );
  2121. addMethodChaining( 'step', step );
  2122. addMethodChaining( 'reflect', reflect );
  2123. addMethodChaining( 'distance', distance );
  2124. addMethodChaining( 'dot', dot );
  2125. addMethodChaining( 'cross', cross );
  2126. addMethodChaining( 'pow', pow );
  2127. addMethodChaining( 'pow2', pow2 );
  2128. addMethodChaining( 'pow3', pow3 );
  2129. addMethodChaining( 'pow4', pow4 );
  2130. addMethodChaining( 'transformDirection', transformDirection );
  2131. addMethodChaining( 'mix', mixElement );
  2132. addMethodChaining( 'clamp', clamp );
  2133. addMethodChaining( 'refract', refract );
  2134. addMethodChaining( 'smoothstep', smoothstepElement );
  2135. addMethodChaining( 'faceForward', faceForward );
  2136. addMethodChaining( 'difference', difference );
  2137. addMethodChaining( 'saturate', saturate );
  2138. addMethodChaining( 'cbrt', cbrt );
  2139. addMethodChaining( 'transpose', transpose );
  2140. addMethodChaining( 'rand', rand );
  2141. class ConditionalNode extends Node {
  2142. static get type() {
  2143. return 'ConditionalNode';
  2144. }
  2145. constructor( condNode, ifNode, elseNode = null ) {
  2146. super();
  2147. this.condNode = condNode;
  2148. this.ifNode = ifNode;
  2149. this.elseNode = elseNode;
  2150. }
  2151. getNodeType( builder ) {
  2152. const ifType = this.ifNode.getNodeType( builder );
  2153. if ( this.elseNode !== null ) {
  2154. const elseType = this.elseNode.getNodeType( builder );
  2155. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  2156. return elseType;
  2157. }
  2158. }
  2159. return ifType;
  2160. }
  2161. setup( builder ) {
  2162. const condNode = this.condNode.cache();
  2163. const ifNode = this.ifNode.cache();
  2164. const elseNode = this.elseNode ? this.elseNode.cache() : null;
  2165. //
  2166. const currentNodeBlock = builder.context.nodeBlock;
  2167. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  2168. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  2169. //
  2170. const properties = builder.getNodeProperties( this );
  2171. properties.condNode = condNode;
  2172. properties.ifNode = ifNode.context( { nodeBlock: ifNode } );
  2173. properties.elseNode = elseNode ? elseNode.context( { nodeBlock: elseNode } ) : null;
  2174. }
  2175. generate( builder, output ) {
  2176. const type = this.getNodeType( builder );
  2177. const nodeData = builder.getDataFromNode( this );
  2178. if ( nodeData.nodeProperty !== undefined ) {
  2179. return nodeData.nodeProperty;
  2180. }
  2181. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  2182. const needsOutput = output !== 'void';
  2183. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  2184. nodeData.nodeProperty = nodeProperty;
  2185. const nodeSnippet = condNode.build( builder, 'bool' );
  2186. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  2187. let ifSnippet = ifNode.build( builder, type );
  2188. if ( ifSnippet ) {
  2189. if ( needsOutput ) {
  2190. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  2191. } else {
  2192. ifSnippet = 'return ' + ifSnippet + ';';
  2193. }
  2194. }
  2195. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  2196. if ( elseNode !== null ) {
  2197. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  2198. let elseSnippet = elseNode.build( builder, type );
  2199. if ( elseSnippet ) {
  2200. if ( needsOutput ) {
  2201. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  2202. } else {
  2203. elseSnippet = 'return ' + elseSnippet + ';';
  2204. }
  2205. }
  2206. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  2207. } else {
  2208. builder.addFlowCode( '\n\n' );
  2209. }
  2210. return builder.format( nodeProperty, type, output );
  2211. }
  2212. }
  2213. const select = /*@__PURE__*/ nodeProxy( ConditionalNode );
  2214. addMethodChaining( 'select', select );
  2215. //
  2216. const cond = ( ...params ) => { // @deprecated, r168
  2217. console.warn( 'TSL.ConditionalNode: cond() has been renamed to select().' );
  2218. return select( ...params );
  2219. };
  2220. addMethodChaining( 'cond', cond );
  2221. class ContextNode extends Node {
  2222. static get type() {
  2223. return 'ContextNode';
  2224. }
  2225. constructor( node, value = {} ) {
  2226. super();
  2227. this.isContextNode = true;
  2228. this.node = node;
  2229. this.value = value;
  2230. }
  2231. getScope() {
  2232. return this.node.getScope();
  2233. }
  2234. getNodeType( builder ) {
  2235. return this.node.getNodeType( builder );
  2236. }
  2237. analyze( builder ) {
  2238. this.node.build( builder );
  2239. }
  2240. setup( builder ) {
  2241. const previousContext = builder.getContext();
  2242. builder.setContext( { ...builder.context, ...this.value } );
  2243. const node = this.node.build( builder );
  2244. builder.setContext( previousContext );
  2245. return node;
  2246. }
  2247. generate( builder, output ) {
  2248. const previousContext = builder.getContext();
  2249. builder.setContext( { ...builder.context, ...this.value } );
  2250. const snippet = this.node.build( builder, output );
  2251. builder.setContext( previousContext );
  2252. return snippet;
  2253. }
  2254. }
  2255. const context = /*@__PURE__*/ nodeProxy( ContextNode );
  2256. const label = ( node, name ) => context( node, { label: name } );
  2257. addMethodChaining( 'context', context );
  2258. addMethodChaining( 'label', label );
  2259. class VarNode extends Node {
  2260. static get type() {
  2261. return 'VarNode';
  2262. }
  2263. constructor( node, name = null ) {
  2264. super();
  2265. this.node = node;
  2266. this.name = name;
  2267. this.global = true;
  2268. this.isVarNode = true;
  2269. }
  2270. getHash( builder ) {
  2271. return this.name || super.getHash( builder );
  2272. }
  2273. getNodeType( builder ) {
  2274. return this.node.getNodeType( builder );
  2275. }
  2276. generate( builder ) {
  2277. const { node, name } = this;
  2278. const nodeVar = builder.getVarFromNode( this, name, builder.getVectorType( this.getNodeType( builder ) ) );
  2279. const propertyName = builder.getPropertyName( nodeVar );
  2280. const snippet = node.build( builder, nodeVar.type );
  2281. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  2282. return propertyName;
  2283. }
  2284. }
  2285. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  2286. addMethodChaining( 'toVar', ( ...params ) => createVar( ...params ).append() );
  2287. // Deprecated
  2288. const temp = ( node ) => { // @deprecated, r170
  2289. console.warn( 'TSL: "temp" is deprecated. Use ".toVar()" instead.' );
  2290. return createVar( node );
  2291. };
  2292. addMethodChaining( 'temp', temp );
  2293. class VaryingNode extends Node {
  2294. static get type() {
  2295. return 'VaryingNode';
  2296. }
  2297. constructor( node, name = null ) {
  2298. super();
  2299. this.node = node;
  2300. this.name = name;
  2301. this.isVaryingNode = true;
  2302. }
  2303. isGlobal() {
  2304. return true;
  2305. }
  2306. getHash( builder ) {
  2307. return this.name || super.getHash( builder );
  2308. }
  2309. getNodeType( builder ) {
  2310. // VaryingNode is auto type
  2311. return this.node.getNodeType( builder );
  2312. }
  2313. setupVarying( builder ) {
  2314. const properties = builder.getNodeProperties( this );
  2315. let varying = properties.varying;
  2316. if ( varying === undefined ) {
  2317. const name = this.name;
  2318. const type = this.getNodeType( builder );
  2319. properties.varying = varying = builder.getVaryingFromNode( this, name, type );
  2320. properties.node = this.node;
  2321. }
  2322. // this property can be used to check if the varying can be optimized for a variable
  2323. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  2324. return varying;
  2325. }
  2326. setup( builder ) {
  2327. this.setupVarying( builder );
  2328. }
  2329. analyze( builder ) {
  2330. this.setupVarying( builder );
  2331. return this.node.analyze( builder );
  2332. }
  2333. generate( builder ) {
  2334. const properties = builder.getNodeProperties( this );
  2335. const varying = this.setupVarying( builder );
  2336. if ( properties.propertyName === undefined ) {
  2337. const type = this.getNodeType( builder );
  2338. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  2339. // force node run in vertex stage
  2340. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node, type, propertyName );
  2341. properties.propertyName = propertyName;
  2342. }
  2343. return builder.getPropertyName( varying );
  2344. }
  2345. }
  2346. const varying = /*@__PURE__*/ nodeProxy( VaryingNode );
  2347. addMethodChaining( 'varying', varying );
  2348. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  2349. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  2350. const b = color.mul( 0.0773993808 );
  2351. const factor = color.lessThanEqual( 0.04045 );
  2352. const rgbResult = mix( a, b, factor );
  2353. return rgbResult;
  2354. } ).setLayout( {
  2355. name: 'sRGBTransferEOTF',
  2356. type: 'vec3',
  2357. inputs: [
  2358. { name: 'color', type: 'vec3' }
  2359. ]
  2360. } );
  2361. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  2362. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  2363. const b = color.mul( 12.92 );
  2364. const factor = color.lessThanEqual( 0.0031308 );
  2365. const rgbResult = mix( a, b, factor );
  2366. return rgbResult;
  2367. } ).setLayout( {
  2368. name: 'sRGBTransferOETF',
  2369. type: 'vec3',
  2370. inputs: [
  2371. { name: 'color', type: 'vec3' }
  2372. ]
  2373. } );
  2374. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  2375. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  2376. class ColorSpaceNode extends TempNode {
  2377. static get type() {
  2378. return 'ColorSpaceNode';
  2379. }
  2380. constructor( colorNode, source, target ) {
  2381. super( 'vec4' );
  2382. this.colorNode = colorNode;
  2383. this.source = source;
  2384. this.target = target;
  2385. }
  2386. resolveColorSpace( builder, colorSpace ) {
  2387. if ( colorSpace === WORKING_COLOR_SPACE ) {
  2388. return ColorManagement.workingColorSpace;
  2389. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  2390. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  2391. }
  2392. return colorSpace;
  2393. }
  2394. setup( builder ) {
  2395. const { colorNode } = this;
  2396. const source = this.resolveColorSpace( builder, this.source );
  2397. const target = this.resolveColorSpace( builder, this.target );
  2398. let outputNode = colorNode;
  2399. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  2400. return outputNode;
  2401. }
  2402. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  2403. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  2404. }
  2405. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  2406. outputNode = vec4(
  2407. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  2408. outputNode.a
  2409. );
  2410. }
  2411. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  2412. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  2413. }
  2414. return outputNode;
  2415. }
  2416. }
  2417. const toOutputColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, OUTPUT_COLOR_SPACE ) );
  2418. const toWorkingColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), OUTPUT_COLOR_SPACE, WORKING_COLOR_SPACE ) );
  2419. const workingToColorSpace = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, colorSpace ) );
  2420. const colorSpaceToWorking = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), colorSpace, WORKING_COLOR_SPACE ) );
  2421. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  2422. addMethodChaining( 'toOutputColorSpace', toOutputColorSpace );
  2423. addMethodChaining( 'toWorkingColorSpace', toWorkingColorSpace );
  2424. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  2425. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  2426. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  2427. static get type() {
  2428. return 'ReferenceElementNode';
  2429. }
  2430. constructor( referenceNode, indexNode ) {
  2431. super( referenceNode, indexNode );
  2432. this.referenceNode = referenceNode;
  2433. this.isReferenceElementNode = true;
  2434. }
  2435. getNodeType() {
  2436. return this.referenceNode.uniformType;
  2437. }
  2438. generate( builder ) {
  2439. const snippet = super.generate( builder );
  2440. const arrayType = this.referenceNode.getNodeType();
  2441. const elementType = this.getNodeType();
  2442. return builder.format( snippet, arrayType, elementType );
  2443. }
  2444. };
  2445. class ReferenceBaseNode extends Node {
  2446. static get type() {
  2447. return 'ReferenceBaseNode';
  2448. }
  2449. constructor( property, uniformType, object = null, count = null ) {
  2450. super();
  2451. this.property = property;
  2452. this.uniformType = uniformType;
  2453. this.object = object;
  2454. this.count = count;
  2455. this.properties = property.split( '.' );
  2456. this.reference = object;
  2457. this.node = null;
  2458. this.group = null;
  2459. this.updateType = NodeUpdateType.OBJECT;
  2460. }
  2461. setGroup( group ) {
  2462. this.group = group;
  2463. return this;
  2464. }
  2465. element( indexNode ) {
  2466. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  2467. }
  2468. setNodeType( uniformType ) {
  2469. const node = uniform( null, uniformType ).getSelf();
  2470. if ( this.group !== null ) {
  2471. node.setGroup( this.group );
  2472. }
  2473. this.node = node;
  2474. }
  2475. getNodeType( builder ) {
  2476. if ( this.node === null ) {
  2477. this.updateReference( builder );
  2478. this.updateValue();
  2479. }
  2480. return this.node.getNodeType( builder );
  2481. }
  2482. getValueFromReference( object = this.reference ) {
  2483. const { properties } = this;
  2484. let value = object[ properties[ 0 ] ];
  2485. for ( let i = 1; i < properties.length; i ++ ) {
  2486. value = value[ properties[ i ] ];
  2487. }
  2488. return value;
  2489. }
  2490. updateReference( state ) {
  2491. this.reference = this.object !== null ? this.object : state.object;
  2492. return this.reference;
  2493. }
  2494. setup() {
  2495. this.updateValue();
  2496. return this.node;
  2497. }
  2498. update( /*frame*/ ) {
  2499. this.updateValue();
  2500. }
  2501. updateValue() {
  2502. if ( this.node === null ) this.setNodeType( this.uniformType );
  2503. const value = this.getValueFromReference();
  2504. if ( Array.isArray( value ) ) {
  2505. this.node.array = value;
  2506. } else {
  2507. this.node.value = value;
  2508. }
  2509. }
  2510. }
  2511. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  2512. class RendererReferenceNode extends ReferenceBaseNode {
  2513. static get type() {
  2514. return 'RendererReferenceNode';
  2515. }
  2516. constructor( property, inputType, renderer = null ) {
  2517. super( property, inputType, renderer );
  2518. this.renderer = renderer;
  2519. this.setGroup( renderGroup );
  2520. }
  2521. updateReference( state ) {
  2522. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  2523. return this.reference;
  2524. }
  2525. }
  2526. const rendererReference = ( name, type, renderer ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  2527. class ToneMappingNode extends TempNode {
  2528. static get type() {
  2529. return 'ToneMappingNode';
  2530. }
  2531. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  2532. super( 'vec3' );
  2533. this.toneMapping = toneMapping;
  2534. this.exposureNode = exposureNode;
  2535. this.colorNode = colorNode;
  2536. }
  2537. getCacheKey() {
  2538. return hash$1( super.getCacheKey(), this.toneMapping );
  2539. }
  2540. setup( builder ) {
  2541. const colorNode = this.colorNode || builder.context.color;
  2542. const toneMapping = this.toneMapping;
  2543. if ( toneMapping === NoToneMapping ) return colorNode;
  2544. let outputNode = null;
  2545. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  2546. if ( toneMappingFn !== null ) {
  2547. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  2548. } else {
  2549. console.error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  2550. outputNode = colorNode;
  2551. }
  2552. return outputNode;
  2553. }
  2554. }
  2555. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  2556. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  2557. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  2558. class BufferAttributeNode extends InputNode {
  2559. static get type() {
  2560. return 'BufferAttributeNode';
  2561. }
  2562. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  2563. super( value, bufferType );
  2564. this.isBufferNode = true;
  2565. this.bufferType = bufferType;
  2566. this.bufferStride = bufferStride;
  2567. this.bufferOffset = bufferOffset;
  2568. this.usage = StaticDrawUsage;
  2569. this.instanced = false;
  2570. this.attribute = null;
  2571. this.global = true;
  2572. if ( value && value.isBufferAttribute === true ) {
  2573. this.attribute = value;
  2574. this.usage = value.usage;
  2575. this.instanced = value.isInstancedBufferAttribute;
  2576. }
  2577. }
  2578. getHash( builder ) {
  2579. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  2580. let bufferData = builder.globalCache.getData( this.value );
  2581. if ( bufferData === undefined ) {
  2582. bufferData = {
  2583. node: this
  2584. };
  2585. builder.globalCache.setData( this.value, bufferData );
  2586. }
  2587. return bufferData.node.uuid;
  2588. }
  2589. return this.uuid;
  2590. }
  2591. getNodeType( builder ) {
  2592. if ( this.bufferType === null ) {
  2593. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  2594. }
  2595. return this.bufferType;
  2596. }
  2597. setup( builder ) {
  2598. if ( this.attribute !== null ) return;
  2599. const type = this.getNodeType( builder );
  2600. const array = this.value;
  2601. const itemSize = builder.getTypeLength( type );
  2602. const stride = this.bufferStride || itemSize;
  2603. const offset = this.bufferOffset;
  2604. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  2605. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  2606. buffer.setUsage( this.usage );
  2607. this.attribute = bufferAttribute;
  2608. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  2609. }
  2610. generate( builder ) {
  2611. const nodeType = this.getNodeType( builder );
  2612. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  2613. const propertyName = builder.getPropertyName( nodeAttribute );
  2614. let output = null;
  2615. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  2616. this.name = propertyName;
  2617. output = propertyName;
  2618. } else {
  2619. const nodeVarying = varying( this );
  2620. output = nodeVarying.build( builder, nodeType );
  2621. }
  2622. return output;
  2623. }
  2624. getInputType( /*builder*/ ) {
  2625. return 'bufferAttribute';
  2626. }
  2627. setUsage( value ) {
  2628. this.usage = value;
  2629. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  2630. this.attribute.usage = value;
  2631. }
  2632. return this;
  2633. }
  2634. setInstanced( value ) {
  2635. this.instanced = value;
  2636. return this;
  2637. }
  2638. }
  2639. const bufferAttribute = ( array, type, stride, offset ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  2640. const dynamicBufferAttribute = ( array, type, stride, offset ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  2641. const instancedBufferAttribute = ( array, type, stride, offset ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  2642. const instancedDynamicBufferAttribute = ( array, type, stride, offset ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  2643. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  2644. class ComputeNode extends Node {
  2645. static get type() {
  2646. return 'ComputeNode';
  2647. }
  2648. constructor( computeNode, count, workgroupSize = [ 64 ] ) {
  2649. super( 'void' );
  2650. this.isComputeNode = true;
  2651. this.computeNode = computeNode;
  2652. this.count = count;
  2653. this.workgroupSize = workgroupSize;
  2654. this.dispatchCount = 0;
  2655. this.version = 1;
  2656. this.updateBeforeType = NodeUpdateType.OBJECT;
  2657. this.onInitFunction = null;
  2658. this.updateDispatchCount();
  2659. }
  2660. dispose() {
  2661. this.dispatchEvent( { type: 'dispose' } );
  2662. }
  2663. set needsUpdate( value ) {
  2664. if ( value === true ) this.version ++;
  2665. }
  2666. updateDispatchCount() {
  2667. const { count, workgroupSize } = this;
  2668. let size = workgroupSize[ 0 ];
  2669. for ( let i = 1; i < workgroupSize.length; i ++ )
  2670. size *= workgroupSize[ i ];
  2671. this.dispatchCount = Math.ceil( count / size );
  2672. }
  2673. onInit( callback ) {
  2674. this.onInitFunction = callback;
  2675. return this;
  2676. }
  2677. updateBefore( { renderer } ) {
  2678. renderer.compute( this );
  2679. }
  2680. generate( builder ) {
  2681. const { shaderStage } = builder;
  2682. if ( shaderStage === 'compute' ) {
  2683. const snippet = this.computeNode.build( builder, 'void' );
  2684. if ( snippet !== '' ) {
  2685. builder.addLineFlowCode( snippet, this );
  2686. }
  2687. }
  2688. }
  2689. }
  2690. const compute = ( node, count, workgroupSize ) => nodeObject( new ComputeNode( nodeObject( node ), count, workgroupSize ) );
  2691. addMethodChaining( 'compute', compute );
  2692. class CacheNode extends Node {
  2693. static get type() {
  2694. return 'CacheNode';
  2695. }
  2696. constructor( node, parent = true ) {
  2697. super();
  2698. this.node = node;
  2699. this.parent = parent;
  2700. this.isCacheNode = true;
  2701. }
  2702. getNodeType( builder ) {
  2703. return this.node.getNodeType( builder );
  2704. }
  2705. build( builder, ...params ) {
  2706. const previousCache = builder.getCache();
  2707. const cache = builder.getCacheFromNode( this, this.parent );
  2708. builder.setCache( cache );
  2709. const data = this.node.build( builder, ...params );
  2710. builder.setCache( previousCache );
  2711. return data;
  2712. }
  2713. }
  2714. const cache = ( node, ...params ) => nodeObject( new CacheNode( nodeObject( node ), ...params ) );
  2715. addMethodChaining( 'cache', cache );
  2716. class BypassNode extends Node {
  2717. static get type() {
  2718. return 'BypassNode';
  2719. }
  2720. constructor( returnNode, callNode ) {
  2721. super();
  2722. this.isBypassNode = true;
  2723. this.outputNode = returnNode;
  2724. this.callNode = callNode;
  2725. }
  2726. getNodeType( builder ) {
  2727. return this.outputNode.getNodeType( builder );
  2728. }
  2729. generate( builder ) {
  2730. const snippet = this.callNode.build( builder, 'void' );
  2731. if ( snippet !== '' ) {
  2732. builder.addLineFlowCode( snippet, this );
  2733. }
  2734. return this.outputNode.build( builder );
  2735. }
  2736. }
  2737. const bypass = /*@__PURE__*/ nodeProxy( BypassNode );
  2738. addMethodChaining( 'bypass', bypass );
  2739. class RemapNode extends Node {
  2740. static get type() {
  2741. return 'RemapNode';
  2742. }
  2743. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  2744. super();
  2745. this.node = node;
  2746. this.inLowNode = inLowNode;
  2747. this.inHighNode = inHighNode;
  2748. this.outLowNode = outLowNode;
  2749. this.outHighNode = outHighNode;
  2750. this.doClamp = true;
  2751. }
  2752. setup() {
  2753. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  2754. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  2755. if ( doClamp === true ) t = t.clamp();
  2756. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  2757. }
  2758. }
  2759. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } );
  2760. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode );
  2761. addMethodChaining( 'remap', remap );
  2762. addMethodChaining( 'remapClamp', remapClamp );
  2763. class ExpressionNode extends Node {
  2764. static get type() {
  2765. return 'ExpressionNode';
  2766. }
  2767. constructor( snippet = '', nodeType = 'void' ) {
  2768. super( nodeType );
  2769. this.snippet = snippet;
  2770. }
  2771. generate( builder, output ) {
  2772. const type = this.getNodeType( builder );
  2773. const snippet = this.snippet;
  2774. if ( type === 'void' ) {
  2775. builder.addLineFlowCode( snippet, this );
  2776. } else {
  2777. return builder.format( `( ${ snippet } )`, type, output );
  2778. }
  2779. }
  2780. }
  2781. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode );
  2782. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).append();
  2783. const Return = () => expression( 'return' ).append();
  2784. addMethodChaining( 'discard', Discard );
  2785. class RenderOutputNode extends TempNode {
  2786. static get type() {
  2787. return 'RenderOutputNode';
  2788. }
  2789. constructor( colorNode, toneMapping, outputColorSpace ) {
  2790. super( 'vec4' );
  2791. this.colorNode = colorNode;
  2792. this.toneMapping = toneMapping;
  2793. this.outputColorSpace = outputColorSpace;
  2794. this.isRenderOutput = true;
  2795. }
  2796. setup( { context } ) {
  2797. let outputNode = this.colorNode || context.color;
  2798. // tone mapping
  2799. const toneMapping = ( this.toneMapping !== null ? this.toneMapping : context.toneMapping ) || NoToneMapping;
  2800. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  2801. if ( toneMapping !== NoToneMapping ) {
  2802. outputNode = outputNode.toneMapping( toneMapping );
  2803. }
  2804. // working to output color space
  2805. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  2806. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  2807. }
  2808. return outputNode;
  2809. }
  2810. }
  2811. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  2812. addMethodChaining( 'renderOutput', renderOutput );
  2813. // Non-PURE exports list, side-effects are required here.
  2814. // TSL Base Syntax
  2815. function addNodeElement( name/*, nodeElement*/ ) {
  2816. console.warn( 'THREE.TSLBase: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  2817. }
  2818. class AttributeNode extends Node {
  2819. static get type() {
  2820. return 'AttributeNode';
  2821. }
  2822. constructor( attributeName, nodeType = null ) {
  2823. super( nodeType );
  2824. this.global = true;
  2825. this._attributeName = attributeName;
  2826. }
  2827. getHash( builder ) {
  2828. return this.getAttributeName( builder );
  2829. }
  2830. getNodeType( builder ) {
  2831. let nodeType = this.nodeType;
  2832. if ( nodeType === null ) {
  2833. const attributeName = this.getAttributeName( builder );
  2834. if ( builder.hasGeometryAttribute( attributeName ) ) {
  2835. const attribute = builder.geometry.getAttribute( attributeName );
  2836. nodeType = builder.getTypeFromAttribute( attribute );
  2837. } else {
  2838. nodeType = 'float';
  2839. }
  2840. }
  2841. return nodeType;
  2842. }
  2843. setAttributeName( attributeName ) {
  2844. this._attributeName = attributeName;
  2845. return this;
  2846. }
  2847. getAttributeName( /*builder*/ ) {
  2848. return this._attributeName;
  2849. }
  2850. generate( builder ) {
  2851. const attributeName = this.getAttributeName( builder );
  2852. const nodeType = this.getNodeType( builder );
  2853. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  2854. if ( geometryAttribute === true ) {
  2855. const attribute = builder.geometry.getAttribute( attributeName );
  2856. const attributeType = builder.getTypeFromAttribute( attribute );
  2857. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  2858. if ( builder.shaderStage === 'vertex' ) {
  2859. return builder.format( nodeAttribute.name, attributeType, nodeType );
  2860. } else {
  2861. const nodeVarying = varying( this );
  2862. return nodeVarying.build( builder, nodeType );
  2863. }
  2864. } else {
  2865. console.warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  2866. return builder.generateConst( nodeType );
  2867. }
  2868. }
  2869. serialize( data ) {
  2870. super.serialize( data );
  2871. data.global = this.global;
  2872. data._attributeName = this._attributeName;
  2873. }
  2874. deserialize( data ) {
  2875. super.deserialize( data );
  2876. this.global = data.global;
  2877. this._attributeName = data._attributeName;
  2878. }
  2879. }
  2880. const attribute = ( name, nodeType ) => nodeObject( new AttributeNode( name, nodeType ) );
  2881. const uv = ( index ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  2882. class TextureSizeNode extends Node {
  2883. static get type() {
  2884. return 'TextureSizeNode';
  2885. }
  2886. constructor( textureNode, levelNode = null ) {
  2887. super( 'uvec2' );
  2888. this.isTextureSizeNode = true;
  2889. this.textureNode = textureNode;
  2890. this.levelNode = levelNode;
  2891. }
  2892. generate( builder, output ) {
  2893. const textureProperty = this.textureNode.build( builder, 'property' );
  2894. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  2895. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  2896. }
  2897. }
  2898. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode );
  2899. class MaxMipLevelNode extends UniformNode {
  2900. static get type() {
  2901. return 'MaxMipLevelNode';
  2902. }
  2903. constructor( textureNode ) {
  2904. super( 0 );
  2905. this._textureNode = textureNode;
  2906. this.updateType = NodeUpdateType.FRAME;
  2907. }
  2908. get textureNode() {
  2909. return this._textureNode;
  2910. }
  2911. get texture() {
  2912. return this._textureNode.value;
  2913. }
  2914. update() {
  2915. const texture = this.texture;
  2916. const images = texture.images;
  2917. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  2918. if ( image && image.width !== undefined ) {
  2919. const { width, height } = image;
  2920. this.value = Math.log2( Math.max( width, height ) );
  2921. }
  2922. }
  2923. }
  2924. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode );
  2925. class TextureNode extends UniformNode {
  2926. static get type() {
  2927. return 'TextureNode';
  2928. }
  2929. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  2930. super( value );
  2931. this.isTextureNode = true;
  2932. this.uvNode = uvNode;
  2933. this.levelNode = levelNode;
  2934. this.biasNode = biasNode;
  2935. this.compareNode = null;
  2936. this.depthNode = null;
  2937. this.gradNode = null;
  2938. this.sampler = true;
  2939. this.updateMatrix = false;
  2940. this.updateType = NodeUpdateType.NONE;
  2941. this.referenceNode = null;
  2942. this._value = value;
  2943. this._matrixUniform = null;
  2944. this.setUpdateMatrix( uvNode === null );
  2945. }
  2946. set value( value ) {
  2947. if ( this.referenceNode ) {
  2948. this.referenceNode.value = value;
  2949. } else {
  2950. this._value = value;
  2951. }
  2952. }
  2953. get value() {
  2954. return this.referenceNode ? this.referenceNode.value : this._value;
  2955. }
  2956. getUniformHash( /*builder*/ ) {
  2957. return this.value.uuid;
  2958. }
  2959. getNodeType( /*builder*/ ) {
  2960. if ( this.value.isDepthTexture === true ) return 'float';
  2961. if ( this.value.type === UnsignedIntType ) {
  2962. return 'uvec4';
  2963. } else if ( this.value.type === IntType ) {
  2964. return 'ivec4';
  2965. }
  2966. return 'vec4';
  2967. }
  2968. getInputType( /*builder*/ ) {
  2969. return 'texture';
  2970. }
  2971. getDefaultUV() {
  2972. return uv( this.value.channel );
  2973. }
  2974. updateReference( /*state*/ ) {
  2975. return this.value;
  2976. }
  2977. getTransformedUV( uvNode ) {
  2978. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  2979. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  2980. }
  2981. setUpdateMatrix( value ) {
  2982. this.updateMatrix = value;
  2983. this.updateType = value ? NodeUpdateType.FRAME : NodeUpdateType.NONE;
  2984. return this;
  2985. }
  2986. setupUV( builder, uvNode ) {
  2987. const texture = this.value;
  2988. if ( builder.isFlipY() && ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true ) ) {
  2989. if ( this.sampler ) {
  2990. uvNode = uvNode.flipY();
  2991. } else {
  2992. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  2993. }
  2994. }
  2995. return uvNode;
  2996. }
  2997. setup( builder ) {
  2998. const properties = builder.getNodeProperties( this );
  2999. properties.referenceNode = this.referenceNode;
  3000. //
  3001. let uvNode = this.uvNode;
  3002. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  3003. uvNode = builder.context.getUV( this );
  3004. }
  3005. if ( ! uvNode ) uvNode = this.getDefaultUV();
  3006. if ( this.updateMatrix === true ) {
  3007. uvNode = this.getTransformedUV( uvNode );
  3008. }
  3009. uvNode = this.setupUV( builder, uvNode );
  3010. //
  3011. let levelNode = this.levelNode;
  3012. if ( levelNode === null && builder.context.getTextureLevel ) {
  3013. levelNode = builder.context.getTextureLevel( this );
  3014. }
  3015. //
  3016. properties.uvNode = uvNode;
  3017. properties.levelNode = levelNode;
  3018. properties.biasNode = this.biasNode;
  3019. properties.compareNode = this.compareNode;
  3020. properties.gradNode = this.gradNode;
  3021. properties.depthNode = this.depthNode;
  3022. }
  3023. generateUV( builder, uvNode ) {
  3024. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  3025. }
  3026. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet ) {
  3027. const texture = this.value;
  3028. let snippet;
  3029. if ( levelSnippet ) {
  3030. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  3031. } else if ( biasSnippet ) {
  3032. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet );
  3033. } else if ( gradSnippet ) {
  3034. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet );
  3035. } else if ( compareSnippet ) {
  3036. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet );
  3037. } else if ( this.sampler === false ) {
  3038. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, depthSnippet );
  3039. } else {
  3040. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet );
  3041. }
  3042. return snippet;
  3043. }
  3044. generate( builder, output ) {
  3045. const properties = builder.getNodeProperties( this );
  3046. const texture = this.value;
  3047. if ( ! texture || texture.isTexture !== true ) {
  3048. throw new Error( 'TextureNode: Need a three.js texture.' );
  3049. }
  3050. const textureProperty = super.generate( builder, 'property' );
  3051. if ( output === 'sampler' ) {
  3052. return textureProperty + '_sampler';
  3053. } else if ( builder.isReference( output ) ) {
  3054. return textureProperty;
  3055. } else {
  3056. const nodeData = builder.getDataFromNode( this );
  3057. let propertyName = nodeData.propertyName;
  3058. if ( propertyName === undefined ) {
  3059. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode } = properties;
  3060. const uvSnippet = this.generateUV( builder, uvNode );
  3061. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  3062. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  3063. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  3064. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  3065. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  3066. const nodeVar = builder.getVarFromNode( this );
  3067. propertyName = builder.getPropertyName( nodeVar );
  3068. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet );
  3069. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  3070. nodeData.snippet = snippet;
  3071. nodeData.propertyName = propertyName;
  3072. }
  3073. let snippet = propertyName;
  3074. const nodeType = this.getNodeType( builder );
  3075. if ( builder.needsToWorkingColorSpace( texture ) ) {
  3076. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  3077. }
  3078. return builder.format( snippet, nodeType, output );
  3079. }
  3080. }
  3081. setSampler( value ) {
  3082. this.sampler = value;
  3083. return this;
  3084. }
  3085. getSampler() {
  3086. return this.sampler;
  3087. }
  3088. // @TODO: Move to TSL
  3089. uv( uvNode ) {
  3090. const textureNode = this.clone();
  3091. textureNode.uvNode = nodeObject( uvNode );
  3092. textureNode.referenceNode = this.getSelf();
  3093. return nodeObject( textureNode );
  3094. }
  3095. blur( amountNode ) {
  3096. const textureNode = this.clone();
  3097. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  3098. textureNode.referenceNode = this.getSelf();
  3099. return nodeObject( textureNode );
  3100. }
  3101. level( levelNode ) {
  3102. const textureNode = this.clone();
  3103. textureNode.levelNode = nodeObject( levelNode );
  3104. textureNode.referenceNode = this.getSelf();
  3105. return nodeObject( textureNode );
  3106. }
  3107. size( levelNode ) {
  3108. return textureSize( this, levelNode );
  3109. }
  3110. bias( biasNode ) {
  3111. const textureNode = this.clone();
  3112. textureNode.biasNode = nodeObject( biasNode );
  3113. textureNode.referenceNode = this.getSelf();
  3114. return nodeObject( textureNode );
  3115. }
  3116. compare( compareNode ) {
  3117. const textureNode = this.clone();
  3118. textureNode.compareNode = nodeObject( compareNode );
  3119. textureNode.referenceNode = this.getSelf();
  3120. return nodeObject( textureNode );
  3121. }
  3122. grad( gradNodeX, gradNodeY ) {
  3123. const textureNode = this.clone();
  3124. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  3125. textureNode.referenceNode = this.getSelf();
  3126. return nodeObject( textureNode );
  3127. }
  3128. depth( depthNode ) {
  3129. const textureNode = this.clone();
  3130. textureNode.depthNode = nodeObject( depthNode );
  3131. textureNode.referenceNode = this.getSelf();
  3132. return nodeObject( textureNode );
  3133. }
  3134. // --
  3135. serialize( data ) {
  3136. super.serialize( data );
  3137. data.value = this.value.toJSON( data.meta ).uuid;
  3138. data.sampler = this.sampler;
  3139. data.updateMatrix = this.updateMatrix;
  3140. data.updateType = this.updateType;
  3141. }
  3142. deserialize( data ) {
  3143. super.deserialize( data );
  3144. this.value = data.meta.textures[ data.value ];
  3145. this.sampler = data.sampler;
  3146. this.updateMatrix = data.updateMatrix;
  3147. this.updateType = data.updateType;
  3148. }
  3149. update() {
  3150. const texture = this.value;
  3151. const matrixUniform = this._matrixUniform;
  3152. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  3153. if ( texture.matrixAutoUpdate === true ) {
  3154. texture.updateMatrix();
  3155. }
  3156. }
  3157. clone() {
  3158. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  3159. newNode.sampler = this.sampler;
  3160. return newNode;
  3161. }
  3162. }
  3163. const texture = /*@__PURE__*/ nodeProxy( TextureNode );
  3164. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  3165. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  3166. const sampler = ( aTexture ) => ( aTexture.isNode === true ? aTexture : texture( aTexture ) ).convert( 'sampler' );
  3167. const cameraNear = /*@__PURE__*/ uniform( 'float' ).label( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  3168. const cameraFar = /*@__PURE__*/ uniform( 'float' ).label( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  3169. const cameraProjectionMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  3170. const cameraProjectionMatrixInverse = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  3171. const cameraViewMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  3172. const cameraWorldMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  3173. const cameraNormalMatrix = /*@__PURE__*/ uniform( 'mat3' ).label( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  3174. const cameraPosition = /*@__PURE__*/ uniform( new Vector3() ).label( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  3175. class Object3DNode extends Node {
  3176. static get type() {
  3177. return 'Object3DNode';
  3178. }
  3179. constructor( scope, object3d = null ) {
  3180. super();
  3181. this.scope = scope;
  3182. this.object3d = object3d;
  3183. this.updateType = NodeUpdateType.OBJECT;
  3184. this._uniformNode = new UniformNode( null );
  3185. }
  3186. getNodeType() {
  3187. const scope = this.scope;
  3188. if ( scope === Object3DNode.WORLD_MATRIX ) {
  3189. return 'mat4';
  3190. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  3191. return 'vec3';
  3192. }
  3193. }
  3194. update( frame ) {
  3195. const object = this.object3d;
  3196. const uniformNode = this._uniformNode;
  3197. const scope = this.scope;
  3198. if ( scope === Object3DNode.WORLD_MATRIX ) {
  3199. uniformNode.value = object.matrixWorld;
  3200. } else if ( scope === Object3DNode.POSITION ) {
  3201. uniformNode.value = uniformNode.value || new Vector3();
  3202. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  3203. } else if ( scope === Object3DNode.SCALE ) {
  3204. uniformNode.value = uniformNode.value || new Vector3();
  3205. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  3206. } else if ( scope === Object3DNode.DIRECTION ) {
  3207. uniformNode.value = uniformNode.value || new Vector3();
  3208. object.getWorldDirection( uniformNode.value );
  3209. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  3210. const camera = frame.camera;
  3211. uniformNode.value = uniformNode.value || new Vector3();
  3212. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  3213. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  3214. }
  3215. }
  3216. generate( builder ) {
  3217. const scope = this.scope;
  3218. if ( scope === Object3DNode.WORLD_MATRIX ) {
  3219. this._uniformNode.nodeType = 'mat4';
  3220. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  3221. this._uniformNode.nodeType = 'vec3';
  3222. }
  3223. return this._uniformNode.build( builder );
  3224. }
  3225. serialize( data ) {
  3226. super.serialize( data );
  3227. data.scope = this.scope;
  3228. }
  3229. deserialize( data ) {
  3230. super.deserialize( data );
  3231. this.scope = data.scope;
  3232. }
  3233. }
  3234. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  3235. Object3DNode.POSITION = 'position';
  3236. Object3DNode.SCALE = 'scale';
  3237. Object3DNode.VIEW_POSITION = 'viewPosition';
  3238. Object3DNode.DIRECTION = 'direction';
  3239. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION );
  3240. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX );
  3241. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION );
  3242. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE );
  3243. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION );
  3244. class ModelNode extends Object3DNode {
  3245. static get type() {
  3246. return 'ModelNode';
  3247. }
  3248. constructor( scope ) {
  3249. super( scope );
  3250. }
  3251. update( frame ) {
  3252. this.object3d = frame.object;
  3253. super.update( frame );
  3254. }
  3255. }
  3256. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  3257. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  3258. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  3259. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  3260. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  3261. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  3262. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  3263. const modelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix ).toVar( 'modelViewMatrix' );
  3264. const highPrecisionModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  3265. builder.context.isHighPrecisionModelViewMatrix = true;
  3266. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  3267. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  3268. } );
  3269. } ).once() )().toVar( 'highPrecisionModelViewMatrix' );
  3270. const highPrecisionModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  3271. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  3272. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  3273. if ( isHighPrecisionModelViewMatrix !== true ) {
  3274. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  3275. }
  3276. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  3277. } );
  3278. } ).once() )().toVar( 'highPrecisionModelNormalMatrix' );
  3279. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  3280. const positionLocal = /*@__PURE__*/ positionGeometry.varying( 'positionLocal' );
  3281. const positionPrevious = /*@__PURE__*/ positionGeometry.varying( 'positionPrevious' );
  3282. const positionWorld = /*@__PURE__*/ modelWorldMatrix.mul( positionLocal ).xyz.varying( 'v_positionWorld' );
  3283. const positionWorldDirection = /*@__PURE__*/ positionLocal.transformDirection( modelWorldMatrix ).varying( 'v_positionWorldDirection' ).normalize().toVar( 'positionWorldDirection' );
  3284. const positionView = /*@__PURE__*/ modelViewMatrix.mul( positionLocal ).xyz.varying( 'v_positionView' );
  3285. const positionViewDirection = /*@__PURE__*/ positionView.negate().varying( 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  3286. class FrontFacingNode extends Node {
  3287. static get type() {
  3288. return 'FrontFacingNode';
  3289. }
  3290. constructor() {
  3291. super( 'bool' );
  3292. this.isFrontFacingNode = true;
  3293. }
  3294. generate( builder ) {
  3295. const { renderer, material } = builder;
  3296. if ( renderer.coordinateSystem === WebGLCoordinateSystem ) {
  3297. if ( material.side === BackSide ) {
  3298. return 'false';
  3299. }
  3300. }
  3301. return builder.getFrontFacing();
  3302. }
  3303. }
  3304. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  3305. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  3306. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  3307. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  3308. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  3309. console.warn( 'TSL.NormalNode: Vertex attribute "normal" not found on geometry.' );
  3310. return vec3( 0, 1, 0 );
  3311. }
  3312. return normalGeometry;
  3313. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  3314. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  3315. const normalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  3316. let node;
  3317. if ( builder.material.flatShading === true ) {
  3318. node = normalFlat;
  3319. } else {
  3320. node = varying( transformNormalToView( normalLocal ), 'v_normalView' ).normalize();
  3321. }
  3322. return node;
  3323. }, 'vec3' ).once() )().toVar( 'normalView' );
  3324. const normalWorld = /*@__PURE__*/ varying( normalView.transformDirection( cameraViewMatrix ), 'v_normalWorld' ).normalize().toVar( 'normalWorld' );
  3325. const transformedNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  3326. return builder.context.setupNormal();
  3327. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedNormalView' );
  3328. const transformedNormalWorld = /*@__PURE__*/ transformedNormalView.transformDirection( cameraViewMatrix ).toVar( 'transformedNormalWorld' );
  3329. const transformedClearcoatNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  3330. return builder.context.setupClearcoatNormal();
  3331. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedClearcoatNormalView' );
  3332. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  3333. const m = mat3( matrix );
  3334. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  3335. return m.mul( transformedNormal ).xyz;
  3336. } );
  3337. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  3338. const modelNormalViewMatrix = builder.renderer.nodes.modelNormalViewMatrix;
  3339. if ( modelNormalViewMatrix !== null ) {
  3340. return modelNormalViewMatrix.transformDirection( normal );
  3341. }
  3342. //
  3343. const transformedNormal = modelNormalMatrix.mul( normal );
  3344. return cameraViewMatrix.transformDirection( transformedNormal );
  3345. } );
  3346. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onRenderUpdate( ( { material } ) => material.refractionRatio );
  3347. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( transformedNormalView );
  3348. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( transformedNormalView, materialRefractionRatio );
  3349. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  3350. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  3351. class CubeTextureNode extends TextureNode {
  3352. static get type() {
  3353. return 'CubeTextureNode';
  3354. }
  3355. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  3356. super( value, uvNode, levelNode, biasNode );
  3357. this.isCubeTextureNode = true;
  3358. }
  3359. getInputType( /*builder*/ ) {
  3360. return 'cubeTexture';
  3361. }
  3362. getDefaultUV() {
  3363. const texture = this.value;
  3364. if ( texture.mapping === CubeReflectionMapping ) {
  3365. return reflectVector;
  3366. } else if ( texture.mapping === CubeRefractionMapping ) {
  3367. return refractVector;
  3368. } else {
  3369. console.error( 'THREE.CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  3370. return vec3( 0, 0, 0 );
  3371. }
  3372. }
  3373. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  3374. setupUV( builder, uvNode ) {
  3375. const texture = this.value;
  3376. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  3377. return vec3( uvNode.x.negate(), uvNode.yz );
  3378. } else {
  3379. return uvNode;
  3380. }
  3381. }
  3382. generateUV( builder, cubeUV ) {
  3383. return cubeUV.build( builder, 'vec3' );
  3384. }
  3385. }
  3386. const cubeTexture = /*@__PURE__*/ nodeProxy( CubeTextureNode );
  3387. class BufferNode extends UniformNode {
  3388. static get type() {
  3389. return 'BufferNode';
  3390. }
  3391. constructor( value, bufferType, bufferCount = 0 ) {
  3392. super( value, bufferType );
  3393. this.isBufferNode = true;
  3394. this.bufferType = bufferType;
  3395. this.bufferCount = bufferCount;
  3396. }
  3397. getElementType( builder ) {
  3398. return this.getNodeType( builder );
  3399. }
  3400. getInputType( /*builder*/ ) {
  3401. return 'buffer';
  3402. }
  3403. }
  3404. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  3405. class UniformArrayElementNode extends ArrayElementNode {
  3406. static get type() {
  3407. return 'UniformArrayElementNode';
  3408. }
  3409. constructor( arrayBuffer, indexNode ) {
  3410. super( arrayBuffer, indexNode );
  3411. this.isArrayBufferElementNode = true;
  3412. }
  3413. generate( builder ) {
  3414. const snippet = super.generate( builder );
  3415. const type = this.getNodeType();
  3416. return builder.format( snippet, 'vec4', type );
  3417. }
  3418. }
  3419. class UniformArrayNode extends BufferNode {
  3420. static get type() {
  3421. return 'UniformArrayNode';
  3422. }
  3423. constructor( value, elementType = null ) {
  3424. super( null, 'vec4' );
  3425. this.array = value;
  3426. this.elementType = elementType;
  3427. this._elementType = null;
  3428. this._elementLength = 0;
  3429. this.updateType = NodeUpdateType.RENDER;
  3430. this.isArrayBufferNode = true;
  3431. }
  3432. getElementType() {
  3433. return this.elementType || this._elementType;
  3434. }
  3435. getElementLength() {
  3436. return this._elementLength;
  3437. }
  3438. update( /*frame*/ ) {
  3439. const { array, value } = this;
  3440. const elementLength = this.getElementLength();
  3441. const elementType = this.getElementType();
  3442. if ( elementLength === 1 ) {
  3443. for ( let i = 0; i < array.length; i ++ ) {
  3444. const index = i * 4;
  3445. value[ index ] = array[ i ];
  3446. }
  3447. } else if ( elementType === 'color' ) {
  3448. for ( let i = 0; i < array.length; i ++ ) {
  3449. const index = i * 4;
  3450. const vector = array[ i ];
  3451. value[ index ] = vector.r;
  3452. value[ index + 1 ] = vector.g;
  3453. value[ index + 2 ] = vector.b || 0;
  3454. //value[ index + 3 ] = vector.a || 0;
  3455. }
  3456. } else {
  3457. for ( let i = 0; i < array.length; i ++ ) {
  3458. const index = i * 4;
  3459. const vector = array[ i ];
  3460. value[ index ] = vector.x;
  3461. value[ index + 1 ] = vector.y;
  3462. value[ index + 2 ] = vector.z || 0;
  3463. value[ index + 3 ] = vector.w || 0;
  3464. }
  3465. }
  3466. }
  3467. setup( builder ) {
  3468. const length = this.array.length;
  3469. this._elementType = this.elementType === null ? getValueType( this.array[ 0 ] ) : this.elementType;
  3470. this._elementLength = builder.getTypeLength( this._elementType );
  3471. let arrayType = Float32Array;
  3472. if ( this._elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  3473. else if ( this._elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  3474. this.value = new arrayType( length * 4 );
  3475. this.bufferCount = length;
  3476. this.bufferType = builder.changeComponentType( 'vec4', builder.getComponentType( this._elementType ) );
  3477. return super.setup( builder );
  3478. }
  3479. element( indexNode ) {
  3480. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  3481. }
  3482. }
  3483. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  3484. //
  3485. const uniforms = ( values, nodeType ) => { // @deprecated, r168
  3486. console.warn( 'TSL.UniformArrayNode: uniforms() has been renamed to uniformArray().' );
  3487. return nodeObject( new UniformArrayNode( values, nodeType ) );
  3488. };
  3489. class ReferenceElementNode extends ArrayElementNode {
  3490. static get type() {
  3491. return 'ReferenceElementNode';
  3492. }
  3493. constructor( referenceNode, indexNode ) {
  3494. super( referenceNode, indexNode );
  3495. this.referenceNode = referenceNode;
  3496. this.isReferenceElementNode = true;
  3497. }
  3498. getNodeType() {
  3499. return this.referenceNode.uniformType;
  3500. }
  3501. generate( builder ) {
  3502. const snippet = super.generate( builder );
  3503. const arrayType = this.referenceNode.getNodeType();
  3504. const elementType = this.getNodeType();
  3505. return builder.format( snippet, arrayType, elementType );
  3506. }
  3507. }
  3508. // TODO: Extends this from ReferenceBaseNode
  3509. class ReferenceNode extends Node {
  3510. static get type() {
  3511. return 'ReferenceNode';
  3512. }
  3513. constructor( property, uniformType, object = null, count = null ) {
  3514. super();
  3515. this.property = property;
  3516. this.uniformType = uniformType;
  3517. this.object = object;
  3518. this.count = count;
  3519. this.properties = property.split( '.' );
  3520. this.reference = object;
  3521. this.node = null;
  3522. this.group = null;
  3523. this.name = null;
  3524. this.updateType = NodeUpdateType.OBJECT;
  3525. }
  3526. element( indexNode ) {
  3527. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  3528. }
  3529. setGroup( group ) {
  3530. this.group = group;
  3531. return this;
  3532. }
  3533. label( name ) {
  3534. this.name = name;
  3535. return this;
  3536. }
  3537. setNodeType( uniformType ) {
  3538. let node = null;
  3539. if ( this.count !== null ) {
  3540. node = buffer( null, uniformType, this.count );
  3541. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  3542. node = uniformArray( null, uniformType );
  3543. } else if ( uniformType === 'texture' ) {
  3544. node = texture( null );
  3545. } else if ( uniformType === 'cubeTexture' ) {
  3546. node = cubeTexture( null );
  3547. } else {
  3548. node = uniform( null, uniformType );
  3549. }
  3550. if ( this.group !== null ) {
  3551. node.setGroup( this.group );
  3552. }
  3553. if ( this.name !== null ) node.label( this.name );
  3554. this.node = node.getSelf();
  3555. }
  3556. getNodeType( builder ) {
  3557. if ( this.node === null ) {
  3558. this.updateReference( builder );
  3559. this.updateValue();
  3560. }
  3561. return this.node.getNodeType( builder );
  3562. }
  3563. getValueFromReference( object = this.reference ) {
  3564. const { properties } = this;
  3565. let value = object[ properties[ 0 ] ];
  3566. for ( let i = 1; i < properties.length; i ++ ) {
  3567. value = value[ properties[ i ] ];
  3568. }
  3569. return value;
  3570. }
  3571. updateReference( state ) {
  3572. this.reference = this.object !== null ? this.object : state.object;
  3573. return this.reference;
  3574. }
  3575. setup() {
  3576. this.updateValue();
  3577. return this.node;
  3578. }
  3579. update( /*frame*/ ) {
  3580. this.updateValue();
  3581. }
  3582. updateValue() {
  3583. if ( this.node === null ) this.setNodeType( this.uniformType );
  3584. const value = this.getValueFromReference();
  3585. if ( Array.isArray( value ) ) {
  3586. this.node.array = value;
  3587. } else {
  3588. this.node.value = value;
  3589. }
  3590. }
  3591. }
  3592. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  3593. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  3594. class MaterialReferenceNode extends ReferenceNode {
  3595. static get type() {
  3596. return 'MaterialReferenceNode';
  3597. }
  3598. constructor( property, inputType, material = null ) {
  3599. super( property, inputType, material );
  3600. this.material = material;
  3601. //this.updateType = NodeUpdateType.RENDER;
  3602. this.isMaterialReferenceNode = true;
  3603. }
  3604. /*setNodeType( node ) {
  3605. super.setNodeType( node );
  3606. this.node.groupNode = renderGroup;
  3607. }*/
  3608. updateReference( state ) {
  3609. this.reference = this.material !== null ? this.material : state.material;
  3610. return this.reference;
  3611. }
  3612. }
  3613. const materialReference = ( name, type, material ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  3614. const tangentGeometry = /*@__PURE__*/ Fn( ( builder ) => {
  3615. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  3616. builder.geometry.computeTangents();
  3617. }
  3618. return attribute( 'tangent', 'vec4' );
  3619. } )();
  3620. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  3621. const tangentView = /*@__PURE__*/ modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.varying( 'v_tangentView' ).normalize().toVar( 'tangentView' );
  3622. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).varying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  3623. const transformedTangentView = /*@__PURE__*/ tangentView.toVar( 'transformedTangentView' );
  3624. const transformedTangentWorld = /*@__PURE__*/ transformedTangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedTangentWorld' );
  3625. const getBitangent = ( crossNormalTangent ) => crossNormalTangent.mul( tangentGeometry.w ).xyz;
  3626. const bitangentGeometry = /*@__PURE__*/ varying( getBitangent( normalGeometry.cross( tangentGeometry ) ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  3627. const bitangentLocal = /*@__PURE__*/ varying( getBitangent( normalLocal.cross( tangentLocal ) ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  3628. const bitangentView = /*@__PURE__*/ varying( getBitangent( normalView.cross( tangentView ) ), 'v_bitangentView' ).normalize().toVar( 'bitangentView' );
  3629. const bitangentWorld = /*@__PURE__*/ varying( getBitangent( normalWorld.cross( tangentWorld ) ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  3630. const transformedBitangentView = /*@__PURE__*/ getBitangent( transformedNormalView.cross( transformedTangentView ) ).normalize().toVar( 'transformedBitangentView' );
  3631. const transformedBitangentWorld = /*@__PURE__*/ transformedBitangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedBitangentWorld' );
  3632. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView );
  3633. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  3634. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  3635. const transformedBentNormalView = /*@__PURE__*/ ( () => {
  3636. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  3637. let bentNormal = anisotropyB.cross( positionViewDirection );
  3638. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  3639. bentNormal = mix( bentNormal, transformedNormalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  3640. return bentNormal;
  3641. } )();
  3642. // Normal Mapping Without Precomputed Tangents
  3643. // http://www.thetenthplanet.de/archives/1180
  3644. const perturbNormal2Arb = /*@__PURE__*/ Fn( ( inputs ) => {
  3645. const { eye_pos, surf_norm, mapN, uv } = inputs;
  3646. const q0 = eye_pos.dFdx();
  3647. const q1 = eye_pos.dFdy();
  3648. const st0 = uv.dFdx();
  3649. const st1 = uv.dFdy();
  3650. const N = surf_norm; // normalized
  3651. const q1perp = q1.cross( N );
  3652. const q0perp = N.cross( q0 );
  3653. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  3654. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  3655. const det = T.dot( T ).max( B.dot( B ) );
  3656. const scale = faceDirection.mul( det.inverseSqrt() );
  3657. return add( T.mul( mapN.x, scale ), B.mul( mapN.y, scale ), N.mul( mapN.z ) ).normalize();
  3658. } );
  3659. class NormalMapNode extends TempNode {
  3660. static get type() {
  3661. return 'NormalMapNode';
  3662. }
  3663. constructor( node, scaleNode = null ) {
  3664. super( 'vec3' );
  3665. this.node = node;
  3666. this.scaleNode = scaleNode;
  3667. this.normalMapType = TangentSpaceNormalMap;
  3668. }
  3669. setup( builder ) {
  3670. const { normalMapType, scaleNode } = this;
  3671. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  3672. if ( scaleNode !== null ) {
  3673. normalMap = vec3( normalMap.xy.mul( scaleNode ), normalMap.z );
  3674. }
  3675. let outputNode = null;
  3676. if ( normalMapType === ObjectSpaceNormalMap ) {
  3677. outputNode = transformNormalToView( normalMap );
  3678. } else if ( normalMapType === TangentSpaceNormalMap ) {
  3679. const tangent = builder.hasGeometryAttribute( 'tangent' );
  3680. if ( tangent === true ) {
  3681. outputNode = TBNViewMatrix.mul( normalMap ).normalize();
  3682. } else {
  3683. outputNode = perturbNormal2Arb( {
  3684. eye_pos: positionView,
  3685. surf_norm: normalView,
  3686. mapN: normalMap,
  3687. uv: uv()
  3688. } );
  3689. }
  3690. }
  3691. return outputNode;
  3692. }
  3693. }
  3694. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode );
  3695. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  3696. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  3697. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  3698. // It's used to preserve the same TextureNode instance
  3699. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv() ), forceUVContext: true } );
  3700. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  3701. return vec2(
  3702. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  3703. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  3704. ).mul( bumpScale );
  3705. } );
  3706. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  3707. const perturbNormalArb = Fn( ( inputs ) => {
  3708. const { surf_pos, surf_norm, dHdxy } = inputs;
  3709. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  3710. const vSigmaX = surf_pos.dFdx().normalize();
  3711. const vSigmaY = surf_pos.dFdy().normalize();
  3712. const vN = surf_norm; // normalized
  3713. const R1 = vSigmaY.cross( vN );
  3714. const R2 = vN.cross( vSigmaX );
  3715. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  3716. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  3717. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  3718. } );
  3719. class BumpMapNode extends TempNode {
  3720. static get type() {
  3721. return 'BumpMapNode';
  3722. }
  3723. constructor( textureNode, scaleNode = null ) {
  3724. super( 'vec3' );
  3725. this.textureNode = textureNode;
  3726. this.scaleNode = scaleNode;
  3727. }
  3728. setup() {
  3729. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  3730. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  3731. return perturbNormalArb( {
  3732. surf_pos: positionView,
  3733. surf_norm: normalView,
  3734. dHdxy
  3735. } );
  3736. }
  3737. }
  3738. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode );
  3739. const _propertyCache = new Map();
  3740. class MaterialNode extends Node {
  3741. static get type() {
  3742. return 'MaterialNode';
  3743. }
  3744. constructor( scope ) {
  3745. super();
  3746. this.scope = scope;
  3747. }
  3748. getCache( property, type ) {
  3749. let node = _propertyCache.get( property );
  3750. if ( node === undefined ) {
  3751. node = materialReference( property, type );
  3752. _propertyCache.set( property, node );
  3753. }
  3754. return node;
  3755. }
  3756. getFloat( property ) {
  3757. return this.getCache( property, 'float' );
  3758. }
  3759. getColor( property ) {
  3760. return this.getCache( property, 'color' );
  3761. }
  3762. getTexture( property ) {
  3763. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  3764. }
  3765. setup( builder ) {
  3766. const material = builder.context.material;
  3767. const scope = this.scope;
  3768. let node = null;
  3769. if ( scope === MaterialNode.COLOR ) {
  3770. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  3771. if ( material.map && material.map.isTexture === true ) {
  3772. node = colorNode.mul( this.getTexture( 'map' ) );
  3773. } else {
  3774. node = colorNode;
  3775. }
  3776. } else if ( scope === MaterialNode.OPACITY ) {
  3777. const opacityNode = this.getFloat( scope );
  3778. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  3779. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  3780. } else {
  3781. node = opacityNode;
  3782. }
  3783. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  3784. if ( material.specularMap && material.specularMap.isTexture === true ) {
  3785. node = this.getTexture( 'specular' ).r;
  3786. } else {
  3787. node = float( 1 );
  3788. }
  3789. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  3790. const specularIntensity = this.getFloat( scope );
  3791. if ( material.specularMap ) {
  3792. node = specularIntensity.mul( this.getTexture( scope ).a );
  3793. } else {
  3794. node = specularIntensity;
  3795. }
  3796. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  3797. const specularColorNode = this.getColor( scope );
  3798. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  3799. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  3800. } else {
  3801. node = specularColorNode;
  3802. }
  3803. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  3804. const roughnessNode = this.getFloat( scope );
  3805. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  3806. node = roughnessNode.mul( this.getTexture( scope ).g );
  3807. } else {
  3808. node = roughnessNode;
  3809. }
  3810. } else if ( scope === MaterialNode.METALNESS ) {
  3811. const metalnessNode = this.getFloat( scope );
  3812. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  3813. node = metalnessNode.mul( this.getTexture( scope ).b );
  3814. } else {
  3815. node = metalnessNode;
  3816. }
  3817. } else if ( scope === MaterialNode.EMISSIVE ) {
  3818. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  3819. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  3820. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  3821. node = emissiveNode.mul( this.getTexture( scope ) );
  3822. } else {
  3823. node = emissiveNode;
  3824. }
  3825. } else if ( scope === MaterialNode.NORMAL ) {
  3826. if ( material.normalMap ) {
  3827. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  3828. node.normalMapType = material.normalMapType;
  3829. } else if ( material.bumpMap ) {
  3830. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  3831. } else {
  3832. node = normalView;
  3833. }
  3834. } else if ( scope === MaterialNode.CLEARCOAT ) {
  3835. const clearcoatNode = this.getFloat( scope );
  3836. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  3837. node = clearcoatNode.mul( this.getTexture( scope ).r );
  3838. } else {
  3839. node = clearcoatNode;
  3840. }
  3841. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  3842. const clearcoatRoughnessNode = this.getFloat( scope );
  3843. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  3844. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  3845. } else {
  3846. node = clearcoatRoughnessNode;
  3847. }
  3848. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  3849. if ( material.clearcoatNormalMap ) {
  3850. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  3851. } else {
  3852. node = normalView;
  3853. }
  3854. } else if ( scope === MaterialNode.SHEEN ) {
  3855. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  3856. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  3857. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  3858. } else {
  3859. node = sheenNode;
  3860. }
  3861. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  3862. const sheenRoughnessNode = this.getFloat( scope );
  3863. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  3864. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  3865. } else {
  3866. node = sheenRoughnessNode;
  3867. }
  3868. node = node.clamp( 0.07, 1.0 );
  3869. } else if ( scope === MaterialNode.ANISOTROPY ) {
  3870. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  3871. const anisotropyPolar = this.getTexture( scope );
  3872. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  3873. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  3874. } else {
  3875. node = materialAnisotropyVector;
  3876. }
  3877. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  3878. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  3879. if ( material.iridescenceThicknessMap ) {
  3880. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  3881. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  3882. } else {
  3883. node = iridescenceThicknessMaximum;
  3884. }
  3885. } else if ( scope === MaterialNode.TRANSMISSION ) {
  3886. const transmissionNode = this.getFloat( scope );
  3887. if ( material.transmissionMap ) {
  3888. node = transmissionNode.mul( this.getTexture( scope ).r );
  3889. } else {
  3890. node = transmissionNode;
  3891. }
  3892. } else if ( scope === MaterialNode.THICKNESS ) {
  3893. const thicknessNode = this.getFloat( scope );
  3894. if ( material.thicknessMap ) {
  3895. node = thicknessNode.mul( this.getTexture( scope ).g );
  3896. } else {
  3897. node = thicknessNode;
  3898. }
  3899. } else if ( scope === MaterialNode.IOR ) {
  3900. node = this.getFloat( scope );
  3901. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  3902. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  3903. } else if ( scope === MaterialNode.AO_MAP ) {
  3904. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  3905. } else {
  3906. const outputType = this.getNodeType( builder );
  3907. node = this.getCache( scope, outputType );
  3908. }
  3909. return node;
  3910. }
  3911. }
  3912. MaterialNode.ALPHA_TEST = 'alphaTest';
  3913. MaterialNode.COLOR = 'color';
  3914. MaterialNode.OPACITY = 'opacity';
  3915. MaterialNode.SHININESS = 'shininess';
  3916. MaterialNode.SPECULAR = 'specular';
  3917. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  3918. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  3919. MaterialNode.SPECULAR_COLOR = 'specularColor';
  3920. MaterialNode.REFLECTIVITY = 'reflectivity';
  3921. MaterialNode.ROUGHNESS = 'roughness';
  3922. MaterialNode.METALNESS = 'metalness';
  3923. MaterialNode.NORMAL = 'normal';
  3924. MaterialNode.CLEARCOAT = 'clearcoat';
  3925. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  3926. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  3927. MaterialNode.EMISSIVE = 'emissive';
  3928. MaterialNode.ROTATION = 'rotation';
  3929. MaterialNode.SHEEN = 'sheen';
  3930. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  3931. MaterialNode.ANISOTROPY = 'anisotropy';
  3932. MaterialNode.IRIDESCENCE = 'iridescence';
  3933. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  3934. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  3935. MaterialNode.IOR = 'ior';
  3936. MaterialNode.TRANSMISSION = 'transmission';
  3937. MaterialNode.THICKNESS = 'thickness';
  3938. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  3939. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  3940. MaterialNode.LINE_SCALE = 'scale';
  3941. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  3942. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  3943. MaterialNode.LINE_WIDTH = 'linewidth';
  3944. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  3945. MaterialNode.POINT_WIDTH = 'pointWidth';
  3946. MaterialNode.DISPERSION = 'dispersion';
  3947. MaterialNode.LIGHT_MAP = 'light';
  3948. MaterialNode.AO_MAP = 'ao';
  3949. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  3950. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  3951. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  3952. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  3953. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  3954. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  3955. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  3956. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  3957. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  3958. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  3959. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  3960. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  3961. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL ).context( { getUV: null } );
  3962. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  3963. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  3964. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL ).context( { getUV: null } );
  3965. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  3966. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  3967. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  3968. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  3969. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  3970. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  3971. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  3972. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  3973. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  3974. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  3975. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  3976. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  3977. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  3978. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  3979. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  3980. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  3981. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  3982. const materialPointWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_WIDTH );
  3983. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  3984. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  3985. const materialAOMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO_MAP );
  3986. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  3987. return frame.material;
  3988. } ).onRenderUpdate( function ( { material } ) {
  3989. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  3990. } );
  3991. class ModelViewProjectionNode extends TempNode {
  3992. static get type() {
  3993. return 'ModelViewProjectionNode';
  3994. }
  3995. constructor( positionNode = null ) {
  3996. super( 'vec4' );
  3997. this.positionNode = positionNode;
  3998. }
  3999. setup( builder ) {
  4000. if ( builder.shaderStage === 'fragment' ) {
  4001. return varying( builder.context.mvp );
  4002. }
  4003. const position = this.positionNode || positionLocal;
  4004. const viewMatrix = builder.renderer.nodes.modelViewMatrix || modelViewMatrix;
  4005. return cameraProjectionMatrix.mul( viewMatrix ).mul( position );
  4006. }
  4007. }
  4008. const modelViewProjection = /*@__PURE__*/ nodeProxy( ModelViewProjectionNode );
  4009. class IndexNode extends Node {
  4010. static get type() {
  4011. return 'IndexNode';
  4012. }
  4013. constructor( scope ) {
  4014. super( 'uint' );
  4015. this.scope = scope;
  4016. this.isInstanceIndexNode = true;
  4017. }
  4018. generate( builder ) {
  4019. const nodeType = this.getNodeType( builder );
  4020. const scope = this.scope;
  4021. let propertyName;
  4022. if ( scope === IndexNode.VERTEX ) {
  4023. // The index of a vertex within a mesh.
  4024. propertyName = builder.getVertexIndex();
  4025. } else if ( scope === IndexNode.INSTANCE ) {
  4026. // The index of either a mesh instance or an invocation of a compute shader.
  4027. propertyName = builder.getInstanceIndex();
  4028. } else if ( scope === IndexNode.DRAW ) {
  4029. // The index of a draw call.
  4030. propertyName = builder.getDrawIndex();
  4031. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  4032. // The index of a compute invocation within the scope of a workgroup load.
  4033. propertyName = builder.getInvocationLocalIndex();
  4034. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  4035. // The index of a compute invocation within the scope of a subgroup.
  4036. propertyName = builder.getInvocationSubgroupIndex();
  4037. } else if ( scope === IndexNode.SUBGROUP ) {
  4038. // The index of the subgroup the current compute invocation belongs to.
  4039. propertyName = builder.getSubgroupIndex();
  4040. } else {
  4041. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  4042. }
  4043. let output;
  4044. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  4045. output = propertyName;
  4046. } else {
  4047. const nodeVarying = varying( this );
  4048. output = nodeVarying.build( builder, nodeType );
  4049. }
  4050. return output;
  4051. }
  4052. }
  4053. IndexNode.VERTEX = 'vertex';
  4054. IndexNode.INSTANCE = 'instance';
  4055. IndexNode.SUBGROUP = 'subgroup';
  4056. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  4057. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  4058. IndexNode.DRAW = 'draw';
  4059. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  4060. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  4061. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  4062. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  4063. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  4064. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  4065. class InstanceNode extends Node {
  4066. static get type() {
  4067. return 'InstanceNode';
  4068. }
  4069. constructor( count, instanceMatrix, instanceColor ) {
  4070. super( 'void' );
  4071. this.count = count;
  4072. this.instanceMatrix = instanceMatrix;
  4073. this.instanceColor = instanceColor;
  4074. this.instanceMatrixNode = null;
  4075. this.instanceColorNode = null;
  4076. this.updateType = NodeUpdateType.FRAME;
  4077. this.buffer = null;
  4078. this.bufferColor = null;
  4079. }
  4080. setup( builder ) {
  4081. const { count, instanceMatrix, instanceColor } = this;
  4082. let { instanceMatrixNode, instanceColorNode } = this;
  4083. if ( instanceMatrixNode === null ) {
  4084. // 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.
  4085. if ( count <= 1000 ) {
  4086. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  4087. } else {
  4088. const buffer = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  4089. this.buffer = buffer;
  4090. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  4091. const instanceBuffers = [
  4092. // F.Signature -> bufferAttribute( array, type, stride, offset )
  4093. bufferFn( buffer, 'vec4', 16, 0 ),
  4094. bufferFn( buffer, 'vec4', 16, 4 ),
  4095. bufferFn( buffer, 'vec4', 16, 8 ),
  4096. bufferFn( buffer, 'vec4', 16, 12 )
  4097. ];
  4098. instanceMatrixNode = mat4( ...instanceBuffers );
  4099. }
  4100. this.instanceMatrixNode = instanceMatrixNode;
  4101. }
  4102. if ( instanceColor && instanceColorNode === null ) {
  4103. const buffer = new InstancedBufferAttribute( instanceColor.array, 3 );
  4104. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  4105. this.bufferColor = buffer;
  4106. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  4107. this.instanceColorNode = instanceColorNode;
  4108. }
  4109. // POSITION
  4110. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  4111. positionLocal.assign( instancePosition );
  4112. // NORMAL
  4113. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  4114. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  4115. // ASSIGNS
  4116. normalLocal.assign( instanceNormal );
  4117. }
  4118. // COLOR
  4119. if ( this.instanceColorNode !== null ) {
  4120. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  4121. }
  4122. }
  4123. update( /*frame*/ ) {
  4124. if ( this.instanceMatrix.usage !== DynamicDrawUsage && this.buffer != null && this.instanceMatrix.version !== this.buffer.version ) {
  4125. this.buffer.version = this.instanceMatrix.version;
  4126. }
  4127. if ( this.instanceColor && this.instanceColor.usage !== DynamicDrawUsage && this.bufferColor != null && this.instanceColor.version !== this.bufferColor.version ) {
  4128. this.bufferColor.version = this.instanceColor.version;
  4129. }
  4130. }
  4131. }
  4132. const instance = /*@__PURE__*/ nodeProxy( InstanceNode );
  4133. class InstancedMeshNode extends InstanceNode {
  4134. static get type() {
  4135. return 'InstancedMeshNode';
  4136. }
  4137. constructor( instanceMesh ) {
  4138. const { count, instanceMatrix, instanceColor } = instanceMesh;
  4139. super( count, instanceMatrix, instanceColor );
  4140. this.instanceMesh = instanceMesh;
  4141. }
  4142. }
  4143. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode );
  4144. class BatchNode extends Node {
  4145. static get type() {
  4146. return 'BatchNode';
  4147. }
  4148. constructor( batchMesh ) {
  4149. super( 'void' );
  4150. this.batchMesh = batchMesh;
  4151. this.batchingIdNode = null;
  4152. }
  4153. setup( builder ) {
  4154. // POSITION
  4155. if ( this.batchingIdNode === null ) {
  4156. if ( builder.getDrawIndex() === null ) {
  4157. this.batchingIdNode = instanceIndex;
  4158. } else {
  4159. this.batchingIdNode = drawIndex;
  4160. }
  4161. }
  4162. const getIndirectIndex = Fn( ( [ id ] ) => {
  4163. const size = textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 );
  4164. const x = int( id ).modInt( int( size ) );
  4165. const y = int( id ).div( int( size ) );
  4166. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  4167. } ).setLayout( {
  4168. name: 'getIndirectIndex',
  4169. type: 'uint',
  4170. inputs: [
  4171. { name: 'id', type: 'int' }
  4172. ]
  4173. } );
  4174. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  4175. const matricesTexture = this.batchMesh._matricesTexture;
  4176. const size = textureSize( textureLoad( matricesTexture ), 0 );
  4177. const j = float( indirectId ).mul( 4 ).toInt().toVar();
  4178. const x = j.modInt( size );
  4179. const y = j.div( int( size ) );
  4180. const batchingMatrix = mat4(
  4181. textureLoad( matricesTexture, ivec2( x, y ) ),
  4182. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  4183. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  4184. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  4185. );
  4186. const colorsTexture = this.batchMesh._colorsTexture;
  4187. if ( colorsTexture !== null ) {
  4188. const getBatchingColor = Fn( ( [ id ] ) => {
  4189. const size = textureSize( textureLoad( colorsTexture ), 0 ).x;
  4190. const j = id;
  4191. const x = j.modInt( size );
  4192. const y = j.div( size );
  4193. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  4194. } ).setLayout( {
  4195. name: 'getBatchingColor',
  4196. type: 'vec3',
  4197. inputs: [
  4198. { name: 'id', type: 'int' }
  4199. ]
  4200. } );
  4201. const color = getBatchingColor( indirectId );
  4202. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  4203. }
  4204. const bm = mat3( batchingMatrix );
  4205. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  4206. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  4207. const batchingNormal = bm.mul( transformedNormal ).xyz;
  4208. normalLocal.assign( batchingNormal );
  4209. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  4210. tangentLocal.mulAssign( bm );
  4211. }
  4212. }
  4213. }
  4214. const batch = /*@__PURE__*/ nodeProxy( BatchNode );
  4215. const _frameId = new WeakMap();
  4216. class SkinningNode extends Node {
  4217. static get type() {
  4218. return 'SkinningNode';
  4219. }
  4220. constructor( skinnedMesh, useReference = false ) {
  4221. super( 'void' );
  4222. this.skinnedMesh = skinnedMesh;
  4223. this.useReference = useReference;
  4224. this.updateType = NodeUpdateType.OBJECT;
  4225. //
  4226. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  4227. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  4228. let bindMatrixNode, bindMatrixInverseNode, boneMatricesNode;
  4229. if ( useReference ) {
  4230. bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  4231. bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  4232. boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  4233. } else {
  4234. bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  4235. bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  4236. boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  4237. }
  4238. this.bindMatrixNode = bindMatrixNode;
  4239. this.bindMatrixInverseNode = bindMatrixInverseNode;
  4240. this.boneMatricesNode = boneMatricesNode;
  4241. this.previousBoneMatricesNode = null;
  4242. }
  4243. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = positionLocal ) {
  4244. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  4245. const boneMatX = boneMatrices.element( skinIndexNode.x );
  4246. const boneMatY = boneMatrices.element( skinIndexNode.y );
  4247. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  4248. const boneMatW = boneMatrices.element( skinIndexNode.w );
  4249. // POSITION
  4250. const skinVertex = bindMatrixNode.mul( position );
  4251. const skinned = add(
  4252. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  4253. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  4254. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  4255. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  4256. );
  4257. return bindMatrixInverseNode.mul( skinned ).xyz;
  4258. }
  4259. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  4260. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  4261. const boneMatX = boneMatrices.element( skinIndexNode.x );
  4262. const boneMatY = boneMatrices.element( skinIndexNode.y );
  4263. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  4264. const boneMatW = boneMatrices.element( skinIndexNode.w );
  4265. // NORMAL
  4266. let skinMatrix = add(
  4267. skinWeightNode.x.mul( boneMatX ),
  4268. skinWeightNode.y.mul( boneMatY ),
  4269. skinWeightNode.z.mul( boneMatZ ),
  4270. skinWeightNode.w.mul( boneMatW )
  4271. );
  4272. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  4273. return skinMatrix.transformDirection( normal ).xyz;
  4274. }
  4275. getPreviousSkinnedPosition( builder ) {
  4276. const skinnedMesh = builder.object;
  4277. if ( this.previousBoneMatricesNode === null ) {
  4278. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  4279. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  4280. }
  4281. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  4282. }
  4283. needsPreviousBoneMatrices( builder ) {
  4284. const mrt = builder.renderer.getMRT();
  4285. return mrt && mrt.has( 'velocity' );
  4286. }
  4287. setup( builder ) {
  4288. if ( this.needsPreviousBoneMatrices( builder ) ) {
  4289. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  4290. }
  4291. const skinPosition = this.getSkinnedPosition();
  4292. positionLocal.assign( skinPosition );
  4293. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  4294. const skinNormal = this.getSkinnedNormal();
  4295. normalLocal.assign( skinNormal );
  4296. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  4297. tangentLocal.assign( skinNormal );
  4298. }
  4299. }
  4300. }
  4301. generate( builder, output ) {
  4302. if ( output !== 'void' ) {
  4303. return positionLocal.build( builder, output );
  4304. }
  4305. }
  4306. update( frame ) {
  4307. const object = this.useReference ? frame.object : this.skinnedMesh;
  4308. const skeleton = object.skeleton;
  4309. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  4310. _frameId.set( skeleton, frame.frameId );
  4311. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  4312. skeleton.update();
  4313. }
  4314. }
  4315. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  4316. const skinningReference = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh, true ) );
  4317. class LoopNode extends Node {
  4318. static get type() {
  4319. return 'LoopNode';
  4320. }
  4321. constructor( params = [] ) {
  4322. super();
  4323. this.params = params;
  4324. }
  4325. getVarName( index ) {
  4326. return String.fromCharCode( 'i'.charCodeAt() + index );
  4327. }
  4328. getProperties( builder ) {
  4329. const properties = builder.getNodeProperties( this );
  4330. if ( properties.stackNode !== undefined ) return properties;
  4331. //
  4332. const inputs = {};
  4333. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  4334. const param = this.params[ i ];
  4335. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  4336. const type = ( param.isNode !== true && param.type ) || 'int';
  4337. inputs[ name ] = expression( name, type );
  4338. }
  4339. const stack = builder.addStack(); // TODO: cache() it
  4340. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, stack, builder );
  4341. properties.stackNode = stack;
  4342. builder.removeStack();
  4343. return properties;
  4344. }
  4345. getNodeType( builder ) {
  4346. const { returnsNode } = this.getProperties( builder );
  4347. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  4348. }
  4349. setup( builder ) {
  4350. // setup properties
  4351. this.getProperties( builder );
  4352. }
  4353. generate( builder ) {
  4354. const properties = this.getProperties( builder );
  4355. const params = this.params;
  4356. const stackNode = properties.stackNode;
  4357. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  4358. const param = params[ i ];
  4359. let start = null, end = null, name = null, type = null, condition = null, update = null;
  4360. if ( param.isNode ) {
  4361. type = 'int';
  4362. name = this.getVarName( i );
  4363. start = '0';
  4364. end = param.build( builder, type );
  4365. condition = '<';
  4366. } else {
  4367. type = param.type || 'int';
  4368. name = param.name || this.getVarName( i );
  4369. start = param.start;
  4370. end = param.end;
  4371. condition = param.condition;
  4372. update = param.update;
  4373. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  4374. else if ( start && start.isNode ) start = start.build( builder, type );
  4375. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  4376. else if ( end && end.isNode ) end = end.build( builder, type );
  4377. if ( start !== undefined && end === undefined ) {
  4378. start = start + ' - 1';
  4379. end = '0';
  4380. condition = '>=';
  4381. } else if ( end !== undefined && start === undefined ) {
  4382. start = '0';
  4383. condition = '<';
  4384. }
  4385. if ( condition === undefined ) {
  4386. if ( Number( start ) > Number( end ) ) {
  4387. condition = '>=';
  4388. } else {
  4389. condition = '<';
  4390. }
  4391. }
  4392. }
  4393. const internalParam = { start, end, condition };
  4394. //
  4395. const startSnippet = internalParam.start;
  4396. const endSnippet = internalParam.end;
  4397. let declarationSnippet = '';
  4398. let conditionalSnippet = '';
  4399. let updateSnippet = '';
  4400. if ( ! update ) {
  4401. if ( type === 'int' || type === 'uint' ) {
  4402. if ( condition.includes( '<' ) ) update = '++';
  4403. else update = '--';
  4404. } else {
  4405. if ( condition.includes( '<' ) ) update = '+= 1.';
  4406. else update = '-= 1.';
  4407. }
  4408. }
  4409. declarationSnippet += builder.getVar( type, name ) + ' = ' + startSnippet;
  4410. conditionalSnippet += name + ' ' + condition + ' ' + endSnippet;
  4411. updateSnippet += name + ' ' + update;
  4412. const forSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  4413. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + forSnippet + ' {\n\n' ).addFlowTab();
  4414. }
  4415. const stackSnippet = stackNode.build( builder, 'void' );
  4416. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  4417. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  4418. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  4419. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  4420. }
  4421. builder.addFlowTab();
  4422. return returnsSnippet;
  4423. }
  4424. }
  4425. const Loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).append();
  4426. const Continue = () => expression( 'continue' ).append();
  4427. const Break = () => expression( 'break' ).append();
  4428. //
  4429. const loop = ( ...params ) => { // @deprecated, r168
  4430. console.warn( 'TSL.LoopNode: loop() has been renamed to Loop().' );
  4431. return Loop( ...params );
  4432. };
  4433. const _morphTextures = /*@__PURE__*/ new WeakMap();
  4434. const _morphVec4 = /*@__PURE__*/ new Vector4();
  4435. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  4436. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  4437. const y = texelIndex.div( width );
  4438. const x = texelIndex.sub( y.mul( width ) );
  4439. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth );
  4440. return bufferAttrib.mul( influence );
  4441. } );
  4442. function getEntry( geometry ) {
  4443. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  4444. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  4445. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  4446. // instead of using attributes, the WebGL 2 code path encodes morph targets
  4447. // into an array of data textures. Each layer represents a single morph target.
  4448. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  4449. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  4450. let entry = _morphTextures.get( geometry );
  4451. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  4452. if ( entry !== undefined ) entry.texture.dispose();
  4453. const morphTargets = geometry.morphAttributes.position || [];
  4454. const morphNormals = geometry.morphAttributes.normal || [];
  4455. const morphColors = geometry.morphAttributes.color || [];
  4456. let vertexDataCount = 0;
  4457. if ( hasMorphPosition === true ) vertexDataCount = 1;
  4458. if ( hasMorphNormals === true ) vertexDataCount = 2;
  4459. if ( hasMorphColors === true ) vertexDataCount = 3;
  4460. let width = geometry.attributes.position.count * vertexDataCount;
  4461. let height = 1;
  4462. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  4463. if ( width > maxTextureSize ) {
  4464. height = Math.ceil( width / maxTextureSize );
  4465. width = maxTextureSize;
  4466. }
  4467. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  4468. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  4469. bufferTexture.type = FloatType;
  4470. bufferTexture.needsUpdate = true;
  4471. // fill buffer
  4472. const vertexDataStride = vertexDataCount * 4;
  4473. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  4474. const morphTarget = morphTargets[ i ];
  4475. const morphNormal = morphNormals[ i ];
  4476. const morphColor = morphColors[ i ];
  4477. const offset = width * height * 4 * i;
  4478. for ( let j = 0; j < morphTarget.count; j ++ ) {
  4479. const stride = j * vertexDataStride;
  4480. if ( hasMorphPosition === true ) {
  4481. _morphVec4.fromBufferAttribute( morphTarget, j );
  4482. buffer[ offset + stride + 0 ] = _morphVec4.x;
  4483. buffer[ offset + stride + 1 ] = _morphVec4.y;
  4484. buffer[ offset + stride + 2 ] = _morphVec4.z;
  4485. buffer[ offset + stride + 3 ] = 0;
  4486. }
  4487. if ( hasMorphNormals === true ) {
  4488. _morphVec4.fromBufferAttribute( morphNormal, j );
  4489. buffer[ offset + stride + 4 ] = _morphVec4.x;
  4490. buffer[ offset + stride + 5 ] = _morphVec4.y;
  4491. buffer[ offset + stride + 6 ] = _morphVec4.z;
  4492. buffer[ offset + stride + 7 ] = 0;
  4493. }
  4494. if ( hasMorphColors === true ) {
  4495. _morphVec4.fromBufferAttribute( morphColor, j );
  4496. buffer[ offset + stride + 8 ] = _morphVec4.x;
  4497. buffer[ offset + stride + 9 ] = _morphVec4.y;
  4498. buffer[ offset + stride + 10 ] = _morphVec4.z;
  4499. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  4500. }
  4501. }
  4502. }
  4503. entry = {
  4504. count: morphTargetsCount,
  4505. texture: bufferTexture,
  4506. stride: vertexDataCount,
  4507. size: new Vector2( width, height )
  4508. };
  4509. _morphTextures.set( geometry, entry );
  4510. function disposeTexture() {
  4511. bufferTexture.dispose();
  4512. _morphTextures.delete( geometry );
  4513. geometry.removeEventListener( 'dispose', disposeTexture );
  4514. }
  4515. geometry.addEventListener( 'dispose', disposeTexture );
  4516. }
  4517. return entry;
  4518. }
  4519. class MorphNode extends Node {
  4520. static get type() {
  4521. return 'MorphNode';
  4522. }
  4523. constructor( mesh ) {
  4524. super( 'void' );
  4525. this.mesh = mesh;
  4526. this.morphBaseInfluence = uniform( 1 );
  4527. this.updateType = NodeUpdateType.OBJECT;
  4528. }
  4529. setup( builder ) {
  4530. const { geometry } = builder;
  4531. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  4532. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  4533. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  4534. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  4535. // nodes
  4536. const { texture: bufferMap, stride, size } = getEntry( geometry );
  4537. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  4538. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  4539. const width = int( size.width );
  4540. Loop( morphTargetsCount, ( { i } ) => {
  4541. const influence = float( 0 ).toVar();
  4542. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  4543. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  4544. } else {
  4545. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  4546. }
  4547. if ( hasMorphPosition === true ) {
  4548. positionLocal.addAssign( getMorph( {
  4549. bufferMap,
  4550. influence,
  4551. stride,
  4552. width,
  4553. depth: i,
  4554. offset: int( 0 )
  4555. } ) );
  4556. }
  4557. if ( hasMorphNormals === true ) {
  4558. normalLocal.addAssign( getMorph( {
  4559. bufferMap,
  4560. influence,
  4561. stride,
  4562. width,
  4563. depth: i,
  4564. offset: int( 1 )
  4565. } ) );
  4566. }
  4567. } );
  4568. }
  4569. update() {
  4570. const morphBaseInfluence = this.morphBaseInfluence;
  4571. if ( this.mesh.geometry.morphTargetsRelative ) {
  4572. morphBaseInfluence.value = 1;
  4573. } else {
  4574. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  4575. }
  4576. }
  4577. }
  4578. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode );
  4579. class LightingNode extends Node {
  4580. static get type() {
  4581. return 'LightingNode';
  4582. }
  4583. constructor() {
  4584. super( 'vec3' );
  4585. this.isLightingNode = true;
  4586. }
  4587. generate( /*builder*/ ) {
  4588. console.warn( 'Abstract function.' );
  4589. }
  4590. }
  4591. class AONode extends LightingNode {
  4592. static get type() {
  4593. return 'AONode';
  4594. }
  4595. constructor( aoNode = null ) {
  4596. super();
  4597. this.aoNode = aoNode;
  4598. }
  4599. setup( builder ) {
  4600. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  4601. }
  4602. }
  4603. class LightingContextNode extends ContextNode {
  4604. static get type() {
  4605. return 'LightingContextNode';
  4606. }
  4607. constructor( node, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  4608. super( node );
  4609. this.lightingModel = lightingModel;
  4610. this.backdropNode = backdropNode;
  4611. this.backdropAlphaNode = backdropAlphaNode;
  4612. this._value = null;
  4613. }
  4614. getContext() {
  4615. const { backdropNode, backdropAlphaNode } = this;
  4616. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  4617. directSpecular = vec3().toVar( 'directSpecular' ),
  4618. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  4619. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  4620. const reflectedLight = {
  4621. directDiffuse,
  4622. directSpecular,
  4623. indirectDiffuse,
  4624. indirectSpecular
  4625. };
  4626. const context = {
  4627. radiance: vec3().toVar( 'radiance' ),
  4628. irradiance: vec3().toVar( 'irradiance' ),
  4629. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  4630. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  4631. reflectedLight,
  4632. backdrop: backdropNode,
  4633. backdropAlpha: backdropAlphaNode
  4634. };
  4635. return context;
  4636. }
  4637. setup( builder ) {
  4638. this.value = this._value || ( this._value = this.getContext() );
  4639. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  4640. return super.setup( builder );
  4641. }
  4642. }
  4643. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  4644. class IrradianceNode extends LightingNode {
  4645. static get type() {
  4646. return 'IrradianceNode';
  4647. }
  4648. constructor( node ) {
  4649. super();
  4650. this.node = node;
  4651. }
  4652. setup( builder ) {
  4653. builder.context.irradiance.addAssign( this.node );
  4654. }
  4655. }
  4656. let screenSizeVec, viewportVec;
  4657. class ScreenNode extends Node {
  4658. static get type() {
  4659. return 'ScreenNode';
  4660. }
  4661. constructor( scope ) {
  4662. super();
  4663. this.scope = scope;
  4664. this.isViewportNode = true;
  4665. }
  4666. getNodeType() {
  4667. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  4668. else return 'vec2';
  4669. }
  4670. getUpdateType() {
  4671. let updateType = NodeUpdateType.NONE;
  4672. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT ) {
  4673. updateType = NodeUpdateType.RENDER;
  4674. }
  4675. this.updateType = updateType;
  4676. return updateType;
  4677. }
  4678. update( { renderer } ) {
  4679. const renderTarget = renderer.getRenderTarget();
  4680. if ( this.scope === ScreenNode.VIEWPORT ) {
  4681. if ( renderTarget !== null ) {
  4682. viewportVec.copy( renderTarget.viewport );
  4683. } else {
  4684. renderer.getViewport( viewportVec );
  4685. viewportVec.multiplyScalar( renderer.getPixelRatio() );
  4686. }
  4687. } else {
  4688. if ( renderTarget !== null ) {
  4689. screenSizeVec.width = renderTarget.width;
  4690. screenSizeVec.height = renderTarget.height;
  4691. } else {
  4692. renderer.getDrawingBufferSize( screenSizeVec );
  4693. }
  4694. }
  4695. }
  4696. setup( /*builder*/ ) {
  4697. const scope = this.scope;
  4698. let output = null;
  4699. if ( scope === ScreenNode.SIZE ) {
  4700. output = uniform( screenSizeVec || ( screenSizeVec = new Vector2() ) );
  4701. } else if ( scope === ScreenNode.VIEWPORT ) {
  4702. output = uniform( viewportVec || ( viewportVec = new Vector4() ) );
  4703. } else {
  4704. output = vec2( screenCoordinate.div( screenSize ) );
  4705. }
  4706. return output;
  4707. }
  4708. generate( builder ) {
  4709. if ( this.scope === ScreenNode.COORDINATE ) {
  4710. let coord = builder.getFragCoord();
  4711. if ( builder.isFlipY() ) {
  4712. // follow webgpu standards
  4713. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  4714. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  4715. }
  4716. return coord;
  4717. }
  4718. return super.generate( builder );
  4719. }
  4720. }
  4721. ScreenNode.COORDINATE = 'coordinate';
  4722. ScreenNode.VIEWPORT = 'viewport';
  4723. ScreenNode.SIZE = 'size';
  4724. ScreenNode.UV = 'uv';
  4725. // Screen
  4726. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  4727. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  4728. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  4729. // Viewport
  4730. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  4731. const viewportSize = viewport.zw;
  4732. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  4733. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  4734. // Deprecated
  4735. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  4736. console.warn( 'TSL.ViewportNode: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  4737. return screenSize;
  4738. }, 'vec2' ).once() )();
  4739. const viewportTopLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  4740. console.warn( 'TSL.ViewportNode: "viewportTopLeft" is deprecated. Use "screenUV" instead.' );
  4741. return screenUV;
  4742. }, 'vec2' ).once() )();
  4743. const viewportBottomLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  4744. console.warn( 'TSL.ViewportNode: "viewportBottomLeft" is deprecated. Use "screenUV.flipY()" instead.' );
  4745. return screenUV.flipY();
  4746. }, 'vec2' ).once() )();
  4747. const _size$4 = /*@__PURE__*/ new Vector2();
  4748. class ViewportTextureNode extends TextureNode {
  4749. static get type() {
  4750. return 'ViewportTextureNode';
  4751. }
  4752. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  4753. if ( framebufferTexture === null ) {
  4754. framebufferTexture = new FramebufferTexture();
  4755. framebufferTexture.minFilter = LinearMipmapLinearFilter;
  4756. }
  4757. super( framebufferTexture, uvNode, levelNode );
  4758. this.generateMipmaps = false;
  4759. this.isOutputTextureNode = true;
  4760. this.updateBeforeType = NodeUpdateType.FRAME;
  4761. }
  4762. updateBefore( frame ) {
  4763. const renderer = frame.renderer;
  4764. renderer.getDrawingBufferSize( _size$4 );
  4765. //
  4766. const framebufferTexture = this.value;
  4767. if ( framebufferTexture.image.width !== _size$4.width || framebufferTexture.image.height !== _size$4.height ) {
  4768. framebufferTexture.image.width = _size$4.width;
  4769. framebufferTexture.image.height = _size$4.height;
  4770. framebufferTexture.needsUpdate = true;
  4771. }
  4772. //
  4773. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  4774. framebufferTexture.generateMipmaps = this.generateMipmaps;
  4775. renderer.copyFramebufferToTexture( framebufferTexture );
  4776. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  4777. }
  4778. clone() {
  4779. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  4780. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  4781. return viewportTextureNode;
  4782. }
  4783. }
  4784. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode );
  4785. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } );
  4786. let sharedDepthbuffer = null;
  4787. class ViewportDepthTextureNode extends ViewportTextureNode {
  4788. static get type() {
  4789. return 'ViewportDepthTextureNode';
  4790. }
  4791. constructor( uvNode = screenUV, levelNode = null ) {
  4792. if ( sharedDepthbuffer === null ) {
  4793. sharedDepthbuffer = new DepthTexture();
  4794. }
  4795. super( uvNode, levelNode, sharedDepthbuffer );
  4796. }
  4797. }
  4798. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode );
  4799. class ViewportDepthNode extends Node {
  4800. static get type() {
  4801. return 'ViewportDepthNode';
  4802. }
  4803. constructor( scope, valueNode = null ) {
  4804. super( 'float' );
  4805. this.scope = scope;
  4806. this.valueNode = valueNode;
  4807. this.isViewportDepthNode = true;
  4808. }
  4809. generate( builder ) {
  4810. const { scope } = this;
  4811. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  4812. return builder.getFragDepth();
  4813. }
  4814. return super.generate( builder );
  4815. }
  4816. setup( { camera } ) {
  4817. const { scope } = this;
  4818. const value = this.valueNode;
  4819. let node = null;
  4820. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  4821. if ( value !== null ) {
  4822. node = depthBase().assign( value );
  4823. }
  4824. } else if ( scope === ViewportDepthNode.DEPTH ) {
  4825. if ( camera.isPerspectiveCamera ) {
  4826. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  4827. } else {
  4828. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  4829. }
  4830. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  4831. if ( value !== null ) {
  4832. if ( camera.isPerspectiveCamera ) {
  4833. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  4834. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  4835. } else {
  4836. node = value;
  4837. }
  4838. } else {
  4839. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  4840. }
  4841. }
  4842. return node;
  4843. }
  4844. }
  4845. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  4846. ViewportDepthNode.DEPTH = 'depth';
  4847. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  4848. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  4849. // -near maps to 0; -far maps to 1
  4850. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  4851. // maps orthographic depth in [ 0, 1 ] to viewZ
  4852. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  4853. // NOTE: https://twitter.com/gonnavis/status/1377183786949959682
  4854. // -near maps to 0; -far maps to 1
  4855. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  4856. // maps perspective depth in [ 0, 1 ] to viewZ
  4857. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  4858. // -near maps to 0; -far maps to 1
  4859. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  4860. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  4861. // The final logarithmic depth formula used here is adapted from one described in an
  4862. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  4863. // which was an improvement upon an earlier formula one described in an
  4864. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  4865. // Ulrich's formula is the following:
  4866. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  4867. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  4868. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  4869. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  4870. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  4871. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  4872. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  4873. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  4874. // be used, and ultimately Ulrich's "near plane" version was chosen.
  4875. // Outerra eventually made another improvement to their original "C-constant" variant,
  4876. // but it still does not incorporate the camera near plane (for this version,
  4877. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  4878. // Here we make 4 changes to Ulrich's formula:
  4879. // 1. Clamp the camera near plane so we don't divide by 0.
  4880. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  4881. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  4882. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  4883. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  4884. // so we do the same here, hence the 'viewZ.negate()' call.
  4885. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  4886. near = near.max( 1e-6 ).toVar();
  4887. const numerator = log2( viewZ.negate().div( near ) );
  4888. const denominator = log2( far.div( near ) );
  4889. return numerator.div( denominator );
  4890. };
  4891. // maps logarithmic depth in [ 0, 1 ] to viewZ
  4892. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  4893. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  4894. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  4895. // a negative viewZ).
  4896. const exponent = depth.mul( log( far.div( near ) ) );
  4897. return float( Math.E ).pow( exponent ).mul( near ).negate();
  4898. };
  4899. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  4900. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  4901. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH );
  4902. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  4903. depth.assign = ( value ) => depthBase( value );
  4904. class BuiltinNode extends Node {
  4905. constructor( name ) {
  4906. super( 'float' );
  4907. this.name = name;
  4908. this.isBuiltinNode = true;
  4909. }
  4910. generate( /* builder */ ) {
  4911. return this.name;
  4912. }
  4913. }
  4914. const builtin = nodeProxy( BuiltinNode );
  4915. class ClippingNode extends Node {
  4916. static get type() {
  4917. return 'ClippingNode';
  4918. }
  4919. constructor( scope = ClippingNode.DEFAULT ) {
  4920. super();
  4921. this.scope = scope;
  4922. }
  4923. setup( builder ) {
  4924. super.setup( builder );
  4925. const clippingContext = builder.clippingContext;
  4926. const { intersectionPlanes, unionPlanes } = clippingContext;
  4927. this.hardwareClipping = builder.material.hardwareClipping;
  4928. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  4929. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  4930. } else if ( this.scope === ClippingNode.HARDWARE ) {
  4931. return this.setupHardwareClipping( unionPlanes, builder );
  4932. } else {
  4933. return this.setupDefault( intersectionPlanes, unionPlanes );
  4934. }
  4935. }
  4936. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  4937. return Fn( () => {
  4938. const distanceToPlane = float().toVar( 'distanceToPlane' );
  4939. const distanceGradient = float().toVar( 'distanceToGradient' );
  4940. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  4941. const numUnionPlanes = unionPlanes.length;
  4942. if ( ! this.hardwareClipping && numUnionPlanes > 0 ) {
  4943. const clippingPlanes = uniformArray( unionPlanes );
  4944. Loop( numUnionPlanes, ( { i } ) => {
  4945. const plane = clippingPlanes.element( i );
  4946. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  4947. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  4948. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  4949. } );
  4950. }
  4951. const numIntersectionPlanes = intersectionPlanes.length;
  4952. if ( numIntersectionPlanes > 0 ) {
  4953. const clippingPlanes = uniformArray( intersectionPlanes );
  4954. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  4955. Loop( numIntersectionPlanes, ( { i } ) => {
  4956. const plane = clippingPlanes.element( i );
  4957. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  4958. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  4959. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  4960. } );
  4961. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  4962. }
  4963. diffuseColor.a.mulAssign( clipOpacity );
  4964. diffuseColor.a.equal( 0.0 ).discard();
  4965. } )();
  4966. }
  4967. setupDefault( intersectionPlanes, unionPlanes ) {
  4968. return Fn( () => {
  4969. const numUnionPlanes = unionPlanes.length;
  4970. if ( ! this.hardwareClipping && numUnionPlanes > 0 ) {
  4971. const clippingPlanes = uniformArray( unionPlanes );
  4972. Loop( numUnionPlanes, ( { i } ) => {
  4973. const plane = clippingPlanes.element( i );
  4974. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  4975. } );
  4976. }
  4977. const numIntersectionPlanes = intersectionPlanes.length;
  4978. if ( numIntersectionPlanes > 0 ) {
  4979. const clippingPlanes = uniformArray( intersectionPlanes );
  4980. const clipped = bool( true ).toVar( 'clipped' );
  4981. Loop( numIntersectionPlanes, ( { i } ) => {
  4982. const plane = clippingPlanes.element( i );
  4983. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  4984. } );
  4985. clipped.discard();
  4986. }
  4987. } )();
  4988. }
  4989. setupHardwareClipping( unionPlanes, builder ) {
  4990. const numUnionPlanes = unionPlanes.length;
  4991. builder.enableHardwareClipping( numUnionPlanes );
  4992. return Fn( () => {
  4993. const clippingPlanes = uniformArray( unionPlanes );
  4994. const hw_clip_distances = builtin( builder.getClipDistance() );
  4995. Loop( numUnionPlanes, ( { i } ) => {
  4996. const plane = clippingPlanes.element( i );
  4997. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  4998. hw_clip_distances.element( i ).assign( distance );
  4999. } );
  5000. } )();
  5001. }
  5002. }
  5003. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  5004. ClippingNode.DEFAULT = 'default';
  5005. ClippingNode.HARDWARE = 'hardware';
  5006. const clipping = () => nodeObject( new ClippingNode() );
  5007. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  5008. const hardwareClipping = () => nodeObject( new ClippingNode( ClippingNode.HARDWARE ) );
  5009. /**
  5010. * See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  5011. */
  5012. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  5013. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  5014. 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 ) ) ) ) ) );
  5015. } );
  5016. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  5017. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  5018. } );
  5019. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  5020. // Find the discretized derivatives of our coordinates
  5021. const maxDeriv = max$1(
  5022. length( dFdx( position.xyz ) ),
  5023. length( dFdy( position.xyz ) )
  5024. );
  5025. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  5026. // Find two nearest log-discretized noise scales
  5027. const pixScales = vec2(
  5028. exp2( floor( log2( pixScale ) ) ),
  5029. exp2( ceil( log2( pixScale ) ) )
  5030. );
  5031. // Compute alpha thresholds at our two noise scales
  5032. const alpha = vec2(
  5033. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  5034. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  5035. );
  5036. // Factor to interpolate lerp with
  5037. const lerpFactor = fract( log2( pixScale ) );
  5038. // Interpolate alpha threshold from noise at two scales
  5039. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) );
  5040. // Pass into CDF to compute uniformly distrib threshold
  5041. const a = min$1( lerpFactor, lerpFactor.oneMinus() );
  5042. const cases = vec3(
  5043. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  5044. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  5045. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) );
  5046. // Find our final, uniformly distributed alpha threshold (ατ)
  5047. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  5048. // Avoids ατ == 0. Could also do ατ =1-ατ
  5049. return clamp( threshold, 1.0e-6, 1.0 );
  5050. } ).setLayout( {
  5051. name: 'getAlphaHashThreshold',
  5052. type: 'float',
  5053. inputs: [
  5054. { name: 'position', type: 'vec3' }
  5055. ]
  5056. } );
  5057. class NodeMaterial extends Material {
  5058. static get type() {
  5059. return 'NodeMaterial';
  5060. }
  5061. get type() {
  5062. return this.constructor.type;
  5063. }
  5064. set type( _value ) { /* */ }
  5065. constructor() {
  5066. super();
  5067. this.isNodeMaterial = true;
  5068. this.forceSinglePass = false;
  5069. this.fog = true;
  5070. this.lights = false;
  5071. this.hardwareClipping = false;
  5072. this.lightsNode = null;
  5073. this.envNode = null;
  5074. this.aoNode = null;
  5075. this.colorNode = null;
  5076. this.normalNode = null;
  5077. this.opacityNode = null;
  5078. this.backdropNode = null;
  5079. this.backdropAlphaNode = null;
  5080. this.alphaTestNode = null;
  5081. this.positionNode = null;
  5082. this.geometryNode = null;
  5083. this.depthNode = null;
  5084. this.shadowPositionNode = null;
  5085. this.receivedShadowNode = null;
  5086. this.castShadowNode = null;
  5087. this.outputNode = null;
  5088. this.mrtNode = null;
  5089. this.fragmentNode = null;
  5090. this.vertexNode = null;
  5091. }
  5092. customProgramCacheKey() {
  5093. return this.type + getCacheKey$1( this );
  5094. }
  5095. build( builder ) {
  5096. this.setup( builder );
  5097. }
  5098. setupObserver( builder ) {
  5099. return new NodeMaterialObserver( builder );
  5100. }
  5101. setup( builder ) {
  5102. builder.context.setupNormal = () => this.setupNormal( builder );
  5103. const renderer = builder.renderer;
  5104. const renderTarget = renderer.getRenderTarget();
  5105. // < VERTEX STAGE >
  5106. builder.addStack();
  5107. builder.stack.outputNode = this.vertexNode || this.setupPosition( builder );
  5108. if ( this.geometryNode !== null ) {
  5109. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  5110. }
  5111. builder.addFlow( 'vertex', builder.removeStack() );
  5112. // < FRAGMENT STAGE >
  5113. builder.addStack();
  5114. let resultNode;
  5115. const clippingNode = this.setupClipping( builder );
  5116. if ( this.depthWrite === true ) {
  5117. // only write depth if depth buffer is configured
  5118. if ( renderTarget !== null ) {
  5119. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  5120. } else {
  5121. if ( renderer.depth === true ) this.setupDepth( builder );
  5122. }
  5123. }
  5124. if ( this.fragmentNode === null ) {
  5125. this.setupDiffuseColor( builder );
  5126. this.setupVariants( builder );
  5127. const outgoingLightNode = this.setupLighting( builder );
  5128. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  5129. // force unsigned floats - useful for RenderTargets
  5130. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  5131. resultNode = this.setupOutput( builder, basicOutput );
  5132. // OUTPUT NODE
  5133. output.assign( resultNode );
  5134. //
  5135. if ( this.outputNode !== null ) resultNode = this.outputNode;
  5136. // MRT
  5137. if ( renderTarget !== null ) {
  5138. const mrt = renderer.getMRT();
  5139. const materialMRT = this.mrtNode;
  5140. if ( mrt !== null ) {
  5141. resultNode = mrt;
  5142. if ( materialMRT !== null ) {
  5143. resultNode = mrt.merge( materialMRT );
  5144. }
  5145. } else if ( materialMRT !== null ) {
  5146. resultNode = materialMRT;
  5147. }
  5148. }
  5149. } else {
  5150. let fragmentNode = this.fragmentNode;
  5151. if ( fragmentNode.isOutputStructNode !== true ) {
  5152. fragmentNode = vec4( fragmentNode );
  5153. }
  5154. resultNode = this.setupOutput( builder, fragmentNode );
  5155. }
  5156. builder.stack.outputNode = resultNode;
  5157. builder.addFlow( 'fragment', builder.removeStack() );
  5158. // < MONITOR >
  5159. builder.monitor = this.setupObserver( builder );
  5160. }
  5161. setupClipping( builder ) {
  5162. if ( builder.clippingContext === null ) return null;
  5163. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  5164. let result = null;
  5165. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  5166. const samples = builder.renderer.samples;
  5167. if ( this.alphaToCoverage && samples > 1 ) {
  5168. // to be added to flow when the color/alpha value has been determined
  5169. result = clippingAlpha();
  5170. } else {
  5171. builder.stack.add( clipping() );
  5172. }
  5173. }
  5174. return result;
  5175. }
  5176. setupHardwareClipping( builder ) {
  5177. this.hardwareClipping = false;
  5178. if ( builder.clippingContext === null ) return;
  5179. const candidateCount = builder.clippingContext.unionPlanes.length;
  5180. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  5181. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  5182. builder.stack.add( hardwareClipping() );
  5183. this.hardwareClipping = true;
  5184. }
  5185. return;
  5186. }
  5187. setupDepth( builder ) {
  5188. const { renderer, camera } = builder;
  5189. // Depth
  5190. let depthNode = this.depthNode;
  5191. if ( depthNode === null ) {
  5192. const mrt = renderer.getMRT();
  5193. if ( mrt && mrt.has( 'depth' ) ) {
  5194. depthNode = mrt.get( 'depth' );
  5195. } else if ( renderer.logarithmicDepthBuffer === true ) {
  5196. if ( camera.isPerspectiveCamera ) {
  5197. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  5198. } else {
  5199. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  5200. }
  5201. }
  5202. }
  5203. if ( depthNode !== null ) {
  5204. depth.assign( depthNode ).append();
  5205. }
  5206. }
  5207. setupPosition( builder ) {
  5208. const { object } = builder;
  5209. const geometry = object.geometry;
  5210. builder.addStack();
  5211. // Vertex
  5212. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  5213. morphReference( object ).append();
  5214. }
  5215. if ( object.isSkinnedMesh === true ) {
  5216. skinningReference( object ).append();
  5217. }
  5218. if ( this.displacementMap ) {
  5219. const displacementMap = materialReference( 'displacementMap', 'texture' );
  5220. const displacementScale = materialReference( 'displacementScale', 'float' );
  5221. const displacementBias = materialReference( 'displacementBias', 'float' );
  5222. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  5223. }
  5224. if ( object.isBatchedMesh ) {
  5225. batch( object ).append();
  5226. }
  5227. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  5228. instancedMesh( object ).append();
  5229. }
  5230. if ( this.positionNode !== null ) {
  5231. positionLocal.assign( this.positionNode );
  5232. }
  5233. this.setupHardwareClipping( builder );
  5234. const mvp = modelViewProjection();
  5235. builder.context.vertex = builder.removeStack();
  5236. builder.context.mvp = mvp;
  5237. return mvp;
  5238. }
  5239. setupDiffuseColor( { object, geometry } ) {
  5240. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  5241. // VERTEX COLORS
  5242. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  5243. colorNode = vec4( colorNode.xyz.mul( attribute( 'color', 'vec3' ) ), colorNode.a );
  5244. }
  5245. // Instanced colors
  5246. if ( object.instanceColor ) {
  5247. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  5248. colorNode = instanceColor.mul( colorNode );
  5249. }
  5250. if ( object.isBatchedMesh && object._colorsTexture ) {
  5251. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  5252. colorNode = batchColor.mul( colorNode );
  5253. }
  5254. // COLOR
  5255. diffuseColor.assign( colorNode );
  5256. // OPACITY
  5257. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  5258. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  5259. // ALPHA TEST
  5260. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  5261. const alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  5262. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  5263. }
  5264. // ALPHA HASH
  5265. if ( this.alphaHash === true ) {
  5266. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  5267. }
  5268. if ( this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false ) {
  5269. diffuseColor.a.assign( 1.0 );
  5270. }
  5271. }
  5272. setupVariants( /*builder*/ ) {
  5273. // Interface function.
  5274. }
  5275. setupOutgoingLight() {
  5276. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  5277. }
  5278. setupNormal() {
  5279. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  5280. }
  5281. setupEnvironment( /*builder*/ ) {
  5282. let node = null;
  5283. if ( this.envNode ) {
  5284. node = this.envNode;
  5285. } else if ( this.envMap ) {
  5286. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  5287. }
  5288. return node;
  5289. }
  5290. setupLightMap( builder ) {
  5291. let node = null;
  5292. if ( builder.material.lightMap ) {
  5293. node = new IrradianceNode( materialLightMap );
  5294. }
  5295. return node;
  5296. }
  5297. setupLights( builder ) {
  5298. const materialLightsNode = [];
  5299. //
  5300. const envNode = this.setupEnvironment( builder );
  5301. if ( envNode && envNode.isLightingNode ) {
  5302. materialLightsNode.push( envNode );
  5303. }
  5304. const lightMapNode = this.setupLightMap( builder );
  5305. if ( lightMapNode && lightMapNode.isLightingNode ) {
  5306. materialLightsNode.push( lightMapNode );
  5307. }
  5308. if ( this.aoNode !== null || builder.material.aoMap ) {
  5309. const aoNode = this.aoNode !== null ? this.aoNode : materialAOMap;
  5310. materialLightsNode.push( new AONode( aoNode ) );
  5311. }
  5312. let lightsN = this.lightsNode || builder.lightsNode;
  5313. if ( materialLightsNode.length > 0 ) {
  5314. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  5315. }
  5316. return lightsN;
  5317. }
  5318. setupLightingModel( /*builder*/ ) {
  5319. // Interface function.
  5320. }
  5321. setupLighting( builder ) {
  5322. const { material } = builder;
  5323. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  5324. // OUTGOING LIGHT
  5325. const lights = this.lights === true || this.lightsNode !== null;
  5326. const lightsNode = lights ? this.setupLights( builder ) : null;
  5327. let outgoingLightNode = this.setupOutgoingLight( builder );
  5328. if ( lightsNode && lightsNode.getScope().hasLights ) {
  5329. const lightingModel = this.setupLightingModel( builder );
  5330. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  5331. } else if ( backdropNode !== null ) {
  5332. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  5333. }
  5334. // EMISSIVE
  5335. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  5336. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  5337. outgoingLightNode = outgoingLightNode.add( emissive );
  5338. }
  5339. return outgoingLightNode;
  5340. }
  5341. setupOutput( builder, outputNode ) {
  5342. // FOG
  5343. if ( this.fog === true ) {
  5344. const fogNode = builder.fogNode;
  5345. if ( fogNode ) outputNode = vec4( fogNode.mix( outputNode.rgb, fogNode.colorNode ), outputNode.a );
  5346. }
  5347. return outputNode;
  5348. }
  5349. setDefaultValues( material ) {
  5350. // This approach is to reuse the native refreshUniforms*
  5351. // and turn available the use of features like transmission and environment in core
  5352. for ( const property in material ) {
  5353. const value = material[ property ];
  5354. if ( this[ property ] === undefined ) {
  5355. this[ property ] = value;
  5356. if ( value && value.clone ) this[ property ] = value.clone();
  5357. }
  5358. }
  5359. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  5360. for ( const key in descriptors ) {
  5361. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  5362. descriptors[ key ].get !== undefined ) {
  5363. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  5364. }
  5365. }
  5366. }
  5367. toJSON( meta ) {
  5368. const isRoot = ( meta === undefined || typeof meta === 'string' );
  5369. if ( isRoot ) {
  5370. meta = {
  5371. textures: {},
  5372. images: {},
  5373. nodes: {}
  5374. };
  5375. }
  5376. const data = Material.prototype.toJSON.call( this, meta );
  5377. const nodeChildren = getNodeChildren( this );
  5378. data.inputNodes = {};
  5379. for ( const { property, childNode } of nodeChildren ) {
  5380. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  5381. }
  5382. // TODO: Copied from Object3D.toJSON
  5383. function extractFromCache( cache ) {
  5384. const values = [];
  5385. for ( const key in cache ) {
  5386. const data = cache[ key ];
  5387. delete data.metadata;
  5388. values.push( data );
  5389. }
  5390. return values;
  5391. }
  5392. if ( isRoot ) {
  5393. const textures = extractFromCache( meta.textures );
  5394. const images = extractFromCache( meta.images );
  5395. const nodes = extractFromCache( meta.nodes );
  5396. if ( textures.length > 0 ) data.textures = textures;
  5397. if ( images.length > 0 ) data.images = images;
  5398. if ( nodes.length > 0 ) data.nodes = nodes;
  5399. }
  5400. return data;
  5401. }
  5402. copy( source ) {
  5403. this.lightsNode = source.lightsNode;
  5404. this.envNode = source.envNode;
  5405. this.colorNode = source.colorNode;
  5406. this.normalNode = source.normalNode;
  5407. this.opacityNode = source.opacityNode;
  5408. this.backdropNode = source.backdropNode;
  5409. this.backdropAlphaNode = source.backdropAlphaNode;
  5410. this.alphaTestNode = source.alphaTestNode;
  5411. this.positionNode = source.positionNode;
  5412. this.geometryNode = source.geometryNode;
  5413. this.depthNode = source.depthNode;
  5414. this.shadowPositionNode = source.shadowPositionNode;
  5415. this.receivedShadowNode = source.receivedShadowNode;
  5416. this.castShadowNode = source.castShadowNode;
  5417. this.outputNode = source.outputNode;
  5418. this.mrtNode = source.mrtNode;
  5419. this.fragmentNode = source.fragmentNode;
  5420. this.vertexNode = source.vertexNode;
  5421. return super.copy( source );
  5422. }
  5423. }
  5424. const _defaultValues$e = /*@__PURE__*/ new PointsMaterial();
  5425. class InstancedPointsNodeMaterial extends NodeMaterial {
  5426. static get type() {
  5427. return 'InstancedPointsNodeMaterial';
  5428. }
  5429. constructor( params = {} ) {
  5430. super();
  5431. this.lights = false;
  5432. this.useAlphaToCoverage = true;
  5433. this.useColor = params.vertexColors;
  5434. this.pointWidth = 1;
  5435. this.pointColorNode = null;
  5436. this.pointWidthNode = null;
  5437. this.setDefaultValues( _defaultValues$e );
  5438. this.setValues( params );
  5439. }
  5440. setup( builder ) {
  5441. this.setupShaders( builder );
  5442. super.setup( builder );
  5443. }
  5444. setupShaders( { renderer } ) {
  5445. const useAlphaToCoverage = this.alphaToCoverage;
  5446. const useColor = this.useColor;
  5447. this.vertexNode = Fn( () => {
  5448. const instancePosition = attribute( 'instancePosition' ).xyz;
  5449. // camera space
  5450. const mvPos = vec4( modelViewMatrix.mul( vec4( instancePosition, 1.0 ) ) );
  5451. const aspect = viewport.z.div( viewport.w );
  5452. // clip space
  5453. const clipPos = cameraProjectionMatrix.mul( mvPos );
  5454. // offset in ndc space
  5455. const offset = positionGeometry.xy.toVar();
  5456. offset.mulAssign( this.pointWidthNode ? this.pointWidthNode : materialPointWidth );
  5457. offset.assign( offset.div( viewport.z ) );
  5458. offset.y.assign( offset.y.mul( aspect ) );
  5459. // back to clip space
  5460. offset.assign( offset.mul( clipPos.w ) );
  5461. //clipPos.xy += offset;
  5462. clipPos.addAssign( vec4( offset, 0, 0 ) );
  5463. return clipPos;
  5464. } )();
  5465. this.fragmentNode = Fn( () => {
  5466. const alpha = float( 1 ).toVar();
  5467. const len2 = lengthSq( uv().mul( 2 ).sub( 1 ) );
  5468. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  5469. const dlen = float( len2.fwidth() ).toVar();
  5470. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  5471. } else {
  5472. len2.greaterThan( 1.0 ).discard();
  5473. }
  5474. let pointColorNode;
  5475. if ( this.pointColorNode ) {
  5476. pointColorNode = this.pointColorNode;
  5477. } else {
  5478. if ( useColor ) {
  5479. const instanceColor = attribute( 'instanceColor' );
  5480. pointColorNode = instanceColor.mul( materialColor );
  5481. } else {
  5482. pointColorNode = materialColor;
  5483. }
  5484. }
  5485. alpha.mulAssign( materialOpacity );
  5486. return vec4( pointColorNode, alpha );
  5487. } )();
  5488. }
  5489. get alphaToCoverage() {
  5490. return this.useAlphaToCoverage;
  5491. }
  5492. set alphaToCoverage( value ) {
  5493. if ( this.useAlphaToCoverage !== value ) {
  5494. this.useAlphaToCoverage = value;
  5495. this.needsUpdate = true;
  5496. }
  5497. }
  5498. }
  5499. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  5500. class LineBasicNodeMaterial extends NodeMaterial {
  5501. static get type() {
  5502. return 'LineBasicNodeMaterial';
  5503. }
  5504. constructor( parameters ) {
  5505. super();
  5506. this.isLineBasicNodeMaterial = true;
  5507. this.lights = false;
  5508. this.setDefaultValues( _defaultValues$d );
  5509. this.setValues( parameters );
  5510. }
  5511. }
  5512. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  5513. class LineDashedNodeMaterial extends NodeMaterial {
  5514. static get type() {
  5515. return 'LineDashedNodeMaterial';
  5516. }
  5517. constructor( parameters ) {
  5518. super();
  5519. this.isLineDashedNodeMaterial = true;
  5520. this.lights = false;
  5521. this.setDefaultValues( _defaultValues$c );
  5522. this.dashOffset = 0;
  5523. this.offsetNode = null;
  5524. this.dashScaleNode = null;
  5525. this.dashSizeNode = null;
  5526. this.gapSizeNode = null;
  5527. this.setValues( parameters );
  5528. }
  5529. setupVariants() {
  5530. const offsetNode = this.offsetNode ? float( this.offsetNodeNode ) : materialLineDashOffset;
  5531. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  5532. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  5533. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  5534. dashSize.assign( dashSizeNode );
  5535. gapSize.assign( gapSizeNode );
  5536. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  5537. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  5538. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  5539. }
  5540. }
  5541. let _sharedFramebuffer = null;
  5542. class ViewportSharedTextureNode extends ViewportTextureNode {
  5543. static get type() {
  5544. return 'ViewportSharedTextureNode';
  5545. }
  5546. constructor( uvNode = screenUV, levelNode = null ) {
  5547. if ( _sharedFramebuffer === null ) {
  5548. _sharedFramebuffer = new FramebufferTexture();
  5549. }
  5550. super( uvNode, levelNode, _sharedFramebuffer );
  5551. }
  5552. updateReference() {
  5553. return this;
  5554. }
  5555. }
  5556. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode );
  5557. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  5558. class Line2NodeMaterial extends NodeMaterial {
  5559. static get type() {
  5560. return 'Line2NodeMaterial';
  5561. }
  5562. constructor( params = {} ) {
  5563. super();
  5564. this.lights = false;
  5565. this.setDefaultValues( _defaultValues$b );
  5566. this.useAlphaToCoverage = true;
  5567. this.useColor = params.vertexColors;
  5568. this.useDash = params.dashed;
  5569. this.useWorldUnits = false;
  5570. this.dashOffset = 0;
  5571. this.lineWidth = 1;
  5572. this.lineColorNode = null;
  5573. this.offsetNode = null;
  5574. this.dashScaleNode = null;
  5575. this.dashSizeNode = null;
  5576. this.gapSizeNode = null;
  5577. this.blending = NoBlending;
  5578. this.setValues( params );
  5579. }
  5580. setup( builder ) {
  5581. this.setupShaders( builder );
  5582. super.setup( builder );
  5583. }
  5584. setupShaders( { renderer } ) {
  5585. const useAlphaToCoverage = this.alphaToCoverage;
  5586. const useColor = this.useColor;
  5587. const useDash = this.dashed;
  5588. const useWorldUnits = this.worldUnits;
  5589. const trimSegment = Fn( ( { start, end } ) => {
  5590. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  5591. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  5592. const nearEstimate = b.mul( - 0.5 ).div( a );
  5593. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  5594. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  5595. } ).setLayout( {
  5596. name: 'trimSegment',
  5597. type: 'vec4',
  5598. inputs: [
  5599. { name: 'start', type: 'vec4' },
  5600. { name: 'end', type: 'vec4' }
  5601. ]
  5602. } );
  5603. this.vertexNode = Fn( () => {
  5604. const instanceStart = attribute( 'instanceStart' );
  5605. const instanceEnd = attribute( 'instanceEnd' );
  5606. // camera space
  5607. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  5608. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  5609. if ( useDash ) {
  5610. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  5611. const offsetNode = this.offsetNode ? float( this.offsetNodeNode ) : materialLineDashOffset;
  5612. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  5613. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  5614. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  5615. lineDistance = lineDistance.add( offsetNode );
  5616. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  5617. }
  5618. if ( useWorldUnits ) {
  5619. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  5620. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  5621. }
  5622. const aspect = viewport.z.div( viewport.w );
  5623. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  5624. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  5625. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  5626. // perhaps there is a more elegant solution -- WestLangley
  5627. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( - 1.0 ); // 4th entry in the 3rd column
  5628. If( perspective, () => {
  5629. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  5630. end.assign( trimSegment( { start: start, end: end } ) );
  5631. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  5632. start.assign( trimSegment( { start: end, end: start } ) );
  5633. } );
  5634. } );
  5635. // clip space
  5636. const clipStart = cameraProjectionMatrix.mul( start );
  5637. const clipEnd = cameraProjectionMatrix.mul( end );
  5638. // ndc space
  5639. const ndcStart = clipStart.xyz.div( clipStart.w );
  5640. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  5641. // direction
  5642. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  5643. // account for clip-space aspect ratio
  5644. dir.x.assign( dir.x.mul( aspect ) );
  5645. dir.assign( dir.normalize() );
  5646. const clip = vec4().toVar();
  5647. if ( useWorldUnits ) {
  5648. // get the offset direction as perpendicular to the view vector
  5649. const worldDir = end.xyz.sub( start.xyz ).normalize();
  5650. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  5651. const worldUp = worldDir.cross( tmpFwd ).normalize();
  5652. const worldFwd = worldDir.cross( worldUp );
  5653. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  5654. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  5655. // height offset
  5656. const hw = materialLineWidth.mul( 0.5 );
  5657. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  5658. // don't extend the line if we're rendering dashes because we
  5659. // won't be rendering the endcaps
  5660. if ( ! useDash ) {
  5661. // cap extension
  5662. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  5663. // add width to the box
  5664. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  5665. // endcaps
  5666. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  5667. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  5668. } );
  5669. }
  5670. // project the worldpos
  5671. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  5672. // shift the depth of the projected points so the line
  5673. // segments overlap neatly
  5674. const clipPose = vec3().toVar();
  5675. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  5676. clip.z.assign( clipPose.z.mul( clip.w ) );
  5677. } else {
  5678. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  5679. // undo aspect ratio adjustment
  5680. dir.x.assign( dir.x.div( aspect ) );
  5681. offset.x.assign( offset.x.div( aspect ) );
  5682. // sign flip
  5683. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  5684. // endcaps
  5685. If( positionGeometry.y.lessThan( 0.0 ), () => {
  5686. offset.assign( offset.sub( dir ) );
  5687. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  5688. offset.assign( offset.add( dir ) );
  5689. } );
  5690. // adjust for linewidth
  5691. offset.assign( offset.mul( materialLineWidth ) );
  5692. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  5693. offset.assign( offset.div( viewport.w ) );
  5694. // select end
  5695. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  5696. // back to clip space
  5697. offset.assign( offset.mul( clip.w ) );
  5698. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  5699. }
  5700. return clip;
  5701. } )();
  5702. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  5703. const p13 = p1.sub( p3 );
  5704. const p43 = p4.sub( p3 );
  5705. const p21 = p2.sub( p1 );
  5706. const d1343 = p13.dot( p43 );
  5707. const d4321 = p43.dot( p21 );
  5708. const d1321 = p13.dot( p21 );
  5709. const d4343 = p43.dot( p43 );
  5710. const d2121 = p21.dot( p21 );
  5711. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  5712. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  5713. const mua = numer.div( denom ).clamp();
  5714. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  5715. return vec2( mua, mub );
  5716. } );
  5717. this.colorNode = Fn( () => {
  5718. const vUv = uv();
  5719. if ( useDash ) {
  5720. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  5721. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  5722. dashSize.assign( dashSizeNode );
  5723. gapSize.assign( gapSizeNode );
  5724. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  5725. vUv.y.lessThan( - 1.0 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  5726. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  5727. }
  5728. const alpha = float( 1 ).toVar( 'alpha' );
  5729. if ( useWorldUnits ) {
  5730. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  5731. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  5732. // Find the closest points on the view ray and the line segment
  5733. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  5734. const lineDir = worldEnd.sub( worldStart );
  5735. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  5736. const p1 = worldStart.add( lineDir.mul( params.x ) );
  5737. const p2 = rayEnd.mul( params.y );
  5738. const delta = p1.sub( p2 );
  5739. const len = delta.length();
  5740. const norm = len.div( materialLineWidth );
  5741. if ( ! useDash ) {
  5742. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  5743. const dnorm = norm.fwidth();
  5744. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  5745. } else {
  5746. norm.greaterThan( 0.5 ).discard();
  5747. }
  5748. }
  5749. } else {
  5750. // round endcaps
  5751. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  5752. const a = vUv.x;
  5753. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  5754. const len2 = a.mul( a ).add( b.mul( b ) );
  5755. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  5756. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  5757. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  5758. } );
  5759. } else {
  5760. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  5761. const a = vUv.x;
  5762. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  5763. const len2 = a.mul( a ).add( b.mul( b ) );
  5764. len2.greaterThan( 1.0 ).discard();
  5765. } );
  5766. }
  5767. }
  5768. let lineColorNode;
  5769. if ( this.lineColorNode ) {
  5770. lineColorNode = this.lineColorNode;
  5771. } else {
  5772. if ( useColor ) {
  5773. const instanceColorStart = attribute( 'instanceColorStart' );
  5774. const instanceColorEnd = attribute( 'instanceColorEnd' );
  5775. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  5776. lineColorNode = instanceColor.mul( materialColor );
  5777. } else {
  5778. lineColorNode = materialColor;
  5779. }
  5780. }
  5781. return vec4( lineColorNode, alpha );
  5782. } )();
  5783. if ( this.transparent ) {
  5784. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  5785. this.outputNode = vec4( this.colorNode.rgb.mul( opacityNode ).add( viewportSharedTexture().rgb.mul( opacityNode.oneMinus() ) ), this.colorNode.a );
  5786. }
  5787. }
  5788. get worldUnits() {
  5789. return this.useWorldUnits;
  5790. }
  5791. set worldUnits( value ) {
  5792. if ( this.useWorldUnits !== value ) {
  5793. this.useWorldUnits = value;
  5794. this.needsUpdate = true;
  5795. }
  5796. }
  5797. get dashed() {
  5798. return this.useDash;
  5799. }
  5800. set dashed( value ) {
  5801. if ( this.useDash !== value ) {
  5802. this.useDash = value;
  5803. this.needsUpdate = true;
  5804. }
  5805. }
  5806. get alphaToCoverage() {
  5807. return this.useAlphaToCoverage;
  5808. }
  5809. set alphaToCoverage( value ) {
  5810. if ( this.useAlphaToCoverage !== value ) {
  5811. this.useAlphaToCoverage = value;
  5812. this.needsUpdate = true;
  5813. }
  5814. }
  5815. }
  5816. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  5817. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  5818. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  5819. class MeshNormalNodeMaterial extends NodeMaterial {
  5820. static get type() {
  5821. return 'MeshNormalNodeMaterial';
  5822. }
  5823. constructor( parameters ) {
  5824. super();
  5825. this.lights = false;
  5826. this.isMeshNormalNodeMaterial = true;
  5827. this.setDefaultValues( _defaultValues$a );
  5828. this.setValues( parameters );
  5829. }
  5830. setupDiffuseColor() {
  5831. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  5832. diffuseColor.assign( vec4( directionToColor( transformedNormalView ), opacityNode ) );
  5833. }
  5834. }
  5835. class EquirectUVNode extends TempNode {
  5836. static get type() {
  5837. return 'EquirectUVNode';
  5838. }
  5839. constructor( dirNode = positionWorldDirection ) {
  5840. super( 'vec2' );
  5841. this.dirNode = dirNode;
  5842. }
  5843. setup() {
  5844. const dir = this.dirNode;
  5845. const u = dir.z.atan2( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  5846. const v = dir.y.clamp( - 1.0, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  5847. return vec2( u, v );
  5848. }
  5849. }
  5850. const equirectUV = /*@__PURE__*/ nodeProxy( EquirectUVNode );
  5851. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  5852. class CubeRenderTarget extends WebGLCubeRenderTarget {
  5853. constructor( size = 1, options = {} ) {
  5854. super( size, options );
  5855. this.isCubeRenderTarget = true;
  5856. }
  5857. fromEquirectangularTexture( renderer, texture$1 ) {
  5858. const currentMinFilter = texture$1.minFilter;
  5859. const currentGenerateMipmaps = texture$1.generateMipmaps;
  5860. texture$1.generateMipmaps = true;
  5861. this.texture.type = texture$1.type;
  5862. this.texture.colorSpace = texture$1.colorSpace;
  5863. this.texture.generateMipmaps = texture$1.generateMipmaps;
  5864. this.texture.minFilter = texture$1.minFilter;
  5865. this.texture.magFilter = texture$1.magFilter;
  5866. const geometry = new BoxGeometry( 5, 5, 5 );
  5867. const uvNode = equirectUV( positionWorldDirection );
  5868. const material = new NodeMaterial();
  5869. material.colorNode = texture( texture$1, uvNode, 0 );
  5870. material.side = BackSide;
  5871. material.blending = NoBlending;
  5872. const mesh = new Mesh( geometry, material );
  5873. const scene = new Scene();
  5874. scene.add( mesh );
  5875. // Avoid blurred poles
  5876. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  5877. const camera = new CubeCamera( 1, 10, this );
  5878. const currentMRT = renderer.getMRT();
  5879. renderer.setMRT( null );
  5880. camera.update( renderer, scene );
  5881. renderer.setMRT( currentMRT );
  5882. texture$1.minFilter = currentMinFilter;
  5883. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  5884. mesh.geometry.dispose();
  5885. mesh.material.dispose();
  5886. return this;
  5887. }
  5888. }
  5889. const _cache$1 = new WeakMap();
  5890. class CubeMapNode extends TempNode {
  5891. static get type() {
  5892. return 'CubeMapNode';
  5893. }
  5894. constructor( envNode ) {
  5895. super( 'vec3' );
  5896. this.envNode = envNode;
  5897. this._cubeTexture = null;
  5898. this._cubeTextureNode = cubeTexture();
  5899. const defaultTexture = new CubeTexture();
  5900. defaultTexture.isRenderTargetTexture = true;
  5901. this._defaultTexture = defaultTexture;
  5902. this.updateBeforeType = NodeUpdateType.RENDER;
  5903. }
  5904. updateBefore( frame ) {
  5905. const { renderer, material } = frame;
  5906. const envNode = this.envNode;
  5907. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  5908. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  5909. if ( texture && texture.isTexture ) {
  5910. const mapping = texture.mapping;
  5911. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  5912. // check for converted cubemap map
  5913. if ( _cache$1.has( texture ) ) {
  5914. const cubeMap = _cache$1.get( texture );
  5915. mapTextureMapping( cubeMap, texture.mapping );
  5916. this._cubeTexture = cubeMap;
  5917. } else {
  5918. // create cube map from equirectangular map
  5919. const image = texture.image;
  5920. if ( isEquirectangularMapReady$1( image ) ) {
  5921. const renderTarget = new CubeRenderTarget( image.height );
  5922. renderTarget.fromEquirectangularTexture( renderer, texture );
  5923. mapTextureMapping( renderTarget.texture, texture.mapping );
  5924. this._cubeTexture = renderTarget.texture;
  5925. _cache$1.set( texture, renderTarget.texture );
  5926. texture.addEventListener( 'dispose', onTextureDispose );
  5927. } else {
  5928. // default cube texture as fallback when equirectangular texture is not yet loaded
  5929. this._cubeTexture = this._defaultTexture;
  5930. }
  5931. }
  5932. //
  5933. this._cubeTextureNode.value = this._cubeTexture;
  5934. } else {
  5935. // envNode already refers to a cube map
  5936. this._cubeTextureNode = this.envNode;
  5937. }
  5938. }
  5939. }
  5940. }
  5941. setup( builder ) {
  5942. this.updateBefore( builder );
  5943. return this._cubeTextureNode;
  5944. }
  5945. }
  5946. function isEquirectangularMapReady$1( image ) {
  5947. if ( image === null || image === undefined ) return false;
  5948. return image.height > 0;
  5949. }
  5950. function onTextureDispose( event ) {
  5951. const texture = event.target;
  5952. texture.removeEventListener( 'dispose', onTextureDispose );
  5953. const renderTarget = _cache$1.get( texture );
  5954. if ( renderTarget !== undefined ) {
  5955. _cache$1.delete( texture );
  5956. renderTarget.dispose();
  5957. }
  5958. }
  5959. function mapTextureMapping( texture, mapping ) {
  5960. if ( mapping === EquirectangularReflectionMapping ) {
  5961. texture.mapping = CubeReflectionMapping;
  5962. } else if ( mapping === EquirectangularRefractionMapping ) {
  5963. texture.mapping = CubeRefractionMapping;
  5964. }
  5965. }
  5966. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode );
  5967. class BasicEnvironmentNode extends LightingNode {
  5968. static get type() {
  5969. return 'BasicEnvironmentNode';
  5970. }
  5971. constructor( envNode = null ) {
  5972. super();
  5973. this.envNode = envNode;
  5974. }
  5975. setup( builder ) {
  5976. // environment property is used in the finish() method of BasicLightingModel
  5977. builder.context.environment = cubeMapNode( this.envNode );
  5978. }
  5979. }
  5980. class BasicLightMapNode extends LightingNode {
  5981. static get type() {
  5982. return 'BasicLightMapNode';
  5983. }
  5984. constructor( lightMapNode = null ) {
  5985. super();
  5986. this.lightMapNode = lightMapNode;
  5987. }
  5988. setup( builder ) {
  5989. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  5990. const RECIPROCAL_PI = float( 1 / Math.PI );
  5991. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  5992. }
  5993. }
  5994. class LightingModel {
  5995. start( /*input, stack, builder*/ ) { }
  5996. finish( /*input, stack, builder*/ ) { }
  5997. direct( /*input, stack, builder*/ ) { }
  5998. directRectArea( /*input, stack, builder*/ ) {}
  5999. indirect( /*input, stack, builder*/ ) { }
  6000. ambientOcclusion( /*input, stack, builder*/ ) { }
  6001. }
  6002. class BasicLightingModel extends LightingModel {
  6003. constructor() {
  6004. super();
  6005. }
  6006. indirect( context, stack, builder ) {
  6007. const ambientOcclusion = context.ambientOcclusion;
  6008. const reflectedLight = context.reflectedLight;
  6009. const irradianceLightMap = builder.context.irradianceLightMap;
  6010. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  6011. // accumulation (baked indirect lighting only)
  6012. if ( irradianceLightMap ) {
  6013. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  6014. } else {
  6015. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  6016. }
  6017. // modulation
  6018. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  6019. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  6020. }
  6021. finish( context, stack, builder ) {
  6022. const material = builder.material;
  6023. const outgoingLight = context.outgoingLight;
  6024. const envNode = builder.context.environment;
  6025. if ( envNode ) {
  6026. switch ( material.combine ) {
  6027. case MultiplyOperation:
  6028. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  6029. break;
  6030. case MixOperation:
  6031. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  6032. break;
  6033. case AddOperation:
  6034. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  6035. break;
  6036. default:
  6037. console.warn( 'THREE.BasicLightingModel: Unsupported .combine value:', material.combine );
  6038. break;
  6039. }
  6040. }
  6041. }
  6042. }
  6043. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  6044. class MeshBasicNodeMaterial extends NodeMaterial {
  6045. static get type() {
  6046. return 'MeshBasicNodeMaterial';
  6047. }
  6048. constructor( parameters ) {
  6049. super();
  6050. this.isMeshBasicNodeMaterial = true;
  6051. this.lights = true;
  6052. this.setDefaultValues( _defaultValues$9 );
  6053. this.setValues( parameters );
  6054. }
  6055. setupNormal() {
  6056. return normalView; // see #28839
  6057. }
  6058. setupEnvironment( builder ) {
  6059. const envNode = super.setupEnvironment( builder );
  6060. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  6061. }
  6062. setupLightMap( builder ) {
  6063. let node = null;
  6064. if ( builder.material.lightMap ) {
  6065. node = new BasicLightMapNode( materialLightMap );
  6066. }
  6067. return node;
  6068. }
  6069. setupOutgoingLight() {
  6070. return diffuseColor.rgb;
  6071. }
  6072. setupLightingModel() {
  6073. return new BasicLightingModel();
  6074. }
  6075. }
  6076. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  6077. // Original approximation by Christophe Schlick '94
  6078. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  6079. // Optimized variant (presented by Epic at SIGGRAPH '13)
  6080. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  6081. const fresnel = dotVH.mul( - 5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  6082. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  6083. } ); // validated
  6084. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  6085. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  6086. } ); // validated
  6087. const G_BlinnPhong_Implicit = () => float( 0.25 );
  6088. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  6089. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  6090. } );
  6091. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  6092. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  6093. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  6094. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  6095. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  6096. const G = G_BlinnPhong_Implicit();
  6097. const D = D_BlinnPhong( { dotNH } );
  6098. return F.mul( G ).mul( D );
  6099. } );
  6100. class PhongLightingModel extends BasicLightingModel {
  6101. constructor( specular = true ) {
  6102. super();
  6103. this.specular = specular;
  6104. }
  6105. direct( { lightDirection, lightColor, reflectedLight } ) {
  6106. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  6107. const irradiance = dotNL.mul( lightColor );
  6108. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  6109. if ( this.specular === true ) {
  6110. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  6111. }
  6112. }
  6113. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  6114. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  6115. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  6116. }
  6117. }
  6118. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  6119. class MeshLambertNodeMaterial extends NodeMaterial {
  6120. static get type() {
  6121. return 'MeshLambertNodeMaterial';
  6122. }
  6123. constructor( parameters ) {
  6124. super();
  6125. this.isMeshLambertNodeMaterial = true;
  6126. this.lights = true;
  6127. this.setDefaultValues( _defaultValues$8 );
  6128. this.setValues( parameters );
  6129. }
  6130. setupEnvironment( builder ) {
  6131. const envNode = super.setupEnvironment( builder );
  6132. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  6133. }
  6134. setupLightingModel( /*builder*/ ) {
  6135. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  6136. }
  6137. }
  6138. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  6139. class MeshPhongNodeMaterial extends NodeMaterial {
  6140. static get type() {
  6141. return 'MeshPhongNodeMaterial';
  6142. }
  6143. constructor( parameters ) {
  6144. super();
  6145. this.isMeshPhongNodeMaterial = true;
  6146. this.lights = true;
  6147. this.shininessNode = null;
  6148. this.specularNode = null;
  6149. this.setDefaultValues( _defaultValues$7 );
  6150. this.setValues( parameters );
  6151. }
  6152. setupEnvironment( builder ) {
  6153. const envNode = super.setupEnvironment( builder );
  6154. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  6155. }
  6156. setupLightingModel( /*builder*/ ) {
  6157. return new PhongLightingModel();
  6158. }
  6159. setupVariants() {
  6160. // SHININESS
  6161. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  6162. shininess.assign( shininessNode );
  6163. // SPECULAR COLOR
  6164. const specularNode = this.specularNode || materialSpecular;
  6165. specularColor.assign( specularNode );
  6166. }
  6167. copy( source ) {
  6168. this.shininessNode = source.shininessNode;
  6169. this.specularNode = source.specularNode;
  6170. return super.copy( source );
  6171. }
  6172. }
  6173. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  6174. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  6175. return float( 0 );
  6176. }
  6177. const dxy = normalView.dFdx().abs().max( normalView.dFdy().abs() );
  6178. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  6179. return geometryRoughness;
  6180. } );
  6181. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  6182. const { roughness } = inputs;
  6183. const geometryRoughness = getGeometryRoughness();
  6184. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  6185. roughnessFactor = roughnessFactor.add( geometryRoughness );
  6186. roughnessFactor = roughnessFactor.min( 1.0 );
  6187. return roughnessFactor;
  6188. } );
  6189. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  6190. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  6191. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  6192. const a2 = alpha.pow2();
  6193. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  6194. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  6195. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  6196. } ).setLayout( {
  6197. name: 'V_GGX_SmithCorrelated',
  6198. type: 'float',
  6199. inputs: [
  6200. { name: 'alpha', type: 'float' },
  6201. { name: 'dotNL', type: 'float' },
  6202. { name: 'dotNV', type: 'float' }
  6203. ]
  6204. } ); // validated
  6205. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  6206. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  6207. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  6208. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  6209. const v = div( 0.5, gv.add( gl ) );
  6210. return v.saturate();
  6211. } ).setLayout( {
  6212. name: 'V_GGX_SmithCorrelated_Anisotropic',
  6213. type: 'float',
  6214. inputs: [
  6215. { name: 'alphaT', type: 'float', qualifier: 'in' },
  6216. { name: 'alphaB', type: 'float', qualifier: 'in' },
  6217. { name: 'dotTV', type: 'float', qualifier: 'in' },
  6218. { name: 'dotBV', type: 'float', qualifier: 'in' },
  6219. { name: 'dotTL', type: 'float', qualifier: 'in' },
  6220. { name: 'dotBL', type: 'float', qualifier: 'in' },
  6221. { name: 'dotNV', type: 'float', qualifier: 'in' },
  6222. { name: 'dotNL', type: 'float', qualifier: 'in' }
  6223. ]
  6224. } );
  6225. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  6226. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  6227. // alpha is "roughness squared" in Disney’s reparameterization
  6228. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  6229. const a2 = alpha.pow2();
  6230. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  6231. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  6232. } ).setLayout( {
  6233. name: 'D_GGX',
  6234. type: 'float',
  6235. inputs: [
  6236. { name: 'alpha', type: 'float' },
  6237. { name: 'dotNH', type: 'float' }
  6238. ]
  6239. } ); // validated
  6240. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  6241. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  6242. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  6243. const a2 = alphaT.mul( alphaB );
  6244. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  6245. const v2 = v.dot( v );
  6246. const w2 = a2.div( v2 );
  6247. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  6248. } ).setLayout( {
  6249. name: 'D_GGX_Anisotropic',
  6250. type: 'float',
  6251. inputs: [
  6252. { name: 'alphaT', type: 'float', qualifier: 'in' },
  6253. { name: 'alphaB', type: 'float', qualifier: 'in' },
  6254. { name: 'dotNH', type: 'float', qualifier: 'in' },
  6255. { name: 'dotTH', type: 'float', qualifier: 'in' },
  6256. { name: 'dotBH', type: 'float', qualifier: 'in' }
  6257. ]
  6258. } );
  6259. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  6260. const BRDF_GGX = /*@__PURE__*/ Fn( ( inputs ) => {
  6261. const { lightDirection, f0, f90, roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } = inputs;
  6262. const normalView = inputs.normalView || transformedNormalView;
  6263. const alpha = roughness.pow2(); // UE4's roughness
  6264. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  6265. const dotNL = normalView.dot( lightDirection ).clamp();
  6266. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  6267. const dotNH = normalView.dot( halfDir ).clamp();
  6268. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  6269. let F = F_Schlick( { f0, f90, dotVH } );
  6270. let V, D;
  6271. if ( defined( USE_IRIDESCENCE ) ) {
  6272. F = iridescence.mix( F, f );
  6273. }
  6274. if ( defined( USE_ANISOTROPY ) ) {
  6275. const dotTL = anisotropyT.dot( lightDirection );
  6276. const dotTV = anisotropyT.dot( positionViewDirection );
  6277. const dotTH = anisotropyT.dot( halfDir );
  6278. const dotBL = anisotropyB.dot( lightDirection );
  6279. const dotBV = anisotropyB.dot( positionViewDirection );
  6280. const dotBH = anisotropyB.dot( halfDir );
  6281. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  6282. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  6283. } else {
  6284. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  6285. D = D_GGX( { alpha, dotNH } );
  6286. }
  6287. return F.mul( V ).mul( D );
  6288. } ); // validated
  6289. // Analytical approximation of the DFG LUT, one half of the
  6290. // split-sum approximation used in indirect specular lighting.
  6291. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  6292. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  6293. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  6294. const c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );
  6295. const c1 = vec4( 1, 0.0425, 1.04, - 0.04 );
  6296. const r = roughness.mul( c0 ).add( c1 );
  6297. const a004 = r.x.mul( r.x ).min( dotNV.mul( - 9.28 ).exp2() ).mul( r.x ).add( r.y );
  6298. const fab = vec2( - 1.04, 1.04 ).mul( a004 ).add( r.zw );
  6299. return fab;
  6300. } ).setLayout( {
  6301. name: 'DFGApprox',
  6302. type: 'vec2',
  6303. inputs: [
  6304. { name: 'roughness', type: 'float' },
  6305. { name: 'dotNV', type: 'vec3' }
  6306. ]
  6307. } );
  6308. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  6309. const { dotNV, specularColor, specularF90, roughness } = inputs;
  6310. const fab = DFGApprox( { dotNV, roughness } );
  6311. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  6312. } );
  6313. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  6314. const x = dotVH.oneMinus().saturate();
  6315. const x2 = x.mul( x );
  6316. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  6317. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  6318. } ).setLayout( {
  6319. name: 'Schlick_to_F0',
  6320. type: 'vec3',
  6321. inputs: [
  6322. { name: 'f', type: 'vec3' },
  6323. { name: 'f90', type: 'float' },
  6324. { name: 'dotVH', type: 'float' }
  6325. ]
  6326. } );
  6327. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  6328. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  6329. const alpha = roughness.pow2();
  6330. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  6331. const invAlpha = float( 1.0 ).div( alpha );
  6332. const cos2h = dotNH.pow2();
  6333. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  6334. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  6335. } ).setLayout( {
  6336. name: 'D_Charlie',
  6337. type: 'float',
  6338. inputs: [
  6339. { name: 'roughness', type: 'float' },
  6340. { name: 'dotNH', type: 'float' }
  6341. ]
  6342. } );
  6343. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  6344. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  6345. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  6346. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  6347. } ).setLayout( {
  6348. name: 'V_Neubelt',
  6349. type: 'float',
  6350. inputs: [
  6351. { name: 'dotNV', type: 'float' },
  6352. { name: 'dotNL', type: 'float' }
  6353. ]
  6354. } );
  6355. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  6356. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  6357. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  6358. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp();
  6359. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  6360. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  6361. const V = V_Neubelt( { dotNV, dotNL } );
  6362. return sheen.mul( D ).mul( V );
  6363. } );
  6364. // Rect Area Light
  6365. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  6366. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  6367. // code: https://github.com/selfshadow/ltc_code/
  6368. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  6369. const LUT_SIZE = 64.0;
  6370. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  6371. const LUT_BIAS = 0.5 / LUT_SIZE;
  6372. const dotNV = N.dot( V ).saturate();
  6373. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  6374. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  6375. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  6376. return uv;
  6377. } ).setLayout( {
  6378. name: 'LTC_Uv',
  6379. type: 'vec2',
  6380. inputs: [
  6381. { name: 'N', type: 'vec3' },
  6382. { name: 'V', type: 'vec3' },
  6383. { name: 'roughness', type: 'float' }
  6384. ]
  6385. } );
  6386. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  6387. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  6388. // An approximation of the form factor of a horizon-clipped rectangle.
  6389. const l = f.length();
  6390. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  6391. } ).setLayout( {
  6392. name: 'LTC_ClippedSphereFormFactor',
  6393. type: 'float',
  6394. inputs: [
  6395. { name: 'f', type: 'vec3' }
  6396. ]
  6397. } );
  6398. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  6399. const x = v1.dot( v2 );
  6400. const y = x.abs().toVar();
  6401. // rational polynomial approximation to theta / sin( theta ) / 2PI
  6402. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  6403. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  6404. const v = a.div( b );
  6405. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  6406. return v1.cross( v2 ).mul( theta_sintheta );
  6407. } ).setLayout( {
  6408. name: 'LTC_EdgeVectorFormFactor',
  6409. type: 'vec3',
  6410. inputs: [
  6411. { name: 'v1', type: 'vec3' },
  6412. { name: 'v2', type: 'vec3' }
  6413. ]
  6414. } );
  6415. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  6416. // bail if point is on back side of plane of light
  6417. // assumes ccw winding order of light vertices
  6418. const v1 = p1.sub( p0 ).toVar();
  6419. const v2 = p3.sub( p0 ).toVar();
  6420. const lightNormal = v1.cross( v2 );
  6421. const result = vec3().toVar();
  6422. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  6423. // construct orthonormal basis around N
  6424. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  6425. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  6426. // compute transform
  6427. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  6428. // transform rect
  6429. // & project rect onto sphere
  6430. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  6431. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  6432. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  6433. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  6434. // calculate vector form factor
  6435. const vectorFormFactor = vec3( 0 ).toVar();
  6436. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  6437. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  6438. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  6439. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  6440. // adjust for horizon clipping
  6441. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  6442. } );
  6443. return result;
  6444. } ).setLayout( {
  6445. name: 'LTC_Evaluate',
  6446. type: 'vec3',
  6447. inputs: [
  6448. { name: 'N', type: 'vec3' },
  6449. { name: 'V', type: 'vec3' },
  6450. { name: 'P', type: 'vec3' },
  6451. { name: 'mInv', type: 'mat3' },
  6452. { name: 'p0', type: 'vec3' },
  6453. { name: 'p1', type: 'vec3' },
  6454. { name: 'p2', type: 'vec3' },
  6455. { name: 'p3', type: 'vec3' }
  6456. ]
  6457. } );
  6458. // Mipped Bicubic Texture Filtering by N8
  6459. // https://www.shadertoy.com/view/Dl2SDW
  6460. const bC = 1.0 / 6.0;
  6461. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  6462. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  6463. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( - 3.0, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  6464. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  6465. const g0 = ( a ) => w0( a ).add( w1( a ) );
  6466. const g1 = ( a ) => w2( a ).add( w3( a ) );
  6467. // h0 and h1 are the two offset functions
  6468. const h0 = ( a ) => add( - 1.0, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  6469. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  6470. const bicubic = ( textureNode, texelSize, lod ) => {
  6471. const uv = textureNode.uvNode;
  6472. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  6473. const iuv = floor( uvScaled );
  6474. const fuv = fract( uvScaled );
  6475. const g0x = g0( fuv.x );
  6476. const g1x = g1( fuv.x );
  6477. const h0x = h0( fuv.x );
  6478. const h1x = h1( fuv.x );
  6479. const h0y = h0( fuv.y );
  6480. const h1y = h1( fuv.y );
  6481. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  6482. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  6483. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  6484. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  6485. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.uv( p0 ).level( lod ) ), g1x.mul( textureNode.uv( p1 ).level( lod ) ) ) );
  6486. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.uv( p2 ).level( lod ) ), g1x.mul( textureNode.uv( p3 ).level( lod ) ) ) );
  6487. return a.add( b );
  6488. };
  6489. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, lodNode = float( 3 ) ] ) => {
  6490. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  6491. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  6492. const fLodSizeInv = div( 1.0, fLodSize );
  6493. const cLodSizeInv = div( 1.0, cLodSize );
  6494. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  6495. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  6496. return fract( lodNode ).mix( fSample, cSample );
  6497. } );
  6498. //
  6499. // Transmission
  6500. //
  6501. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  6502. // Direction of refracted light.
  6503. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  6504. // Compute rotation-independant scaling of the model matrix.
  6505. const modelScale = vec3(
  6506. length( modelMatrix[ 0 ].xyz ),
  6507. length( modelMatrix[ 1 ].xyz ),
  6508. length( modelMatrix[ 2 ].xyz )
  6509. );
  6510. // The thickness is specified in local space.
  6511. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  6512. } ).setLayout( {
  6513. name: 'getVolumeTransmissionRay',
  6514. type: 'vec3',
  6515. inputs: [
  6516. { name: 'n', type: 'vec3' },
  6517. { name: 'v', type: 'vec3' },
  6518. { name: 'thickness', type: 'float' },
  6519. { name: 'ior', type: 'float' },
  6520. { name: 'modelMatrix', type: 'mat4' }
  6521. ]
  6522. } );
  6523. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  6524. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  6525. // an IOR of 1.5 results in the default amount of microfacet refraction.
  6526. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  6527. } ).setLayout( {
  6528. name: 'applyIorToRoughness',
  6529. type: 'float',
  6530. inputs: [
  6531. { name: 'roughness', type: 'float' },
  6532. { name: 'ior', type: 'float' }
  6533. ]
  6534. } );
  6535. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  6536. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  6537. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  6538. const vTexture = material.side == BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  6539. const transmissionSample = vTexture.uv( fragCoord );
  6540. //const transmissionSample = viewportMipTexture( fragCoord );
  6541. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  6542. return textureBicubic( transmissionSample, lod );
  6543. } );
  6544. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  6545. If( attenuationDistance.notEqual( 0 ), () => {
  6546. // Compute light attenuation using Beer's law.
  6547. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  6548. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  6549. return transmittance;
  6550. } );
  6551. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  6552. return vec3( 1.0 );
  6553. } ).setLayout( {
  6554. name: 'volumeAttenuation',
  6555. type: 'vec3',
  6556. inputs: [
  6557. { name: 'transmissionDistance', type: 'float' },
  6558. { name: 'attenuationColor', type: 'vec3' },
  6559. { name: 'attenuationDistance', type: 'float' }
  6560. ]
  6561. } );
  6562. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  6563. let transmittedLight, transmittance;
  6564. if ( dispersion ) {
  6565. transmittedLight = vec4().toVar();
  6566. transmittance = vec3().toVar();
  6567. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  6568. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  6569. Loop( { start: 0, end: 3 }, ( { i } ) => {
  6570. const ior = iors.element( i );
  6571. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  6572. const refractedRayExit = position.add( transmissionRay );
  6573. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  6574. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  6575. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  6576. refractionCoords.addAssign( 1.0 );
  6577. refractionCoords.divAssign( 2.0 );
  6578. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  6579. // Sample framebuffer to get pixel the refracted ray hits.
  6580. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  6581. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  6582. transmittedLight.a.addAssign( transmissionSample.a );
  6583. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  6584. } );
  6585. transmittedLight.a.divAssign( 3.0 );
  6586. } else {
  6587. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  6588. const refractedRayExit = position.add( transmissionRay );
  6589. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  6590. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  6591. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  6592. refractionCoords.addAssign( 1.0 );
  6593. refractionCoords.divAssign( 2.0 );
  6594. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  6595. // Sample framebuffer to get pixel the refracted ray hits.
  6596. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  6597. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  6598. }
  6599. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  6600. const dotNV = n.dot( v ).clamp();
  6601. // Get the specular component.
  6602. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  6603. dotNV,
  6604. specularColor,
  6605. specularF90,
  6606. roughness
  6607. } ) );
  6608. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  6609. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  6610. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  6611. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  6612. } );
  6613. //
  6614. // Iridescence
  6615. //
  6616. // XYZ to linear-sRGB color space
  6617. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  6618. 3.2404542, - 0.9692660, 0.0556434,
  6619. - 1.5371385, 1.8760108, - 0.2040259,
  6620. - 0.4985314, 0.0415560, 1.0572252
  6621. );
  6622. // Assume air interface for top
  6623. // Note: We don't handle the case fresnel0 == 1
  6624. const Fresnel0ToIor = ( fresnel0 ) => {
  6625. const sqrtF0 = fresnel0.sqrt();
  6626. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  6627. };
  6628. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  6629. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  6630. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  6631. };
  6632. // Fresnel equations for dielectric/dielectric interfaces.
  6633. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  6634. // Evaluation XYZ sensitivity curves in Fourier space
  6635. const evalSensitivity = ( OPD, shift ) => {
  6636. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  6637. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  6638. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  6639. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  6640. 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() );
  6641. 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() );
  6642. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  6643. const rgb = XYZ_TO_REC709.mul( xyz );
  6644. return rgb;
  6645. };
  6646. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  6647. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  6648. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  6649. // Evaluate the cosTheta on the base layer (Snell law)
  6650. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  6651. // Handle TIR:
  6652. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  6653. If( cosTheta2Sq.lessThan( 0 ), () => {
  6654. return vec3( 1.0 );
  6655. } );
  6656. const cosTheta2 = cosTheta2Sq.sqrt();
  6657. // First interface
  6658. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  6659. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  6660. //const R21 = R12;
  6661. const T121 = R12.oneMinus();
  6662. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  6663. const phi21 = float( Math.PI ).sub( phi12 );
  6664. // Second interface
  6665. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  6666. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  6667. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  6668. const phi23 = vec3(
  6669. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  6670. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  6671. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  6672. );
  6673. // Phase shift
  6674. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  6675. const phi = vec3( phi21 ).add( phi23 );
  6676. // Compound terms
  6677. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  6678. const r123 = R123.sqrt();
  6679. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  6680. // Reflectance term for m = 0 (DC term amplitude)
  6681. const C0 = R12.add( Rs );
  6682. const I = C0.toVar();
  6683. // Reflectance term for m > 0 (pairs of diracs)
  6684. const Cm = Rs.sub( T121 ).toVar();
  6685. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  6686. Cm.mulAssign( r123 );
  6687. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  6688. I.addAssign( Cm.mul( Sm ) );
  6689. } );
  6690. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  6691. return I.max( vec3( 0.0 ) );
  6692. } ).setLayout( {
  6693. name: 'evalIridescence',
  6694. type: 'vec3',
  6695. inputs: [
  6696. { name: 'outsideIOR', type: 'float' },
  6697. { name: 'eta2', type: 'float' },
  6698. { name: 'cosTheta1', type: 'float' },
  6699. { name: 'thinFilmThickness', type: 'float' },
  6700. { name: 'baseF0', type: 'vec3' }
  6701. ]
  6702. } );
  6703. //
  6704. // Sheen
  6705. //
  6706. // This is a curve-fit approxmation to the "Charlie sheen" BRDF integrated over the hemisphere from
  6707. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  6708. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  6709. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  6710. const dotNV = normal.dot( viewDir ).saturate();
  6711. const r2 = roughness.pow2();
  6712. const a = select(
  6713. roughness.lessThan( 0.25 ),
  6714. float( - 339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  6715. float( - 8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  6716. );
  6717. const b = select(
  6718. roughness.lessThan( 0.25 ),
  6719. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  6720. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  6721. );
  6722. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  6723. return DG.mul( 1.0 / Math.PI ).saturate();
  6724. } );
  6725. const clearcoatF0 = vec3( 0.04 );
  6726. const clearcoatF90 = float( 1 );
  6727. //
  6728. class PhysicalLightingModel extends LightingModel {
  6729. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  6730. super();
  6731. this.clearcoat = clearcoat;
  6732. this.sheen = sheen;
  6733. this.iridescence = iridescence;
  6734. this.anisotropy = anisotropy;
  6735. this.transmission = transmission;
  6736. this.dispersion = dispersion;
  6737. this.clearcoatRadiance = null;
  6738. this.clearcoatSpecularDirect = null;
  6739. this.clearcoatSpecularIndirect = null;
  6740. this.sheenSpecularDirect = null;
  6741. this.sheenSpecularIndirect = null;
  6742. this.iridescenceFresnel = null;
  6743. this.iridescenceF0 = null;
  6744. }
  6745. start( context ) {
  6746. if ( this.clearcoat === true ) {
  6747. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  6748. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  6749. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  6750. }
  6751. if ( this.sheen === true ) {
  6752. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  6753. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  6754. }
  6755. if ( this.iridescence === true ) {
  6756. const dotNVi = transformedNormalView.dot( positionViewDirection ).clamp();
  6757. this.iridescenceFresnel = evalIridescence( {
  6758. outsideIOR: float( 1.0 ),
  6759. eta2: iridescenceIOR,
  6760. cosTheta1: dotNVi,
  6761. thinFilmThickness: iridescenceThickness,
  6762. baseF0: specularColor
  6763. } );
  6764. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  6765. }
  6766. if ( this.transmission === true ) {
  6767. const position = positionWorld;
  6768. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  6769. const n = transformedNormalWorld;
  6770. context.backdrop = getIBLVolumeRefraction(
  6771. n,
  6772. v,
  6773. roughness,
  6774. diffuseColor,
  6775. specularColor,
  6776. specularF90, // specularF90
  6777. position, // positionWorld
  6778. modelWorldMatrix, // modelMatrix
  6779. cameraViewMatrix, // viewMatrix
  6780. cameraProjectionMatrix, // projMatrix
  6781. ior,
  6782. thickness,
  6783. attenuationColor,
  6784. attenuationDistance,
  6785. this.dispersion ? dispersion : null
  6786. );
  6787. context.backdropAlpha = transmission;
  6788. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  6789. }
  6790. }
  6791. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  6792. // Approximates multiscattering in order to preserve energy.
  6793. // http://www.jcgt.org/published/0008/01/03/
  6794. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  6795. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  6796. const fab = DFGApprox( { roughness, dotNV } );
  6797. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  6798. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  6799. const Ess = fab.x.add( fab.y );
  6800. const Ems = Ess.oneMinus();
  6801. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  6802. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  6803. singleScatter.addAssign( FssEss );
  6804. multiScatter.addAssign( Fms.mul( Ems ) );
  6805. }
  6806. direct( { lightDirection, lightColor, reflectedLight } ) {
  6807. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  6808. const irradiance = dotNL.mul( lightColor );
  6809. if ( this.sheen === true ) {
  6810. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  6811. }
  6812. if ( this.clearcoat === true ) {
  6813. const dotNLcc = transformedClearcoatNormalView.dot( lightDirection ).clamp();
  6814. const ccIrradiance = dotNLcc.mul( lightColor );
  6815. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: transformedClearcoatNormalView } ) ) );
  6816. }
  6817. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  6818. 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 } ) ) );
  6819. }
  6820. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 } ) {
  6821. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  6822. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  6823. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  6824. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  6825. const N = transformedNormalView;
  6826. const V = positionViewDirection;
  6827. const P = positionView.toVar();
  6828. const uv = LTC_Uv( { N, V, roughness } );
  6829. const t1 = ltc_1.uv( uv ).toVar();
  6830. const t2 = ltc_2.uv( uv ).toVar();
  6831. const mInv = mat3(
  6832. vec3( t1.x, 0, t1.y ),
  6833. vec3( 0, 1, 0 ),
  6834. vec3( t1.z, 0, t1.w )
  6835. ).toVar();
  6836. // LTC Fresnel Approximation by Stephen Hill
  6837. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  6838. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  6839. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  6840. 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 } ) ) );
  6841. }
  6842. indirect( context, stack, builder ) {
  6843. this.indirectDiffuse( context, stack, builder );
  6844. this.indirectSpecular( context, stack, builder );
  6845. this.ambientOcclusion( context, stack, builder );
  6846. }
  6847. indirectDiffuse( { irradiance, reflectedLight } ) {
  6848. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  6849. }
  6850. indirectSpecular( { radiance, iblIrradiance, reflectedLight } ) {
  6851. if ( this.sheen === true ) {
  6852. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  6853. sheen,
  6854. IBLSheenBRDF( {
  6855. normal: transformedNormalView,
  6856. viewDir: positionViewDirection,
  6857. roughness: sheenRoughness
  6858. } )
  6859. ) );
  6860. }
  6861. if ( this.clearcoat === true ) {
  6862. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  6863. const clearcoatEnv = EnvironmentBRDF( {
  6864. dotNV: dotNVcc,
  6865. specularColor: clearcoatF0,
  6866. specularF90: clearcoatF90,
  6867. roughness: clearcoatRoughness
  6868. } );
  6869. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  6870. }
  6871. // Both indirect specular and indirect diffuse light accumulate here
  6872. const singleScattering = vec3().toVar( 'singleScattering' );
  6873. const multiScattering = vec3().toVar( 'multiScattering' );
  6874. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  6875. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  6876. const totalScattering = singleScattering.add( multiScattering );
  6877. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  6878. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  6879. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  6880. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  6881. }
  6882. ambientOcclusion( { ambientOcclusion, reflectedLight } ) {
  6883. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  6884. const aoNV = dotNV.add( ambientOcclusion );
  6885. const aoExp = roughness.mul( - 16.0 ).oneMinus().negate().exp2();
  6886. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  6887. if ( this.clearcoat === true ) {
  6888. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  6889. }
  6890. if ( this.sheen === true ) {
  6891. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  6892. }
  6893. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  6894. reflectedLight.indirectSpecular.mulAssign( aoNode );
  6895. }
  6896. finish( context ) {
  6897. const { outgoingLight } = context;
  6898. if ( this.clearcoat === true ) {
  6899. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  6900. const Fcc = F_Schlick( {
  6901. dotVH: dotNVcc,
  6902. f0: clearcoatF0,
  6903. f90: clearcoatF90
  6904. } );
  6905. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  6906. outgoingLight.assign( clearcoatLight );
  6907. }
  6908. if ( this.sheen === true ) {
  6909. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  6910. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  6911. outgoingLight.assign( sheenLight );
  6912. }
  6913. }
  6914. }
  6915. // These defines must match with PMREMGenerator
  6916. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  6917. const cubeUV_m0 = /*@__PURE__*/ float( - 2.0 );
  6918. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  6919. const cubeUV_m1 = /*@__PURE__*/ float( - 1.0 );
  6920. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  6921. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  6922. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  6923. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  6924. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  6925. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  6926. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  6927. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  6928. // These shader functions convert between the UV coordinates of a single face of
  6929. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  6930. // sampling a textureCube (not generally normalized ).
  6931. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  6932. const absDirection = vec3( abs( direction ) ).toVar();
  6933. const face = float( - 1.0 ).toVar();
  6934. If( absDirection.x.greaterThan( absDirection.z ), () => {
  6935. If( absDirection.x.greaterThan( absDirection.y ), () => {
  6936. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  6937. } ).Else( () => {
  6938. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  6939. } );
  6940. } ).Else( () => {
  6941. If( absDirection.z.greaterThan( absDirection.y ), () => {
  6942. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  6943. } ).Else( () => {
  6944. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  6945. } );
  6946. } );
  6947. return face;
  6948. } ).setLayout( {
  6949. name: 'getFace',
  6950. type: 'float',
  6951. inputs: [
  6952. { name: 'direction', type: 'vec3' }
  6953. ]
  6954. } );
  6955. // RH coordinate system; PMREM face-indexing convention
  6956. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  6957. const uv = vec2().toVar();
  6958. If( face.equal( 0.0 ), () => {
  6959. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  6960. } ).ElseIf( face.equal( 1.0 ), () => {
  6961. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  6962. } ).ElseIf( face.equal( 2.0 ), () => {
  6963. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  6964. } ).ElseIf( face.equal( 3.0 ), () => {
  6965. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  6966. } ).ElseIf( face.equal( 4.0 ), () => {
  6967. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  6968. } ).Else( () => {
  6969. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  6970. } );
  6971. return mul( 0.5, uv.add( 1.0 ) );
  6972. } ).setLayout( {
  6973. name: 'getUV',
  6974. type: 'vec2',
  6975. inputs: [
  6976. { name: 'direction', type: 'vec3' },
  6977. { name: 'face', type: 'float' }
  6978. ]
  6979. } );
  6980. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  6981. const mip = float( 0.0 ).toVar();
  6982. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  6983. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  6984. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  6985. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  6986. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  6987. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  6988. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  6989. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  6990. } ).Else( () => {
  6991. mip.assign( float( - 2.0 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  6992. } );
  6993. return mip;
  6994. } ).setLayout( {
  6995. name: 'roughnessToMip',
  6996. type: 'float',
  6997. inputs: [
  6998. { name: 'roughness', type: 'float' }
  6999. ]
  7000. } );
  7001. // RH coordinate system; PMREM face-indexing convention
  7002. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  7003. const uv = uv_immutable.toVar();
  7004. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  7005. const direction = vec3( uv, 1.0 ).toVar();
  7006. If( face.equal( 0.0 ), () => {
  7007. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  7008. } ).ElseIf( face.equal( 1.0 ), () => {
  7009. direction.assign( direction.xzy );
  7010. direction.xz.mulAssign( - 1.0 ); // ( -u, 1, -v ) pos y
  7011. } ).ElseIf( face.equal( 2.0 ), () => {
  7012. direction.x.mulAssign( - 1.0 ); // ( -u, v, 1 ) pos z
  7013. } ).ElseIf( face.equal( 3.0 ), () => {
  7014. direction.assign( direction.zyx );
  7015. direction.xz.mulAssign( - 1.0 ); // ( -1, v, -u ) neg x
  7016. } ).ElseIf( face.equal( 4.0 ), () => {
  7017. direction.assign( direction.xzy );
  7018. direction.xy.mulAssign( - 1.0 ); // ( -u, -1, v ) neg y
  7019. } ).ElseIf( face.equal( 5.0 ), () => {
  7020. direction.z.mulAssign( - 1.0 ); // ( u, v, -1 ) neg zS
  7021. } );
  7022. return direction;
  7023. } ).setLayout( {
  7024. name: 'getDirection',
  7025. type: 'vec3',
  7026. inputs: [
  7027. { name: 'uv', type: 'vec2' },
  7028. { name: 'face', type: 'float' }
  7029. ]
  7030. } );
  7031. //
  7032. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  7033. const roughness = float( roughness_immutable );
  7034. const sampleDir = vec3( sampleDir_immutable );
  7035. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  7036. const mipF = fract( mip );
  7037. const mipInt = floor( mip );
  7038. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  7039. If( mipF.notEqual( 0.0 ), () => {
  7040. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  7041. color0.assign( mix( color0, color1, mipF ) );
  7042. } );
  7043. return color0;
  7044. } );
  7045. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  7046. const mipInt = float( mipInt_immutable ).toVar();
  7047. const direction = vec3( direction_immutable );
  7048. const face = float( getFace( direction ) ).toVar();
  7049. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  7050. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  7051. const faceSize = float( exp2( mipInt ) ).toVar();
  7052. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  7053. If( face.greaterThan( 2.0 ), () => {
  7054. uv.y.addAssign( faceSize );
  7055. face.subAssign( 3.0 );
  7056. } );
  7057. uv.x.addAssign( face.mul( faceSize ) );
  7058. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  7059. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  7060. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  7061. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  7062. return envMap.uv( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  7063. } );
  7064. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  7065. const cosTheta = cos( theta );
  7066. // Rodrigues' axis-angle rotation
  7067. const sampleDirection = outputDirection.mul( cosTheta )
  7068. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  7069. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  7070. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  7071. } );
  7072. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  7073. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  7074. If( all( axis.equals( vec3( 0.0 ) ) ), () => {
  7075. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  7076. } );
  7077. axis.assign( normalize( axis ) );
  7078. const gl_FragColor = vec3().toVar();
  7079. 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 } ) ) );
  7080. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  7081. If( i.greaterThanEqual( samples ), () => {
  7082. Break();
  7083. } );
  7084. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  7085. 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 } ) ) );
  7086. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  7087. } );
  7088. return vec4( gl_FragColor, 1 );
  7089. } );
  7090. let _generator = null;
  7091. const _cache = new WeakMap();
  7092. function _generateCubeUVSize( imageHeight ) {
  7093. const maxMip = Math.log2( imageHeight ) - 2;
  7094. const texelHeight = 1.0 / imageHeight;
  7095. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  7096. return { texelWidth, texelHeight, maxMip };
  7097. }
  7098. function _getPMREMFromTexture( texture ) {
  7099. let cacheTexture = _cache.get( texture );
  7100. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : - 1;
  7101. if ( pmremVersion !== texture.pmremVersion ) {
  7102. const image = texture.image;
  7103. if ( texture.isCubeTexture ) {
  7104. if ( isCubeMapReady( image ) ) {
  7105. cacheTexture = _generator.fromCubemap( texture, cacheTexture );
  7106. } else {
  7107. return null;
  7108. }
  7109. } else {
  7110. if ( isEquirectangularMapReady( image ) ) {
  7111. cacheTexture = _generator.fromEquirectangular( texture, cacheTexture );
  7112. } else {
  7113. return null;
  7114. }
  7115. }
  7116. cacheTexture.pmremVersion = texture.pmremVersion;
  7117. _cache.set( texture, cacheTexture );
  7118. }
  7119. return cacheTexture.texture;
  7120. }
  7121. class PMREMNode extends TempNode {
  7122. static get type() {
  7123. return 'PMREMNode';
  7124. }
  7125. constructor( value, uvNode = null, levelNode = null ) {
  7126. super( 'vec3' );
  7127. this._value = value;
  7128. this._pmrem = null;
  7129. this.uvNode = uvNode;
  7130. this.levelNode = levelNode;
  7131. this._generator = null;
  7132. const defaultTexture = new Texture();
  7133. defaultTexture.isRenderTargetTexture = true;
  7134. this._texture = texture( defaultTexture );
  7135. this._width = uniform( 0 );
  7136. this._height = uniform( 0 );
  7137. this._maxMip = uniform( 0 );
  7138. this.updateBeforeType = NodeUpdateType.RENDER;
  7139. }
  7140. set value( value ) {
  7141. this._value = value;
  7142. this._pmrem = null;
  7143. }
  7144. get value() {
  7145. return this._value;
  7146. }
  7147. updateFromTexture( texture ) {
  7148. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  7149. this._texture.value = texture;
  7150. this._width.value = cubeUVSize.texelWidth;
  7151. this._height.value = cubeUVSize.texelHeight;
  7152. this._maxMip.value = cubeUVSize.maxMip;
  7153. }
  7154. updateBefore() {
  7155. let pmrem = this._pmrem;
  7156. const pmremVersion = pmrem ? pmrem.pmremVersion : - 1;
  7157. const texture = this._value;
  7158. if ( pmremVersion !== texture.pmremVersion ) {
  7159. if ( texture.isPMREMTexture === true ) {
  7160. pmrem = texture;
  7161. } else {
  7162. pmrem = _getPMREMFromTexture( texture );
  7163. }
  7164. if ( pmrem !== null ) {
  7165. this._pmrem = pmrem;
  7166. this.updateFromTexture( pmrem );
  7167. }
  7168. }
  7169. }
  7170. setup( builder ) {
  7171. if ( _generator === null ) {
  7172. _generator = builder.createPMREMGenerator();
  7173. }
  7174. //
  7175. this.updateBefore( builder );
  7176. //
  7177. let uvNode = this.uvNode;
  7178. if ( uvNode === null && builder.context.getUV ) {
  7179. uvNode = builder.context.getUV( this );
  7180. }
  7181. //
  7182. const texture = this.value;
  7183. if ( builder.renderer.coordinateSystem === WebGLCoordinateSystem && texture.isPMREMTexture !== true && texture.isRenderTargetTexture === true ) {
  7184. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  7185. }
  7186. //
  7187. let levelNode = this.levelNode;
  7188. if ( levelNode === null && builder.context.getTextureLevel ) {
  7189. levelNode = builder.context.getTextureLevel( this );
  7190. }
  7191. //
  7192. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  7193. }
  7194. }
  7195. function isCubeMapReady( image ) {
  7196. if ( image === null || image === undefined ) return false;
  7197. let count = 0;
  7198. const length = 6;
  7199. for ( let i = 0; i < length; i ++ ) {
  7200. if ( image[ i ] !== undefined ) count ++;
  7201. }
  7202. return count === length;
  7203. }
  7204. function isEquirectangularMapReady( image ) {
  7205. if ( image === null || image === undefined ) return false;
  7206. return image.height > 0;
  7207. }
  7208. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode );
  7209. const _envNodeCache = new WeakMap();
  7210. class EnvironmentNode extends LightingNode {
  7211. static get type() {
  7212. return 'EnvironmentNode';
  7213. }
  7214. constructor( envNode = null ) {
  7215. super();
  7216. this.envNode = envNode;
  7217. }
  7218. setup( builder ) {
  7219. const { material } = builder;
  7220. let envNode = this.envNode;
  7221. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  7222. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  7223. let cacheEnvNode = _envNodeCache.get( value );
  7224. if ( cacheEnvNode === undefined ) {
  7225. cacheEnvNode = pmremTexture( value );
  7226. _envNodeCache.set( value, cacheEnvNode );
  7227. }
  7228. envNode = cacheEnvNode;
  7229. }
  7230. //
  7231. const envMap = material.envMap;
  7232. const intensity = envMap ? reference( 'envMapIntensity', 'float', builder.material ) : reference( 'environmentIntensity', 'float', builder.scene ); // @TODO: Add materialEnvIntensity in MaterialNode
  7233. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  7234. const radianceNormalView = useAnisotropy ? transformedBentNormalView : transformedNormalView;
  7235. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( intensity );
  7236. const irradiance = envNode.context( createIrradianceContext( transformedNormalWorld ) ).mul( Math.PI ).mul( intensity );
  7237. const isolateRadiance = cache( radiance );
  7238. const isolateIrradiance = cache( irradiance );
  7239. //
  7240. builder.context.radiance.addAssign( isolateRadiance );
  7241. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  7242. //
  7243. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  7244. if ( clearcoatRadiance ) {
  7245. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, transformedClearcoatNormalView ) ).mul( intensity );
  7246. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  7247. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  7248. }
  7249. }
  7250. }
  7251. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  7252. let reflectVec = null;
  7253. return {
  7254. getUV: () => {
  7255. if ( reflectVec === null ) {
  7256. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  7257. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  7258. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  7259. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  7260. }
  7261. return reflectVec;
  7262. },
  7263. getTextureLevel: () => {
  7264. return roughnessNode;
  7265. }
  7266. };
  7267. };
  7268. const createIrradianceContext = ( normalWorldNode ) => {
  7269. return {
  7270. getUV: () => {
  7271. return normalWorldNode;
  7272. },
  7273. getTextureLevel: () => {
  7274. return float( 1.0 );
  7275. }
  7276. };
  7277. };
  7278. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  7279. class MeshStandardNodeMaterial extends NodeMaterial {
  7280. static get type() {
  7281. return 'MeshStandardNodeMaterial';
  7282. }
  7283. constructor( parameters ) {
  7284. super();
  7285. this.isMeshStandardNodeMaterial = true;
  7286. this.lights = true;
  7287. this.emissiveNode = null;
  7288. this.metalnessNode = null;
  7289. this.roughnessNode = null;
  7290. this.setDefaultValues( _defaultValues$6 );
  7291. this.setValues( parameters );
  7292. }
  7293. setupEnvironment( builder ) {
  7294. let envNode = super.setupEnvironment( builder );
  7295. if ( envNode === null && builder.environmentNode ) {
  7296. envNode = builder.environmentNode;
  7297. }
  7298. return envNode ? new EnvironmentNode( envNode ) : null;
  7299. }
  7300. setupLightingModel( /*builder*/ ) {
  7301. return new PhysicalLightingModel();
  7302. }
  7303. setupSpecular() {
  7304. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  7305. specularColor.assign( specularColorNode );
  7306. specularF90.assign( 1.0 );
  7307. }
  7308. setupVariants() {
  7309. // METALNESS
  7310. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  7311. metalness.assign( metalnessNode );
  7312. // ROUGHNESS
  7313. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  7314. roughnessNode = getRoughness( { roughness: roughnessNode } );
  7315. roughness.assign( roughnessNode );
  7316. // SPECULAR COLOR
  7317. this.setupSpecular();
  7318. // DIFFUSE COLOR
  7319. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  7320. }
  7321. copy( source ) {
  7322. this.emissiveNode = source.emissiveNode;
  7323. this.metalnessNode = source.metalnessNode;
  7324. this.roughnessNode = source.roughnessNode;
  7325. return super.copy( source );
  7326. }
  7327. }
  7328. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  7329. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  7330. static get type() {
  7331. return 'MeshPhysicalNodeMaterial';
  7332. }
  7333. constructor( parameters ) {
  7334. super();
  7335. this.isMeshPhysicalNodeMaterial = true;
  7336. this.clearcoatNode = null;
  7337. this.clearcoatRoughnessNode = null;
  7338. this.clearcoatNormalNode = null;
  7339. this.sheenNode = null;
  7340. this.sheenRoughnessNode = null;
  7341. this.iridescenceNode = null;
  7342. this.iridescenceIORNode = null;
  7343. this.iridescenceThicknessNode = null;
  7344. this.specularIntensityNode = null;
  7345. this.specularColorNode = null;
  7346. this.iorNode = null;
  7347. this.transmissionNode = null;
  7348. this.thicknessNode = null;
  7349. this.attenuationDistanceNode = null;
  7350. this.attenuationColorNode = null;
  7351. this.dispersionNode = null;
  7352. this.anisotropyNode = null;
  7353. this.setDefaultValues( _defaultValues$5 );
  7354. this.setValues( parameters );
  7355. }
  7356. get useClearcoat() {
  7357. return this.clearcoat > 0 || this.clearcoatNode !== null;
  7358. }
  7359. get useIridescence() {
  7360. return this.iridescence > 0 || this.iridescenceNode !== null;
  7361. }
  7362. get useSheen() {
  7363. return this.sheen > 0 || this.sheenNode !== null;
  7364. }
  7365. get useAnisotropy() {
  7366. return this.anisotropy > 0 || this.anisotropyNode !== null;
  7367. }
  7368. get useTransmission() {
  7369. return this.transmission > 0 || this.transmissionNode !== null;
  7370. }
  7371. get useDispersion() {
  7372. return this.dispersion > 0 || this.dispersionNode !== null;
  7373. }
  7374. setupSpecular() {
  7375. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  7376. ior.assign( iorNode );
  7377. 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 ) );
  7378. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  7379. }
  7380. setupLightingModel( /*builder*/ ) {
  7381. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  7382. }
  7383. setupVariants( builder ) {
  7384. super.setupVariants( builder );
  7385. // CLEARCOAT
  7386. if ( this.useClearcoat ) {
  7387. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  7388. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  7389. clearcoat.assign( clearcoatNode );
  7390. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  7391. }
  7392. // SHEEN
  7393. if ( this.useSheen ) {
  7394. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  7395. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  7396. sheen.assign( sheenNode );
  7397. sheenRoughness.assign( sheenRoughnessNode );
  7398. }
  7399. // IRIDESCENCE
  7400. if ( this.useIridescence ) {
  7401. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  7402. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  7403. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  7404. iridescence.assign( iridescenceNode );
  7405. iridescenceIOR.assign( iridescenceIORNode );
  7406. iridescenceThickness.assign( iridescenceThicknessNode );
  7407. }
  7408. // ANISOTROPY
  7409. if ( this.useAnisotropy ) {
  7410. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  7411. anisotropy.assign( anisotropyV.length() );
  7412. If( anisotropy.equal( 0.0 ), () => {
  7413. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  7414. } ).Else( () => {
  7415. anisotropyV.divAssign( vec2( anisotropy ) );
  7416. anisotropy.assign( anisotropy.saturate() );
  7417. } );
  7418. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  7419. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  7420. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  7421. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  7422. }
  7423. // TRANSMISSION
  7424. if ( this.useTransmission ) {
  7425. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  7426. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  7427. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  7428. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  7429. transmission.assign( transmissionNode );
  7430. thickness.assign( thicknessNode );
  7431. attenuationDistance.assign( attenuationDistanceNode );
  7432. attenuationColor.assign( attenuationColorNode );
  7433. if ( this.useDispersion ) {
  7434. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  7435. dispersion.assign( dispersionNode );
  7436. }
  7437. }
  7438. }
  7439. setupClearcoatNormal() {
  7440. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  7441. }
  7442. setup( builder ) {
  7443. builder.context.setupClearcoatNormal = () => this.setupClearcoatNormal( builder );
  7444. super.setup( builder );
  7445. }
  7446. copy( source ) {
  7447. this.clearcoatNode = source.clearcoatNode;
  7448. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  7449. this.clearcoatNormalNode = source.clearcoatNormalNode;
  7450. this.sheenNode = source.sheenNode;
  7451. this.sheenRoughnessNode = source.sheenRoughnessNode;
  7452. this.iridescenceNode = source.iridescenceNode;
  7453. this.iridescenceIORNode = source.iridescenceIORNode;
  7454. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  7455. this.specularIntensityNode = source.specularIntensityNode;
  7456. this.specularColorNode = source.specularColorNode;
  7457. this.transmissionNode = source.transmissionNode;
  7458. this.thicknessNode = source.thicknessNode;
  7459. this.attenuationDistanceNode = source.attenuationDistanceNode;
  7460. this.attenuationColorNode = source.attenuationColorNode;
  7461. this.dispersionNode = source.dispersionNode;
  7462. this.anisotropyNode = source.anisotropyNode;
  7463. return super.copy( source );
  7464. }
  7465. }
  7466. class SSSLightingModel extends PhysicalLightingModel {
  7467. constructor( useClearcoat, useSheen, useIridescence, useSSS ) {
  7468. super( useClearcoat, useSheen, useIridescence );
  7469. this.useSSS = useSSS;
  7470. }
  7471. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  7472. if ( this.useSSS === true ) {
  7473. const material = builder.material;
  7474. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  7475. const scatteringHalf = lightDirection.add( transformedNormalView.mul( thicknessDistortionNode ) ).normalize();
  7476. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  7477. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  7478. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  7479. }
  7480. super.direct( { lightDirection, lightColor, reflectedLight }, stack, builder );
  7481. }
  7482. }
  7483. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  7484. static get type() {
  7485. return 'MeshSSSNodeMaterial';
  7486. }
  7487. constructor( parameters ) {
  7488. super( parameters );
  7489. this.thicknessColorNode = null;
  7490. this.thicknessDistortionNode = float( 0.1 );
  7491. this.thicknessAmbientNode = float( 0.0 );
  7492. this.thicknessAttenuationNode = float( .1 );
  7493. this.thicknessPowerNode = float( 2.0 );
  7494. this.thicknessScaleNode = float( 10.0 );
  7495. }
  7496. get useSSS() {
  7497. return this.thicknessColorNode !== null;
  7498. }
  7499. setupLightingModel( /*builder*/ ) {
  7500. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useSSS );
  7501. }
  7502. copy( source ) {
  7503. this.thicknessColorNode = source.thicknessColorNode;
  7504. this.thicknessDistortionNode = source.thicknessDistortionNode;
  7505. this.thicknessAmbientNode = source.thicknessAmbientNode;
  7506. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  7507. this.thicknessPowerNode = source.thicknessPowerNode;
  7508. this.thicknessScaleNode = source.thicknessScaleNode;
  7509. return super.copy( source );
  7510. }
  7511. }
  7512. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  7513. // dotNL will be from -1.0 to 1.0
  7514. const dotNL = normal.dot( lightDirection );
  7515. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  7516. if ( builder.material.gradientMap ) {
  7517. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  7518. return vec3( gradientMap.r );
  7519. } else {
  7520. const fw = coord.fwidth().mul( 0.5 );
  7521. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  7522. }
  7523. } );
  7524. class ToonLightingModel extends LightingModel {
  7525. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  7526. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  7527. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  7528. }
  7529. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  7530. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  7531. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  7532. }
  7533. }
  7534. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  7535. class MeshToonNodeMaterial extends NodeMaterial {
  7536. static get type() {
  7537. return 'MeshToonNodeMaterial';
  7538. }
  7539. constructor( parameters ) {
  7540. super();
  7541. this.isMeshToonNodeMaterial = true;
  7542. this.lights = true;
  7543. this.setDefaultValues( _defaultValues$4 );
  7544. this.setValues( parameters );
  7545. }
  7546. setupLightingModel( /*builder*/ ) {
  7547. return new ToonLightingModel();
  7548. }
  7549. }
  7550. class MatcapUVNode extends TempNode {
  7551. static get type() {
  7552. return 'MatcapUVNode';
  7553. }
  7554. constructor() {
  7555. super( 'vec2' );
  7556. }
  7557. setup() {
  7558. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  7559. const y = positionViewDirection.cross( x );
  7560. return vec2( x.dot( transformedNormalView ), y.dot( transformedNormalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  7561. }
  7562. }
  7563. const matcapUV = /*@__PURE__*/ nodeImmutable( MatcapUVNode );
  7564. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  7565. class MeshMatcapNodeMaterial extends NodeMaterial {
  7566. static get type() {
  7567. return 'MeshMatcapNodeMaterial';
  7568. }
  7569. constructor( parameters ) {
  7570. super();
  7571. this.lights = false;
  7572. this.isMeshMatcapNodeMaterial = true;
  7573. this.setDefaultValues( _defaultValues$3 );
  7574. this.setValues( parameters );
  7575. }
  7576. setupVariants( builder ) {
  7577. const uv = matcapUV;
  7578. let matcapColor;
  7579. if ( builder.material.matcap ) {
  7580. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  7581. } else {
  7582. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  7583. }
  7584. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  7585. }
  7586. }
  7587. const _defaultValues$2 = /*@__PURE__*/ new PointsMaterial();
  7588. class PointsNodeMaterial extends NodeMaterial {
  7589. static get type() {
  7590. return 'PointsNodeMaterial';
  7591. }
  7592. constructor( parameters ) {
  7593. super();
  7594. this.isPointsNodeMaterial = true;
  7595. this.lights = false;
  7596. this.transparent = true;
  7597. this.sizeNode = null;
  7598. this.setDefaultValues( _defaultValues$2 );
  7599. this.setValues( parameters );
  7600. }
  7601. copy( source ) {
  7602. this.sizeNode = source.sizeNode;
  7603. return super.copy( source );
  7604. }
  7605. }
  7606. class RotateNode extends TempNode {
  7607. static get type() {
  7608. return 'RotateNode';
  7609. }
  7610. constructor( positionNode, rotationNode ) {
  7611. super();
  7612. this.positionNode = positionNode;
  7613. this.rotationNode = rotationNode;
  7614. }
  7615. getNodeType( builder ) {
  7616. return this.positionNode.getNodeType( builder );
  7617. }
  7618. setup( builder ) {
  7619. const { rotationNode, positionNode } = this;
  7620. const nodeType = this.getNodeType( builder );
  7621. if ( nodeType === 'vec2' ) {
  7622. const cosAngle = rotationNode.cos();
  7623. const sinAngle = rotationNode.sin();
  7624. const rotationMatrix = mat2(
  7625. cosAngle, sinAngle,
  7626. sinAngle.negate(), cosAngle
  7627. );
  7628. return rotationMatrix.mul( positionNode );
  7629. } else {
  7630. const rotation = rotationNode;
  7631. 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 ) );
  7632. 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 ) );
  7633. 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 ) );
  7634. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  7635. }
  7636. }
  7637. }
  7638. const rotate = /*@__PURE__*/ nodeProxy( RotateNode );
  7639. const _defaultValues$1 = /*@__PURE__*/ new SpriteMaterial();
  7640. class SpriteNodeMaterial extends NodeMaterial {
  7641. static get type() {
  7642. return 'SpriteNodeMaterial';
  7643. }
  7644. constructor( parameters ) {
  7645. super();
  7646. this.isSpriteNodeMaterial = true;
  7647. this.lights = false;
  7648. this._useSizeAttenuation = true;
  7649. this.positionNode = null;
  7650. this.rotationNode = null;
  7651. this.scaleNode = null;
  7652. this.setDefaultValues( _defaultValues$1 );
  7653. this.setValues( parameters );
  7654. }
  7655. setupPosition( { object, camera, context } ) {
  7656. const sizeAttenuation = this.sizeAttenuation;
  7657. // < VERTEX STAGE >
  7658. const { positionNode, rotationNode, scaleNode } = this;
  7659. const vertex = positionLocal;
  7660. let mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  7661. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  7662. if ( scaleNode !== null ) {
  7663. scale = scale.mul( scaleNode );
  7664. }
  7665. if ( ! sizeAttenuation ) {
  7666. if ( camera.isPerspectiveCamera ) {
  7667. scale = scale.mul( mvPosition.z.negate() );
  7668. } else {
  7669. const orthoScale = float( 2.0 ).div( cameraProjectionMatrix.element( 1 ).element( 1 ) );
  7670. scale = scale.mul( orthoScale.mul( 2 ) );
  7671. }
  7672. }
  7673. let alignedPosition = vertex.xy;
  7674. if ( object.center && object.center.isVector2 === true ) {
  7675. const center = reference$1( 'center', 'vec2' );
  7676. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  7677. }
  7678. alignedPosition = alignedPosition.mul( scale );
  7679. const rotation = float( rotationNode || materialRotation );
  7680. const rotatedPosition = rotate( alignedPosition, rotation );
  7681. mvPosition = vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  7682. const modelViewProjection = cameraProjectionMatrix.mul( mvPosition );
  7683. context.vertex = vertex;
  7684. return modelViewProjection;
  7685. }
  7686. copy( source ) {
  7687. this.positionNode = source.positionNode;
  7688. this.rotationNode = source.rotationNode;
  7689. this.scaleNode = source.scaleNode;
  7690. return super.copy( source );
  7691. }
  7692. get sizeAttenuation() {
  7693. return this._useSizeAttenuation;
  7694. }
  7695. set sizeAttenuation( value ) {
  7696. if ( this._useSizeAttenuation !== value ) {
  7697. this._useSizeAttenuation = value;
  7698. this.needsUpdate = true;
  7699. }
  7700. }
  7701. }
  7702. class ShadowMaskModel extends LightingModel {
  7703. constructor() {
  7704. super();
  7705. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  7706. }
  7707. direct( { shadowMask } ) {
  7708. this.shadowNode.mulAssign( shadowMask );
  7709. }
  7710. finish( context ) {
  7711. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  7712. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  7713. }
  7714. }
  7715. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  7716. class ShadowNodeMaterial extends NodeMaterial {
  7717. static get type() {
  7718. return 'ShadowNodeMaterial';
  7719. }
  7720. constructor( parameters ) {
  7721. super();
  7722. this.isShadowNodeMaterial = true;
  7723. this.lights = true;
  7724. this.setDefaultValues( _defaultValues );
  7725. this.setValues( parameters );
  7726. }
  7727. setupLightingModel( /*builder*/ ) {
  7728. return new ShadowMaskModel();
  7729. }
  7730. }
  7731. const normal = Fn( ( { texture, uv } ) => {
  7732. const epsilon = 0.0001;
  7733. const ret = vec3().toVar();
  7734. If( uv.x.lessThan( epsilon ), () => {
  7735. ret.assign( vec3( 1, 0, 0 ) );
  7736. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  7737. ret.assign( vec3( 0, 1, 0 ) );
  7738. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  7739. ret.assign( vec3( 0, 0, 1 ) );
  7740. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  7741. ret.assign( vec3( - 1, 0, 0 ) );
  7742. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  7743. ret.assign( vec3( 0, - 1, 0 ) );
  7744. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  7745. ret.assign( vec3( 0, 0, - 1 ) );
  7746. } ).Else( () => {
  7747. const step = 0.01;
  7748. 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 );
  7749. 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 );
  7750. 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 );
  7751. ret.assign( vec3( x, y, z ) );
  7752. } );
  7753. return ret.normalize();
  7754. } );
  7755. class Texture3DNode extends TextureNode {
  7756. static get type() {
  7757. return 'Texture3DNode';
  7758. }
  7759. constructor( value, uvNode = null, levelNode = null ) {
  7760. super( value, uvNode, levelNode );
  7761. this.isTexture3DNode = true;
  7762. }
  7763. getInputType( /*builder*/ ) {
  7764. return 'texture3D';
  7765. }
  7766. getDefaultUV() {
  7767. return vec3( 0.5, 0.5, 0.5 );
  7768. }
  7769. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  7770. setupUV( builder, uvNode ) {
  7771. return uvNode;
  7772. }
  7773. generateUV( builder, uvNode ) {
  7774. return uvNode.build( builder, 'vec3' );
  7775. }
  7776. normal( uvNode ) {
  7777. return normal( { texture: this, uv: uvNode } );
  7778. }
  7779. }
  7780. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode );
  7781. class VolumeNodeMaterial extends NodeMaterial {
  7782. static get type() {
  7783. return 'VolumeNodeMaterial';
  7784. }
  7785. constructor( params = {} ) {
  7786. super();
  7787. this.lights = false;
  7788. this.isVolumeNodeMaterial = true;
  7789. this.testNode = null;
  7790. this.setValues( params );
  7791. }
  7792. setup( builder ) {
  7793. const map = texture3D( this.map, null, 0 );
  7794. const hitBox = Fn( ( { orig, dir } ) => {
  7795. const box_min = vec3( - 0.5 );
  7796. const box_max = vec3( 0.5 );
  7797. const inv_dir = dir.reciprocal();
  7798. const tmin_tmp = box_min.sub( orig ).mul( inv_dir );
  7799. const tmax_tmp = box_max.sub( orig ).mul( inv_dir );
  7800. const tmin = min$1( tmin_tmp, tmax_tmp );
  7801. const tmax = max$1( tmin_tmp, tmax_tmp );
  7802. const t0 = max$1( tmin.x, max$1( tmin.y, tmin.z ) );
  7803. const t1 = min$1( tmax.x, min$1( tmax.y, tmax.z ) );
  7804. return vec2( t0, t1 );
  7805. } );
  7806. this.fragmentNode = Fn( () => {
  7807. const vOrigin = varying( vec3( modelWorldMatrixInverse.mul( vec4( cameraPosition, 1.0 ) ) ) );
  7808. const vDirection = varying( positionGeometry.sub( vOrigin ) );
  7809. const rayDir = vDirection.normalize();
  7810. const bounds = vec2( hitBox( { orig: vOrigin, dir: rayDir } ) ).toVar();
  7811. bounds.x.greaterThan( bounds.y ).discard();
  7812. bounds.assign( vec2( max$1( bounds.x, 0.0 ), bounds.y ) );
  7813. const p = vec3( vOrigin.add( bounds.x.mul( rayDir ) ) ).toVar();
  7814. const inc = vec3( rayDir.abs().reciprocal() ).toVar();
  7815. const delta = float( min$1( inc.x, min$1( inc.y, inc.z ) ) ).toVar( 'delta' ); // used 'delta' name in loop
  7816. delta.divAssign( materialReference( 'steps', 'float' ) );
  7817. const ac = vec4( materialReference( 'base', 'color' ), 0.0 ).toVar();
  7818. Loop( { type: 'float', start: bounds.x, end: bounds.y, update: '+= delta' }, () => {
  7819. const d = property( 'float', 'd' ).assign( map.uv( p.add( 0.5 ) ).r );
  7820. if ( this.testNode !== null ) {
  7821. this.testNode( { map: map, mapValue: d, probe: p, finalColor: ac } ).append();
  7822. } else {
  7823. // default to show surface of mesh
  7824. ac.a.assign( 1 );
  7825. Break();
  7826. }
  7827. p.addAssign( rayDir.mul( delta ) );
  7828. } );
  7829. ac.a.equal( 0 ).discard();
  7830. return vec4( ac );
  7831. } )();
  7832. super.setup( builder );
  7833. }
  7834. }
  7835. class Animation {
  7836. constructor( nodes, info ) {
  7837. this.nodes = nodes;
  7838. this.info = info;
  7839. this._context = self;
  7840. this._animationLoop = null;
  7841. this._requestId = null;
  7842. }
  7843. start() {
  7844. const update = ( time, frame ) => {
  7845. this._requestId = this._context.requestAnimationFrame( update );
  7846. if ( this.info.autoReset === true ) this.info.reset();
  7847. this.nodes.nodeFrame.update();
  7848. this.info.frame = this.nodes.nodeFrame.frameId;
  7849. if ( this._animationLoop !== null ) this._animationLoop( time, frame );
  7850. };
  7851. update();
  7852. }
  7853. stop() {
  7854. this._context.cancelAnimationFrame( this._requestId );
  7855. this._requestId = null;
  7856. }
  7857. setAnimationLoop( callback ) {
  7858. this._animationLoop = callback;
  7859. }
  7860. setContext( context ) {
  7861. this._context = context;
  7862. }
  7863. dispose() {
  7864. this.stop();
  7865. }
  7866. }
  7867. class ChainMap {
  7868. constructor() {
  7869. this.weakMap = new WeakMap();
  7870. }
  7871. get( keys ) {
  7872. let map = this.weakMap;
  7873. for ( let i = 0; i < keys.length; i ++ ) {
  7874. map = map.get( keys[ i ] );
  7875. if ( map === undefined ) return undefined;
  7876. }
  7877. return map.get( keys[ keys.length - 1 ] );
  7878. }
  7879. set( keys, value ) {
  7880. let map = this.weakMap;
  7881. for ( let i = 0; i < keys.length; i ++ ) {
  7882. const key = keys[ i ];
  7883. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  7884. map = map.get( key );
  7885. }
  7886. return map.set( keys[ keys.length - 1 ], value );
  7887. }
  7888. delete( keys ) {
  7889. let map = this.weakMap;
  7890. for ( let i = 0; i < keys.length; i ++ ) {
  7891. map = map.get( keys[ i ] );
  7892. if ( map === undefined ) return false;
  7893. }
  7894. return map.delete( keys[ keys.length - 1 ] );
  7895. }
  7896. }
  7897. let _id$7 = 0;
  7898. function getKeys( obj ) {
  7899. const keys = Object.keys( obj );
  7900. let proto = Object.getPrototypeOf( obj );
  7901. while ( proto ) {
  7902. const descriptors = Object.getOwnPropertyDescriptors( proto );
  7903. for ( const key in descriptors ) {
  7904. if ( descriptors[ key ] !== undefined ) {
  7905. const descriptor = descriptors[ key ];
  7906. if ( descriptor && typeof descriptor.get === 'function' ) {
  7907. keys.push( key );
  7908. }
  7909. }
  7910. }
  7911. proto = Object.getPrototypeOf( proto );
  7912. }
  7913. return keys;
  7914. }
  7915. class RenderObject {
  7916. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  7917. this._nodes = nodes;
  7918. this._geometries = geometries;
  7919. this.id = _id$7 ++;
  7920. this.renderer = renderer;
  7921. this.object = object;
  7922. this.material = material;
  7923. this.scene = scene;
  7924. this.camera = camera;
  7925. this.lightsNode = lightsNode;
  7926. this.context = renderContext;
  7927. this.geometry = object.geometry;
  7928. this.version = material.version;
  7929. this.drawRange = null;
  7930. this.attributes = null;
  7931. this.pipeline = null;
  7932. this.vertexBuffers = null;
  7933. this.drawParams = null;
  7934. this.bundle = null;
  7935. this.clippingContext = clippingContext;
  7936. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  7937. this.initialNodesCacheKey = this.getDynamicCacheKey();
  7938. this.initialCacheKey = this.getCacheKey();
  7939. this._nodeBuilderState = null;
  7940. this._bindings = null;
  7941. this._monitor = null;
  7942. this.onDispose = null;
  7943. this.isRenderObject = true;
  7944. this.onMaterialDispose = () => {
  7945. this.dispose();
  7946. };
  7947. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  7948. }
  7949. updateClipping( parent ) {
  7950. this.clippingContext = parent;
  7951. }
  7952. get clippingNeedsUpdate() {
  7953. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  7954. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  7955. return true;
  7956. }
  7957. get hardwareClippingPlanes() {
  7958. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  7959. }
  7960. getNodeBuilderState() {
  7961. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  7962. }
  7963. getMonitor() {
  7964. return this._monitor || ( this._monitor = this.getNodeBuilderState().monitor );
  7965. }
  7966. getBindings() {
  7967. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  7968. }
  7969. getIndex() {
  7970. return this._geometries.getIndex( this );
  7971. }
  7972. getIndirect() {
  7973. return this._geometries.getIndirect( this );
  7974. }
  7975. getChainArray() {
  7976. return [ this.object, this.material, this.context, this.lightsNode ];
  7977. }
  7978. setGeometry( geometry ) {
  7979. this.geometry = geometry;
  7980. this.attributes = null;
  7981. }
  7982. getAttributes() {
  7983. if ( this.attributes !== null ) return this.attributes;
  7984. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  7985. const geometry = this.geometry;
  7986. const attributes = [];
  7987. const vertexBuffers = new Set();
  7988. for ( const nodeAttribute of nodeAttributes ) {
  7989. const attribute = nodeAttribute.node && nodeAttribute.node.attribute ? nodeAttribute.node.attribute : geometry.getAttribute( nodeAttribute.name );
  7990. if ( attribute === undefined ) continue;
  7991. attributes.push( attribute );
  7992. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  7993. vertexBuffers.add( bufferAttribute );
  7994. }
  7995. this.attributes = attributes;
  7996. this.vertexBuffers = Array.from( vertexBuffers.values() );
  7997. return attributes;
  7998. }
  7999. getVertexBuffers() {
  8000. if ( this.vertexBuffers === null ) this.getAttributes();
  8001. return this.vertexBuffers;
  8002. }
  8003. getDrawParameters() {
  8004. const { object, material, geometry, group, drawRange } = this;
  8005. const drawParams = this.drawParams || ( this.drawParams = {
  8006. vertexCount: 0,
  8007. firstVertex: 0,
  8008. instanceCount: 0,
  8009. firstInstance: 0
  8010. } );
  8011. const index = this.getIndex();
  8012. const hasIndex = ( index !== null );
  8013. const instanceCount = geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  8014. if ( instanceCount === 0 ) return null;
  8015. drawParams.instanceCount = instanceCount;
  8016. if ( object.isBatchedMesh === true ) return drawParams;
  8017. let rangeFactor = 1;
  8018. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  8019. rangeFactor = 2;
  8020. }
  8021. let firstVertex = drawRange.start * rangeFactor;
  8022. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  8023. if ( group !== null ) {
  8024. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  8025. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  8026. }
  8027. const position = geometry.attributes.position;
  8028. let itemCount = Infinity;
  8029. if ( hasIndex ) {
  8030. itemCount = index.count;
  8031. } else if ( position !== undefined && position !== null ) {
  8032. itemCount = position.count;
  8033. }
  8034. firstVertex = Math.max( firstVertex, 0 );
  8035. lastVertex = Math.min( lastVertex, itemCount );
  8036. const count = lastVertex - firstVertex;
  8037. if ( count < 0 || count === Infinity ) return null;
  8038. drawParams.vertexCount = count;
  8039. drawParams.firstVertex = firstVertex;
  8040. return drawParams;
  8041. }
  8042. getGeometryCacheKey() {
  8043. const { geometry } = this;
  8044. let cacheKey = '';
  8045. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  8046. const attribute = geometry.attributes[ name ];
  8047. cacheKey += name + ',';
  8048. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  8049. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  8050. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  8051. if ( attribute.normalized ) cacheKey += 'n,';
  8052. }
  8053. if ( geometry.index ) {
  8054. cacheKey += 'index,';
  8055. }
  8056. return cacheKey;
  8057. }
  8058. getMaterialCacheKey() {
  8059. const { object, material } = this;
  8060. let cacheKey = material.customProgramCacheKey();
  8061. for ( const property of getKeys( material ) ) {
  8062. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  8063. const value = material[ property ];
  8064. let valueKey;
  8065. if ( value !== null ) {
  8066. // some material values require a formatting
  8067. const type = typeof value;
  8068. if ( type === 'number' ) {
  8069. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  8070. } else if ( type === 'object' ) {
  8071. valueKey = '{';
  8072. if ( value.isTexture ) {
  8073. valueKey += value.mapping;
  8074. }
  8075. valueKey += '}';
  8076. } else {
  8077. valueKey = String( value );
  8078. }
  8079. } else {
  8080. valueKey = String( value );
  8081. }
  8082. cacheKey += /*property + ':' +*/ valueKey + ',';
  8083. }
  8084. cacheKey += this.clippingContextCacheKey + ',';
  8085. if ( object.geometry ) {
  8086. cacheKey += this.getGeometryCacheKey();
  8087. }
  8088. if ( object.skeleton ) {
  8089. cacheKey += object.skeleton.bones.length + ',';
  8090. }
  8091. if ( object.morphTargetInfluences ) {
  8092. cacheKey += object.morphTargetInfluences.length + ',';
  8093. }
  8094. if ( object.isBatchedMesh ) {
  8095. cacheKey += object._matricesTexture.uuid + ',';
  8096. if ( object._colorsTexture !== null ) {
  8097. cacheKey += object._colorsTexture.uuid + ',';
  8098. }
  8099. }
  8100. if ( object.count > 1 ) {
  8101. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  8102. cacheKey += object.uuid + ',';
  8103. }
  8104. cacheKey += object.receiveShadow + ',';
  8105. return hashString( cacheKey );
  8106. }
  8107. get needsGeometryUpdate() {
  8108. return this.geometry.id !== this.object.geometry.id;
  8109. }
  8110. get needsUpdate() {
  8111. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  8112. }
  8113. getDynamicCacheKey() {
  8114. // Environment Nodes Cache Key
  8115. let cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  8116. if ( this.object.receiveShadow ) {
  8117. cacheKey += 1;
  8118. }
  8119. return cacheKey;
  8120. }
  8121. getCacheKey() {
  8122. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  8123. }
  8124. dispose() {
  8125. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  8126. this.onDispose();
  8127. }
  8128. }
  8129. const chainArray = [];
  8130. class RenderObjects {
  8131. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  8132. this.renderer = renderer;
  8133. this.nodes = nodes;
  8134. this.geometries = geometries;
  8135. this.pipelines = pipelines;
  8136. this.bindings = bindings;
  8137. this.info = info;
  8138. this.chainMaps = {};
  8139. }
  8140. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  8141. const chainMap = this.getChainMap( passId );
  8142. // reuse chainArray
  8143. chainArray[ 0 ] = object;
  8144. chainArray[ 1 ] = material;
  8145. chainArray[ 2 ] = renderContext;
  8146. chainArray[ 3 ] = lightsNode;
  8147. let renderObject = chainMap.get( chainArray );
  8148. if ( renderObject === undefined ) {
  8149. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  8150. chainMap.set( chainArray, renderObject );
  8151. } else {
  8152. renderObject.updateClipping( clippingContext );
  8153. if ( renderObject.needsGeometryUpdate ) {
  8154. renderObject.setGeometry( object.geometry );
  8155. }
  8156. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  8157. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  8158. renderObject.dispose();
  8159. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  8160. } else {
  8161. renderObject.version = material.version;
  8162. }
  8163. }
  8164. }
  8165. return renderObject;
  8166. }
  8167. getChainMap( passId = 'default' ) {
  8168. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  8169. }
  8170. dispose() {
  8171. this.chainMaps = {};
  8172. }
  8173. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  8174. const chainMap = this.getChainMap( passId );
  8175. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  8176. renderObject.onDispose = () => {
  8177. this.pipelines.delete( renderObject );
  8178. this.bindings.delete( renderObject );
  8179. this.nodes.delete( renderObject );
  8180. chainMap.delete( renderObject.getChainArray() );
  8181. };
  8182. return renderObject;
  8183. }
  8184. }
  8185. class DataMap {
  8186. constructor() {
  8187. this.data = new WeakMap();
  8188. }
  8189. get( object ) {
  8190. let map = this.data.get( object );
  8191. if ( map === undefined ) {
  8192. map = {};
  8193. this.data.set( object, map );
  8194. }
  8195. return map;
  8196. }
  8197. delete( object ) {
  8198. let map;
  8199. if ( this.data.has( object ) ) {
  8200. map = this.data.get( object );
  8201. this.data.delete( object );
  8202. }
  8203. return map;
  8204. }
  8205. has( object ) {
  8206. return this.data.has( object );
  8207. }
  8208. dispose() {
  8209. this.data = new WeakMap();
  8210. }
  8211. }
  8212. const AttributeType = {
  8213. VERTEX: 1,
  8214. INDEX: 2,
  8215. STORAGE: 3,
  8216. INDIRECT: 4
  8217. };
  8218. // size of a chunk in bytes (STD140 layout)
  8219. const GPU_CHUNK_BYTES = 16;
  8220. // @TODO: Move to src/constants.js
  8221. const BlendColorFactor = 211;
  8222. const OneMinusBlendColorFactor = 212;
  8223. class Attributes extends DataMap {
  8224. constructor( backend ) {
  8225. super();
  8226. this.backend = backend;
  8227. }
  8228. delete( attribute ) {
  8229. const attributeData = super.delete( attribute );
  8230. if ( attributeData !== undefined ) {
  8231. this.backend.destroyAttribute( attribute );
  8232. }
  8233. return attributeData;
  8234. }
  8235. update( attribute, type ) {
  8236. const data = this.get( attribute );
  8237. if ( data.version === undefined ) {
  8238. if ( type === AttributeType.VERTEX ) {
  8239. this.backend.createAttribute( attribute );
  8240. } else if ( type === AttributeType.INDEX ) {
  8241. this.backend.createIndexAttribute( attribute );
  8242. } else if ( type === AttributeType.STORAGE ) {
  8243. this.backend.createStorageAttribute( attribute );
  8244. } else if ( type === AttributeType.INDIRECT ) {
  8245. this.backend.createIndirectStorageAttribute( attribute );
  8246. }
  8247. data.version = this._getBufferAttribute( attribute ).version;
  8248. } else {
  8249. const bufferAttribute = this._getBufferAttribute( attribute );
  8250. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  8251. this.backend.updateAttribute( attribute );
  8252. data.version = bufferAttribute.version;
  8253. }
  8254. }
  8255. }
  8256. _getBufferAttribute( attribute ) {
  8257. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8258. return attribute;
  8259. }
  8260. }
  8261. function arrayNeedsUint32( array ) {
  8262. // assumes larger values usually on last
  8263. for ( let i = array.length - 1; i >= 0; -- i ) {
  8264. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  8265. }
  8266. return false;
  8267. }
  8268. function getWireframeVersion( geometry ) {
  8269. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  8270. }
  8271. function getWireframeIndex( geometry ) {
  8272. const indices = [];
  8273. const geometryIndex = geometry.index;
  8274. const geometryPosition = geometry.attributes.position;
  8275. if ( geometryIndex !== null ) {
  8276. const array = geometryIndex.array;
  8277. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  8278. const a = array[ i + 0 ];
  8279. const b = array[ i + 1 ];
  8280. const c = array[ i + 2 ];
  8281. indices.push( a, b, b, c, c, a );
  8282. }
  8283. } else {
  8284. const array = geometryPosition.array;
  8285. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  8286. const a = i + 0;
  8287. const b = i + 1;
  8288. const c = i + 2;
  8289. indices.push( a, b, b, c, c, a );
  8290. }
  8291. }
  8292. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  8293. attribute.version = getWireframeVersion( geometry );
  8294. return attribute;
  8295. }
  8296. class Geometries extends DataMap {
  8297. constructor( attributes, info ) {
  8298. super();
  8299. this.attributes = attributes;
  8300. this.info = info;
  8301. this.wireframes = new WeakMap();
  8302. this.attributeCall = new WeakMap();
  8303. }
  8304. has( renderObject ) {
  8305. const geometry = renderObject.geometry;
  8306. return super.has( geometry ) && this.get( geometry ).initialized === true;
  8307. }
  8308. updateForRender( renderObject ) {
  8309. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  8310. this.updateAttributes( renderObject );
  8311. }
  8312. initGeometry( renderObject ) {
  8313. const geometry = renderObject.geometry;
  8314. const geometryData = this.get( geometry );
  8315. geometryData.initialized = true;
  8316. this.info.memory.geometries ++;
  8317. const onDispose = () => {
  8318. this.info.memory.geometries --;
  8319. const index = geometry.index;
  8320. const geometryAttributes = renderObject.getAttributes();
  8321. if ( index !== null ) {
  8322. this.attributes.delete( index );
  8323. }
  8324. for ( const geometryAttribute of geometryAttributes ) {
  8325. this.attributes.delete( geometryAttribute );
  8326. }
  8327. const wireframeAttribute = this.wireframes.get( geometry );
  8328. if ( wireframeAttribute !== undefined ) {
  8329. this.attributes.delete( wireframeAttribute );
  8330. }
  8331. geometry.removeEventListener( 'dispose', onDispose );
  8332. };
  8333. geometry.addEventListener( 'dispose', onDispose );
  8334. }
  8335. updateAttributes( renderObject ) {
  8336. // attributes
  8337. const attributes = renderObject.getAttributes();
  8338. for ( const attribute of attributes ) {
  8339. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  8340. this.updateAttribute( attribute, AttributeType.STORAGE );
  8341. } else {
  8342. this.updateAttribute( attribute, AttributeType.VERTEX );
  8343. }
  8344. }
  8345. // indexes
  8346. const index = this.getIndex( renderObject );
  8347. if ( index !== null ) {
  8348. this.updateAttribute( index, AttributeType.INDEX );
  8349. }
  8350. // indirect
  8351. const indirect = renderObject.geometry.indirect;
  8352. if ( indirect !== null ) {
  8353. this.updateAttribute( indirect, AttributeType.INDIRECT );
  8354. }
  8355. }
  8356. updateAttribute( attribute, type ) {
  8357. const callId = this.info.render.calls;
  8358. if ( ! attribute.isInterleavedBufferAttribute ) {
  8359. if ( this.attributeCall.get( attribute ) !== callId ) {
  8360. this.attributes.update( attribute, type );
  8361. this.attributeCall.set( attribute, callId );
  8362. }
  8363. } else {
  8364. if ( this.attributeCall.get( attribute ) === undefined ) {
  8365. this.attributes.update( attribute, type );
  8366. this.attributeCall.set( attribute, callId );
  8367. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  8368. this.attributes.update( attribute, type );
  8369. this.attributeCall.set( attribute.data, callId );
  8370. this.attributeCall.set( attribute, callId );
  8371. }
  8372. }
  8373. }
  8374. getIndirect( renderObject ) {
  8375. return renderObject.geometry.indirect;
  8376. }
  8377. getIndex( renderObject ) {
  8378. const { geometry, material } = renderObject;
  8379. let index = geometry.index;
  8380. if ( material.wireframe === true ) {
  8381. const wireframes = this.wireframes;
  8382. let wireframeAttribute = wireframes.get( geometry );
  8383. if ( wireframeAttribute === undefined ) {
  8384. wireframeAttribute = getWireframeIndex( geometry );
  8385. wireframes.set( geometry, wireframeAttribute );
  8386. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  8387. this.attributes.delete( wireframeAttribute );
  8388. wireframeAttribute = getWireframeIndex( geometry );
  8389. wireframes.set( geometry, wireframeAttribute );
  8390. }
  8391. index = wireframeAttribute;
  8392. }
  8393. return index;
  8394. }
  8395. }
  8396. class Info {
  8397. constructor() {
  8398. this.autoReset = true;
  8399. this.frame = 0;
  8400. this.calls = 0;
  8401. this.render = {
  8402. calls: 0,
  8403. frameCalls: 0,
  8404. drawCalls: 0,
  8405. triangles: 0,
  8406. points: 0,
  8407. lines: 0,
  8408. timestamp: 0,
  8409. previousFrameCalls: 0,
  8410. timestampCalls: 0
  8411. };
  8412. this.compute = {
  8413. calls: 0,
  8414. frameCalls: 0,
  8415. timestamp: 0,
  8416. previousFrameCalls: 0,
  8417. timestampCalls: 0
  8418. };
  8419. this.memory = {
  8420. geometries: 0,
  8421. textures: 0
  8422. };
  8423. }
  8424. update( object, count, instanceCount ) {
  8425. this.render.drawCalls ++;
  8426. if ( object.isMesh || object.isSprite ) {
  8427. this.render.triangles += instanceCount * ( count / 3 );
  8428. } else if ( object.isPoints ) {
  8429. this.render.points += instanceCount * count;
  8430. } else if ( object.isLineSegments ) {
  8431. this.render.lines += instanceCount * ( count / 2 );
  8432. } else if ( object.isLine ) {
  8433. this.render.lines += instanceCount * ( count - 1 );
  8434. } else {
  8435. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  8436. }
  8437. }
  8438. updateTimestamp( type, time ) {
  8439. if ( this[ type ].timestampCalls === 0 ) {
  8440. this[ type ].timestamp = 0;
  8441. }
  8442. this[ type ].timestamp += time;
  8443. this[ type ].timestampCalls ++;
  8444. if ( this[ type ].timestampCalls >= this[ type ].previousFrameCalls ) {
  8445. this[ type ].timestampCalls = 0;
  8446. }
  8447. }
  8448. reset() {
  8449. const previousRenderFrameCalls = this.render.frameCalls;
  8450. this.render.previousFrameCalls = previousRenderFrameCalls;
  8451. const previousComputeFrameCalls = this.compute.frameCalls;
  8452. this.compute.previousFrameCalls = previousComputeFrameCalls;
  8453. this.render.drawCalls = 0;
  8454. this.render.frameCalls = 0;
  8455. this.compute.frameCalls = 0;
  8456. this.render.triangles = 0;
  8457. this.render.points = 0;
  8458. this.render.lines = 0;
  8459. }
  8460. dispose() {
  8461. this.reset();
  8462. this.calls = 0;
  8463. this.render.calls = 0;
  8464. this.compute.calls = 0;
  8465. this.render.timestamp = 0;
  8466. this.compute.timestamp = 0;
  8467. this.memory.geometries = 0;
  8468. this.memory.textures = 0;
  8469. }
  8470. }
  8471. class Pipeline {
  8472. constructor( cacheKey ) {
  8473. this.cacheKey = cacheKey;
  8474. this.usedTimes = 0;
  8475. }
  8476. }
  8477. class RenderPipeline extends Pipeline {
  8478. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  8479. super( cacheKey );
  8480. this.vertexProgram = vertexProgram;
  8481. this.fragmentProgram = fragmentProgram;
  8482. }
  8483. }
  8484. class ComputePipeline extends Pipeline {
  8485. constructor( cacheKey, computeProgram ) {
  8486. super( cacheKey );
  8487. this.computeProgram = computeProgram;
  8488. this.isComputePipeline = true;
  8489. }
  8490. }
  8491. let _id$6 = 0;
  8492. class ProgrammableStage {
  8493. constructor( code, type, transforms = null, attributes = null ) {
  8494. this.id = _id$6 ++;
  8495. this.code = code;
  8496. this.stage = type;
  8497. this.transforms = transforms;
  8498. this.attributes = attributes;
  8499. this.usedTimes = 0;
  8500. }
  8501. }
  8502. class Pipelines extends DataMap {
  8503. constructor( backend, nodes ) {
  8504. super();
  8505. this.backend = backend;
  8506. this.nodes = nodes;
  8507. this.bindings = null; // set by the bindings
  8508. this.caches = new Map();
  8509. this.programs = {
  8510. vertex: new Map(),
  8511. fragment: new Map(),
  8512. compute: new Map()
  8513. };
  8514. }
  8515. getForCompute( computeNode, bindings ) {
  8516. const { backend } = this;
  8517. const data = this.get( computeNode );
  8518. if ( this._needsComputeUpdate( computeNode ) ) {
  8519. const previousPipeline = data.pipeline;
  8520. if ( previousPipeline ) {
  8521. previousPipeline.usedTimes --;
  8522. previousPipeline.computeProgram.usedTimes --;
  8523. }
  8524. // get shader
  8525. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  8526. // programmable stage
  8527. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  8528. if ( stageCompute === undefined ) {
  8529. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  8530. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  8531. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  8532. backend.createProgram( stageCompute );
  8533. }
  8534. // determine compute pipeline
  8535. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  8536. let pipeline = this.caches.get( cacheKey );
  8537. if ( pipeline === undefined ) {
  8538. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  8539. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  8540. }
  8541. // keep track of all used times
  8542. pipeline.usedTimes ++;
  8543. stageCompute.usedTimes ++;
  8544. //
  8545. data.version = computeNode.version;
  8546. data.pipeline = pipeline;
  8547. }
  8548. return data.pipeline;
  8549. }
  8550. getForRender( renderObject, promises = null ) {
  8551. const { backend } = this;
  8552. const data = this.get( renderObject );
  8553. if ( this._needsRenderUpdate( renderObject ) ) {
  8554. const previousPipeline = data.pipeline;
  8555. if ( previousPipeline ) {
  8556. previousPipeline.usedTimes --;
  8557. previousPipeline.vertexProgram.usedTimes --;
  8558. previousPipeline.fragmentProgram.usedTimes --;
  8559. }
  8560. // get shader
  8561. const nodeBuilderState = renderObject.getNodeBuilderState();
  8562. // programmable stages
  8563. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  8564. if ( stageVertex === undefined ) {
  8565. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  8566. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex' );
  8567. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  8568. backend.createProgram( stageVertex );
  8569. }
  8570. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  8571. if ( stageFragment === undefined ) {
  8572. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  8573. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment' );
  8574. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  8575. backend.createProgram( stageFragment );
  8576. }
  8577. // determine render pipeline
  8578. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  8579. let pipeline = this.caches.get( cacheKey );
  8580. if ( pipeline === undefined ) {
  8581. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  8582. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  8583. } else {
  8584. renderObject.pipeline = pipeline;
  8585. }
  8586. // keep track of all used times
  8587. pipeline.usedTimes ++;
  8588. stageVertex.usedTimes ++;
  8589. stageFragment.usedTimes ++;
  8590. //
  8591. data.pipeline = pipeline;
  8592. }
  8593. return data.pipeline;
  8594. }
  8595. delete( object ) {
  8596. const pipeline = this.get( object ).pipeline;
  8597. if ( pipeline ) {
  8598. // pipeline
  8599. pipeline.usedTimes --;
  8600. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  8601. // programs
  8602. if ( pipeline.isComputePipeline ) {
  8603. pipeline.computeProgram.usedTimes --;
  8604. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  8605. } else {
  8606. pipeline.fragmentProgram.usedTimes --;
  8607. pipeline.vertexProgram.usedTimes --;
  8608. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  8609. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  8610. }
  8611. }
  8612. return super.delete( object );
  8613. }
  8614. dispose() {
  8615. super.dispose();
  8616. this.caches = new Map();
  8617. this.programs = {
  8618. vertex: new Map(),
  8619. fragment: new Map(),
  8620. compute: new Map()
  8621. };
  8622. }
  8623. updateForRender( renderObject ) {
  8624. this.getForRender( renderObject );
  8625. }
  8626. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  8627. // check for existing pipeline
  8628. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  8629. let pipeline = this.caches.get( cacheKey );
  8630. if ( pipeline === undefined ) {
  8631. pipeline = new ComputePipeline( cacheKey, stageCompute );
  8632. this.caches.set( cacheKey, pipeline );
  8633. this.backend.createComputePipeline( pipeline, bindings );
  8634. }
  8635. return pipeline;
  8636. }
  8637. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  8638. // check for existing pipeline
  8639. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  8640. let pipeline = this.caches.get( cacheKey );
  8641. if ( pipeline === undefined ) {
  8642. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  8643. this.caches.set( cacheKey, pipeline );
  8644. renderObject.pipeline = pipeline;
  8645. this.backend.createRenderPipeline( renderObject, promises );
  8646. }
  8647. return pipeline;
  8648. }
  8649. _getComputeCacheKey( computeNode, stageCompute ) {
  8650. return computeNode.id + ',' + stageCompute.id;
  8651. }
  8652. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  8653. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  8654. }
  8655. _releasePipeline( pipeline ) {
  8656. this.caches.delete( pipeline.cacheKey );
  8657. }
  8658. _releaseProgram( program ) {
  8659. const code = program.code;
  8660. const stage = program.stage;
  8661. this.programs[ stage ].delete( code );
  8662. }
  8663. _needsComputeUpdate( computeNode ) {
  8664. const data = this.get( computeNode );
  8665. return data.pipeline === undefined || data.version !== computeNode.version;
  8666. }
  8667. _needsRenderUpdate( renderObject ) {
  8668. const data = this.get( renderObject );
  8669. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  8670. }
  8671. }
  8672. class Bindings extends DataMap {
  8673. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  8674. super();
  8675. this.backend = backend;
  8676. this.textures = textures;
  8677. this.pipelines = pipelines;
  8678. this.attributes = attributes;
  8679. this.nodes = nodes;
  8680. this.info = info;
  8681. this.pipelines.bindings = this; // assign bindings to pipelines
  8682. }
  8683. getForRender( renderObject ) {
  8684. const bindings = renderObject.getBindings();
  8685. for ( const bindGroup of bindings ) {
  8686. const groupData = this.get( bindGroup );
  8687. if ( groupData.bindGroup === undefined ) {
  8688. // each object defines an array of bindings (ubos, textures, samplers etc.)
  8689. this._init( bindGroup );
  8690. this.backend.createBindings( bindGroup, bindings, 0 );
  8691. groupData.bindGroup = bindGroup;
  8692. }
  8693. }
  8694. return bindings;
  8695. }
  8696. getForCompute( computeNode ) {
  8697. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  8698. for ( const bindGroup of bindings ) {
  8699. const groupData = this.get( bindGroup );
  8700. if ( groupData.bindGroup === undefined ) {
  8701. this._init( bindGroup );
  8702. this.backend.createBindings( bindGroup, bindings, 0 );
  8703. groupData.bindGroup = bindGroup;
  8704. }
  8705. }
  8706. return bindings;
  8707. }
  8708. updateForCompute( computeNode ) {
  8709. this._updateBindings( this.getForCompute( computeNode ) );
  8710. }
  8711. updateForRender( renderObject ) {
  8712. this._updateBindings( this.getForRender( renderObject ) );
  8713. }
  8714. _updateBindings( bindings ) {
  8715. for ( const bindGroup of bindings ) {
  8716. this._update( bindGroup, bindings );
  8717. }
  8718. }
  8719. _init( bindGroup ) {
  8720. for ( const binding of bindGroup.bindings ) {
  8721. if ( binding.isSampledTexture ) {
  8722. this.textures.updateTexture( binding.texture );
  8723. } else if ( binding.isStorageBuffer ) {
  8724. const attribute = binding.attribute;
  8725. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  8726. this.attributes.update( attribute, attributeType );
  8727. }
  8728. }
  8729. }
  8730. _update( bindGroup, bindings ) {
  8731. const { backend } = this;
  8732. let needsBindingsUpdate = false;
  8733. let cacheBindings = true;
  8734. let cacheIndex = 0;
  8735. let version = 0;
  8736. // iterate over all bindings and check if buffer updates or a new binding group is required
  8737. for ( const binding of bindGroup.bindings ) {
  8738. if ( binding.isNodeUniformsGroup ) {
  8739. const updated = this.nodes.updateGroup( binding );
  8740. if ( ! updated ) continue;
  8741. }
  8742. if ( binding.isUniformBuffer ) {
  8743. const updated = binding.update();
  8744. if ( updated ) {
  8745. backend.updateBinding( binding );
  8746. }
  8747. } else if ( binding.isSampler ) {
  8748. binding.update();
  8749. } else if ( binding.isSampledTexture ) {
  8750. const texturesTextureData = this.textures.get( binding.texture );
  8751. if ( binding.needsBindingsUpdate( texturesTextureData.generation ) ) needsBindingsUpdate = true;
  8752. const updated = binding.update();
  8753. const texture = binding.texture;
  8754. if ( updated ) {
  8755. this.textures.updateTexture( texture );
  8756. }
  8757. const textureData = backend.get( texture );
  8758. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  8759. cacheBindings = false;
  8760. } else {
  8761. cacheIndex = cacheIndex * 10 + texture.id;
  8762. version += texture.version;
  8763. }
  8764. if ( backend.isWebGPUBackend === true && textureData.texture === undefined && textureData.externalTexture === undefined ) {
  8765. // TODO: Remove this once we found why updated === false isn't bound to a texture in the WebGPU backend
  8766. console.error( 'Bindings._update: binding should be available:', binding, updated, texture, binding.textureNode.value, needsBindingsUpdate );
  8767. this.textures.updateTexture( texture );
  8768. needsBindingsUpdate = true;
  8769. }
  8770. if ( texture.isStorageTexture === true ) {
  8771. const textureData = this.get( texture );
  8772. if ( binding.store === true ) {
  8773. textureData.needsMipmap = true;
  8774. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  8775. this.backend.generateMipmaps( texture );
  8776. textureData.needsMipmap = false;
  8777. }
  8778. }
  8779. }
  8780. }
  8781. if ( needsBindingsUpdate === true ) {
  8782. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  8783. }
  8784. }
  8785. }
  8786. function painterSortStable( a, b ) {
  8787. if ( a.groupOrder !== b.groupOrder ) {
  8788. return a.groupOrder - b.groupOrder;
  8789. } else if ( a.renderOrder !== b.renderOrder ) {
  8790. return a.renderOrder - b.renderOrder;
  8791. } else if ( a.material.id !== b.material.id ) {
  8792. return a.material.id - b.material.id;
  8793. } else if ( a.z !== b.z ) {
  8794. return a.z - b.z;
  8795. } else {
  8796. return a.id - b.id;
  8797. }
  8798. }
  8799. function reversePainterSortStable( a, b ) {
  8800. if ( a.groupOrder !== b.groupOrder ) {
  8801. return a.groupOrder - b.groupOrder;
  8802. } else if ( a.renderOrder !== b.renderOrder ) {
  8803. return a.renderOrder - b.renderOrder;
  8804. } else if ( a.z !== b.z ) {
  8805. return b.z - a.z;
  8806. } else {
  8807. return a.id - b.id;
  8808. }
  8809. }
  8810. function needsDoublePass( material ) {
  8811. const hasTransmission = material.transmission > 0 || material.transmissionNode;
  8812. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  8813. }
  8814. class RenderList {
  8815. constructor( lighting, scene, camera ) {
  8816. this.renderItems = [];
  8817. this.renderItemsIndex = 0;
  8818. this.opaque = [];
  8819. this.transparentDoublePass = [];
  8820. this.transparent = [];
  8821. this.bundles = [];
  8822. this.lightsNode = lighting.getNode( scene, camera );
  8823. this.lightsArray = [];
  8824. this.scene = scene;
  8825. this.camera = camera;
  8826. this.occlusionQueryCount = 0;
  8827. }
  8828. begin() {
  8829. this.renderItemsIndex = 0;
  8830. this.opaque.length = 0;
  8831. this.transparentDoublePass.length = 0;
  8832. this.transparent.length = 0;
  8833. this.bundles.length = 0;
  8834. this.lightsArray.length = 0;
  8835. this.occlusionQueryCount = 0;
  8836. return this;
  8837. }
  8838. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  8839. let renderItem = this.renderItems[ this.renderItemsIndex ];
  8840. if ( renderItem === undefined ) {
  8841. renderItem = {
  8842. id: object.id,
  8843. object: object,
  8844. geometry: geometry,
  8845. material: material,
  8846. groupOrder: groupOrder,
  8847. renderOrder: object.renderOrder,
  8848. z: z,
  8849. group: group,
  8850. clippingContext: clippingContext
  8851. };
  8852. this.renderItems[ this.renderItemsIndex ] = renderItem;
  8853. } else {
  8854. renderItem.id = object.id;
  8855. renderItem.object = object;
  8856. renderItem.geometry = geometry;
  8857. renderItem.material = material;
  8858. renderItem.groupOrder = groupOrder;
  8859. renderItem.renderOrder = object.renderOrder;
  8860. renderItem.z = z;
  8861. renderItem.group = group;
  8862. renderItem.clippingContext = clippingContext;
  8863. }
  8864. this.renderItemsIndex ++;
  8865. return renderItem;
  8866. }
  8867. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  8868. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  8869. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  8870. if ( material.transparent === true || material.transmission > 0 ) {
  8871. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  8872. this.transparent.push( renderItem );
  8873. } else {
  8874. this.opaque.push( renderItem );
  8875. }
  8876. }
  8877. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  8878. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  8879. if ( material.transparent === true || material.transmission > 0 ) {
  8880. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  8881. this.transparent.unshift( renderItem );
  8882. } else {
  8883. this.opaque.unshift( renderItem );
  8884. }
  8885. }
  8886. pushBundle( group ) {
  8887. this.bundles.push( group );
  8888. }
  8889. pushLight( light ) {
  8890. this.lightsArray.push( light );
  8891. }
  8892. sort( customOpaqueSort, customTransparentSort ) {
  8893. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  8894. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  8895. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  8896. }
  8897. finish() {
  8898. // update lights
  8899. this.lightsNode.setLights( this.lightsArray );
  8900. // Clear references from inactive renderItems in the list
  8901. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  8902. const renderItem = this.renderItems[ i ];
  8903. if ( renderItem.id === null ) break;
  8904. renderItem.id = null;
  8905. renderItem.object = null;
  8906. renderItem.geometry = null;
  8907. renderItem.material = null;
  8908. renderItem.groupOrder = null;
  8909. renderItem.renderOrder = null;
  8910. renderItem.z = null;
  8911. renderItem.group = null;
  8912. renderItem.clippingContext = null;
  8913. }
  8914. }
  8915. }
  8916. class RenderLists {
  8917. constructor( lighting ) {
  8918. this.lighting = lighting;
  8919. this.lists = new ChainMap();
  8920. }
  8921. get( scene, camera ) {
  8922. const lists = this.lists;
  8923. const keys = [ scene, camera ];
  8924. let list = lists.get( keys );
  8925. if ( list === undefined ) {
  8926. list = new RenderList( this.lighting, scene, camera );
  8927. lists.set( keys, list );
  8928. }
  8929. return list;
  8930. }
  8931. dispose() {
  8932. this.lists = new ChainMap();
  8933. }
  8934. }
  8935. let id$1 = 0;
  8936. class RenderContext {
  8937. constructor() {
  8938. this.id = id$1 ++;
  8939. this.color = true;
  8940. this.clearColor = true;
  8941. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  8942. this.depth = true;
  8943. this.clearDepth = true;
  8944. this.clearDepthValue = 1;
  8945. this.stencil = false;
  8946. this.clearStencil = true;
  8947. this.clearStencilValue = 1;
  8948. this.viewport = false;
  8949. this.viewportValue = new Vector4();
  8950. this.scissor = false;
  8951. this.scissorValue = new Vector4();
  8952. this.textures = null;
  8953. this.depthTexture = null;
  8954. this.activeCubeFace = 0;
  8955. this.sampleCount = 1;
  8956. this.width = 0;
  8957. this.height = 0;
  8958. this.isRenderContext = true;
  8959. }
  8960. getCacheKey() {
  8961. return getCacheKey( this );
  8962. }
  8963. }
  8964. function getCacheKey( renderContext ) {
  8965. const { textures, activeCubeFace } = renderContext;
  8966. const values = [ activeCubeFace ];
  8967. for ( const texture of textures ) {
  8968. values.push( texture.id );
  8969. }
  8970. return hashArray( values );
  8971. }
  8972. class RenderContexts {
  8973. constructor() {
  8974. this.chainMaps = {};
  8975. }
  8976. get( scene, camera, renderTarget = null ) {
  8977. const chainKey = [ scene, camera ];
  8978. let attachmentState;
  8979. if ( renderTarget === null ) {
  8980. attachmentState = 'default';
  8981. } else {
  8982. const format = renderTarget.texture.format;
  8983. const count = renderTarget.textures.length;
  8984. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  8985. }
  8986. const chainMap = this.getChainMap( attachmentState );
  8987. let renderState = chainMap.get( chainKey );
  8988. if ( renderState === undefined ) {
  8989. renderState = new RenderContext();
  8990. chainMap.set( chainKey, renderState );
  8991. }
  8992. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  8993. return renderState;
  8994. }
  8995. getChainMap( attachmentState ) {
  8996. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  8997. }
  8998. dispose() {
  8999. this.chainMaps = {};
  9000. }
  9001. }
  9002. const _size$3 = /*@__PURE__*/ new Vector3();
  9003. class Textures extends DataMap {
  9004. constructor( renderer, backend, info ) {
  9005. super();
  9006. this.renderer = renderer;
  9007. this.backend = backend;
  9008. this.info = info;
  9009. }
  9010. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  9011. const renderTargetData = this.get( renderTarget );
  9012. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  9013. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  9014. const textures = renderTarget.textures;
  9015. const size = this.getSize( textures[ 0 ] );
  9016. const mipWidth = size.width >> activeMipmapLevel;
  9017. const mipHeight = size.height >> activeMipmapLevel;
  9018. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  9019. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  9020. let textureNeedsUpdate = false;
  9021. if ( depthTexture === undefined && useDepthTexture ) {
  9022. depthTexture = new DepthTexture();
  9023. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  9024. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  9025. depthTexture.image.width = mipWidth;
  9026. depthTexture.image.height = mipHeight;
  9027. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  9028. }
  9029. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  9030. textureNeedsUpdate = true;
  9031. if ( depthTexture ) {
  9032. depthTexture.needsUpdate = true;
  9033. depthTexture.image.width = mipWidth;
  9034. depthTexture.image.height = mipHeight;
  9035. }
  9036. }
  9037. renderTargetData.width = size.width;
  9038. renderTargetData.height = size.height;
  9039. renderTargetData.textures = textures;
  9040. renderTargetData.depthTexture = depthTexture || null;
  9041. renderTargetData.depth = renderTarget.depthBuffer;
  9042. renderTargetData.stencil = renderTarget.stencilBuffer;
  9043. renderTargetData.renderTarget = renderTarget;
  9044. if ( renderTargetData.sampleCount !== sampleCount ) {
  9045. textureNeedsUpdate = true;
  9046. if ( depthTexture ) {
  9047. depthTexture.needsUpdate = true;
  9048. }
  9049. renderTargetData.sampleCount = sampleCount;
  9050. }
  9051. //
  9052. const options = { sampleCount };
  9053. for ( let i = 0; i < textures.length; i ++ ) {
  9054. const texture = textures[ i ];
  9055. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  9056. this.updateTexture( texture, options );
  9057. }
  9058. if ( depthTexture ) {
  9059. this.updateTexture( depthTexture, options );
  9060. }
  9061. // dispose handler
  9062. if ( renderTargetData.initialized !== true ) {
  9063. renderTargetData.initialized = true;
  9064. // dispose
  9065. const onDispose = () => {
  9066. renderTarget.removeEventListener( 'dispose', onDispose );
  9067. for ( let i = 0; i < textures.length; i ++ ) {
  9068. this._destroyTexture( textures[ i ] );
  9069. }
  9070. if ( depthTexture ) {
  9071. this._destroyTexture( depthTexture );
  9072. }
  9073. this.delete( renderTarget );
  9074. };
  9075. renderTarget.addEventListener( 'dispose', onDispose );
  9076. }
  9077. }
  9078. updateTexture( texture, options = {} ) {
  9079. const textureData = this.get( texture );
  9080. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  9081. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  9082. const backend = this.backend;
  9083. if ( isRenderTarget && textureData.initialized === true ) {
  9084. // it's an update
  9085. backend.destroySampler( texture );
  9086. backend.destroyTexture( texture );
  9087. }
  9088. //
  9089. if ( texture.isFramebufferTexture ) {
  9090. const renderTarget = this.renderer.getRenderTarget();
  9091. if ( renderTarget ) {
  9092. texture.type = renderTarget.texture.type;
  9093. } else {
  9094. texture.type = UnsignedByteType;
  9095. }
  9096. }
  9097. //
  9098. const { width, height, depth } = this.getSize( texture );
  9099. options.width = width;
  9100. options.height = height;
  9101. options.depth = depth;
  9102. options.needsMipmaps = this.needsMipmaps( texture );
  9103. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  9104. //
  9105. if ( isRenderTarget || texture.isStorageTexture === true ) {
  9106. backend.createSampler( texture );
  9107. backend.createTexture( texture, options );
  9108. textureData.generation = texture.version;
  9109. } else {
  9110. const needsCreate = textureData.initialized !== true;
  9111. if ( needsCreate ) backend.createSampler( texture );
  9112. if ( texture.version > 0 ) {
  9113. const image = texture.image;
  9114. if ( image === undefined ) {
  9115. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  9116. } else if ( image.complete === false ) {
  9117. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  9118. } else {
  9119. if ( texture.images ) {
  9120. const images = [];
  9121. for ( const image of texture.images ) {
  9122. images.push( image );
  9123. }
  9124. options.images = images;
  9125. } else {
  9126. options.image = image;
  9127. }
  9128. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  9129. backend.createTexture( texture, options );
  9130. textureData.isDefaultTexture = false;
  9131. textureData.generation = texture.version;
  9132. }
  9133. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  9134. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  9135. }
  9136. } else {
  9137. // async update
  9138. backend.createDefaultTexture( texture );
  9139. textureData.isDefaultTexture = true;
  9140. textureData.generation = texture.version;
  9141. }
  9142. }
  9143. // dispose handler
  9144. if ( textureData.initialized !== true ) {
  9145. textureData.initialized = true;
  9146. textureData.generation = texture.version;
  9147. //
  9148. this.info.memory.textures ++;
  9149. // dispose
  9150. const onDispose = () => {
  9151. texture.removeEventListener( 'dispose', onDispose );
  9152. this._destroyTexture( texture );
  9153. this.info.memory.textures --;
  9154. };
  9155. texture.addEventListener( 'dispose', onDispose );
  9156. }
  9157. //
  9158. textureData.version = texture.version;
  9159. }
  9160. getSize( texture, target = _size$3 ) {
  9161. let image = texture.images ? texture.images[ 0 ] : texture.image;
  9162. if ( image ) {
  9163. if ( image.image !== undefined ) image = image.image;
  9164. target.width = image.width || 1;
  9165. target.height = image.height || 1;
  9166. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  9167. } else {
  9168. target.width = target.height = target.depth = 1;
  9169. }
  9170. return target;
  9171. }
  9172. getMipLevels( texture, width, height ) {
  9173. let mipLevelCount;
  9174. if ( texture.isCompressedTexture ) {
  9175. if ( texture.mipmaps ) {
  9176. mipLevelCount = texture.mipmaps.length;
  9177. } else {
  9178. mipLevelCount = 1;
  9179. }
  9180. } else {
  9181. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  9182. }
  9183. return mipLevelCount;
  9184. }
  9185. needsMipmaps( texture ) {
  9186. return this.isEnvironmentTexture( texture ) || texture.isCompressedTexture === true || texture.generateMipmaps;
  9187. }
  9188. isEnvironmentTexture( texture ) {
  9189. const mapping = texture.mapping;
  9190. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  9191. }
  9192. _destroyTexture( texture ) {
  9193. this.backend.destroySampler( texture );
  9194. this.backend.destroyTexture( texture );
  9195. this.delete( texture );
  9196. }
  9197. }
  9198. class Color4 extends Color {
  9199. constructor( r, g, b, a = 1 ) {
  9200. super( r, g, b );
  9201. this.a = a;
  9202. }
  9203. set( r, g, b, a = 1 ) {
  9204. this.a = a;
  9205. return super.set( r, g, b );
  9206. }
  9207. copy( color ) {
  9208. if ( color.a !== undefined ) this.a = color.a;
  9209. return super.copy( color );
  9210. }
  9211. clone() {
  9212. return new this.constructor( this.r, this.g, this.b, this.a );
  9213. }
  9214. }
  9215. class ParameterNode extends PropertyNode {
  9216. static get type() {
  9217. return 'ParameterNode';
  9218. }
  9219. constructor( nodeType, name = null ) {
  9220. super( nodeType, name );
  9221. this.isParameterNode = true;
  9222. }
  9223. getHash() {
  9224. return this.uuid;
  9225. }
  9226. generate() {
  9227. return this.name;
  9228. }
  9229. }
  9230. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  9231. class StackNode extends Node {
  9232. static get type() {
  9233. return 'StackNode';
  9234. }
  9235. constructor( parent = null ) {
  9236. super();
  9237. this.nodes = [];
  9238. this.outputNode = null;
  9239. this.parent = parent;
  9240. this._currentCond = null;
  9241. this.isStackNode = true;
  9242. }
  9243. getNodeType( builder ) {
  9244. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  9245. }
  9246. add( node ) {
  9247. this.nodes.push( node );
  9248. return this;
  9249. }
  9250. If( boolNode, method ) {
  9251. const methodNode = new ShaderNode( method );
  9252. this._currentCond = select( boolNode, methodNode );
  9253. return this.add( this._currentCond );
  9254. }
  9255. ElseIf( boolNode, method ) {
  9256. const methodNode = new ShaderNode( method );
  9257. const ifNode = select( boolNode, methodNode );
  9258. this._currentCond.elseNode = ifNode;
  9259. this._currentCond = ifNode;
  9260. return this;
  9261. }
  9262. Else( method ) {
  9263. this._currentCond.elseNode = new ShaderNode( method );
  9264. return this;
  9265. }
  9266. build( builder, ...params ) {
  9267. const previousStack = getCurrentStack();
  9268. setCurrentStack( this );
  9269. for ( const node of this.nodes ) {
  9270. node.build( builder, 'void' );
  9271. }
  9272. setCurrentStack( previousStack );
  9273. return this.outputNode ? this.outputNode.build( builder, ...params ) : super.build( builder, ...params );
  9274. }
  9275. //
  9276. else( ...params ) { // @deprecated, r168
  9277. console.warn( 'TSL.StackNode: .else() has been renamed to .Else().' );
  9278. return this.Else( ...params );
  9279. }
  9280. elseif( ...params ) { // @deprecated, r168
  9281. console.warn( 'TSL.StackNode: .elseif() has been renamed to .ElseIf().' );
  9282. return this.ElseIf( ...params );
  9283. }
  9284. }
  9285. const stack = /*@__PURE__*/ nodeProxy( StackNode );
  9286. class StructTypeNode extends Node {
  9287. static get type() {
  9288. return 'StructTypeNode';
  9289. }
  9290. constructor( types ) {
  9291. super();
  9292. this.types = types;
  9293. this.isStructTypeNode = true;
  9294. }
  9295. getMemberTypes() {
  9296. return this.types;
  9297. }
  9298. }
  9299. class OutputStructNode extends Node {
  9300. static get type() {
  9301. return 'OutputStructNode';
  9302. }
  9303. constructor( ...members ) {
  9304. super();
  9305. this.members = members;
  9306. this.isOutputStructNode = true;
  9307. }
  9308. setup( builder ) {
  9309. super.setup( builder );
  9310. const members = this.members;
  9311. const types = [];
  9312. for ( let i = 0; i < members.length; i ++ ) {
  9313. types.push( members[ i ].getNodeType( builder ) );
  9314. }
  9315. this.nodeType = builder.getStructTypeFromNode( new StructTypeNode( types ) ).name;
  9316. }
  9317. generate( builder, output ) {
  9318. const propertyName = builder.getOutputStructName();
  9319. const members = this.members;
  9320. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  9321. for ( let i = 0; i < members.length; i ++ ) {
  9322. const snippet = members[ i ].build( builder, output );
  9323. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  9324. }
  9325. return propertyName;
  9326. }
  9327. }
  9328. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  9329. function getTextureIndex( textures, name ) {
  9330. for ( let i = 0; i < textures.length; i ++ ) {
  9331. if ( textures[ i ].name === name ) {
  9332. return i;
  9333. }
  9334. }
  9335. return - 1;
  9336. }
  9337. class MRTNode extends OutputStructNode {
  9338. static get type() {
  9339. return 'MRTNode';
  9340. }
  9341. constructor( outputNodes ) {
  9342. super();
  9343. this.outputNodes = outputNodes;
  9344. this.isMRTNode = true;
  9345. }
  9346. has( name ) {
  9347. return this.outputNodes[ name ] !== undefined;
  9348. }
  9349. get( name ) {
  9350. return this.outputNodes[ name ];
  9351. }
  9352. merge( mrtNode ) {
  9353. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  9354. return mrt( outputs );
  9355. }
  9356. setup( builder ) {
  9357. const outputNodes = this.outputNodes;
  9358. const mrt = builder.renderer.getRenderTarget();
  9359. const members = [];
  9360. const textures = mrt.textures;
  9361. for ( const name in outputNodes ) {
  9362. const index = getTextureIndex( textures, name );
  9363. members[ index ] = vec4( outputNodes[ name ] );
  9364. }
  9365. this.members = members;
  9366. return super.setup( builder );
  9367. }
  9368. }
  9369. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  9370. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  9371. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  9372. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  9373. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  9374. const result = word.shiftRight( 22 ).bitXor( word );
  9375. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  9376. } );
  9377. // remapping functions https://iquilezles.org/articles/functions/
  9378. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  9379. 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 ) );
  9380. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  9381. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  9382. // https://github.com/cabbibo/glsl-tri-noise-3d
  9383. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  9384. return x.fract().sub( .5 ).abs();
  9385. } ).setLayout( {
  9386. name: 'tri',
  9387. type: 'float',
  9388. inputs: [
  9389. { name: 'x', type: 'float' }
  9390. ]
  9391. } );
  9392. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  9393. 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. ) ) ) ) );
  9394. } ).setLayout( {
  9395. name: 'tri3',
  9396. type: 'vec3',
  9397. inputs: [
  9398. { name: 'p', type: 'vec3' }
  9399. ]
  9400. } );
  9401. const triNoise3D = /*@__PURE__*/ Fn( ( [ p_immutable, spd, time ] ) => {
  9402. const p = vec3( p_immutable ).toVar();
  9403. const z = float( 1.4 ).toVar();
  9404. const rz = float( 0.0 ).toVar();
  9405. const bp = vec3( p ).toVar();
  9406. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  9407. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  9408. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( spd ) ) ) );
  9409. bp.mulAssign( 1.8 );
  9410. z.mulAssign( 1.5 );
  9411. p.mulAssign( 1.2 );
  9412. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  9413. rz.addAssign( t.div( z ) );
  9414. bp.addAssign( 0.14 );
  9415. } );
  9416. return rz;
  9417. } ).setLayout( {
  9418. name: 'triNoise3D',
  9419. type: 'float',
  9420. inputs: [
  9421. { name: 'p', type: 'vec3' },
  9422. { name: 'spd', type: 'float' },
  9423. { name: 'time', type: 'float' }
  9424. ]
  9425. } );
  9426. class FunctionOverloadingNode extends Node {
  9427. static get type() {
  9428. return 'FunctionOverloadingNode';
  9429. }
  9430. constructor( functionNodes = [], ...parametersNodes ) {
  9431. super();
  9432. this.functionNodes = functionNodes;
  9433. this.parametersNodes = parametersNodes;
  9434. this._candidateFnCall = null;
  9435. this.global = true;
  9436. }
  9437. getNodeType() {
  9438. return this.functionNodes[ 0 ].shaderNode.layout.type;
  9439. }
  9440. setup( builder ) {
  9441. const params = this.parametersNodes;
  9442. let candidateFnCall = this._candidateFnCall;
  9443. if ( candidateFnCall === null ) {
  9444. let candidateFn = null;
  9445. let candidateScore = - 1;
  9446. for ( const functionNode of this.functionNodes ) {
  9447. const shaderNode = functionNode.shaderNode;
  9448. const layout = shaderNode.layout;
  9449. if ( layout === null ) {
  9450. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  9451. }
  9452. const inputs = layout.inputs;
  9453. if ( params.length === inputs.length ) {
  9454. let score = 0;
  9455. for ( let i = 0; i < params.length; i ++ ) {
  9456. const param = params[ i ];
  9457. const input = inputs[ i ];
  9458. if ( param.getNodeType( builder ) === input.type ) {
  9459. score ++;
  9460. } else {
  9461. score = 0;
  9462. }
  9463. }
  9464. if ( score > candidateScore ) {
  9465. candidateFn = functionNode;
  9466. candidateScore = score;
  9467. }
  9468. }
  9469. }
  9470. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  9471. }
  9472. return candidateFnCall;
  9473. }
  9474. }
  9475. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  9476. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  9477. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  9478. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  9479. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  9480. // Deprecated
  9481. const timerLocal = ( timeScale = 1 ) => { // @deprecated, r170
  9482. console.warn( 'TSL: timerLocal() is deprecated. Use "time" instead.' );
  9483. return time.mul( timeScale );
  9484. };
  9485. const timerGlobal = ( timeScale = 1 ) => { // @deprecated, r170
  9486. console.warn( 'TSL: timerGlobal() is deprecated. Use "time" instead.' );
  9487. return time.mul( timeScale );
  9488. };
  9489. const timerDelta = ( timeScale = 1 ) => { // @deprecated, r170
  9490. console.warn( 'TSL: timerDelta() is deprecated. Use "deltaTime" instead.' );
  9491. return deltaTime.mul( timeScale );
  9492. };
  9493. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  9494. const oscSquare = ( t = time ) => t.fract().round();
  9495. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  9496. const oscSawtooth = ( t = time ) => t.fract();
  9497. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  9498. return rotate( uv.sub( center ), rotation ).add( center );
  9499. } );
  9500. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  9501. const delta = uv.sub( center );
  9502. const delta2 = delta.dot( delta );
  9503. const delta4 = delta2.mul( delta2 );
  9504. const deltaOffset = delta4.mul( strength );
  9505. return uv.add( delta.mul( deltaOffset ) );
  9506. } );
  9507. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  9508. let worldMatrix;
  9509. if ( position !== null ) {
  9510. worldMatrix = modelWorldMatrix.toVar();
  9511. worldMatrix[ 3 ][ 0 ] = position.x;
  9512. worldMatrix[ 3 ][ 1 ] = position.y;
  9513. worldMatrix[ 3 ][ 2 ] = position.z;
  9514. } else {
  9515. worldMatrix = modelWorldMatrix;
  9516. }
  9517. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  9518. if ( defined( horizontal ) ) {
  9519. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  9520. modelViewMatrix[ 0 ][ 1 ] = 0;
  9521. modelViewMatrix[ 0 ][ 2 ] = 0;
  9522. }
  9523. if ( defined( vertical ) ) {
  9524. modelViewMatrix[ 1 ][ 0 ] = 0;
  9525. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  9526. modelViewMatrix[ 1 ][ 2 ] = 0;
  9527. }
  9528. modelViewMatrix[ 2 ][ 0 ] = 0;
  9529. modelViewMatrix[ 2 ][ 1 ] = 0;
  9530. modelViewMatrix[ 2 ][ 2 ] = 1;
  9531. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  9532. } );
  9533. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  9534. const depth = linearDepth();
  9535. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  9536. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  9537. return finalUV;
  9538. } );
  9539. class SpriteSheetUVNode extends Node {
  9540. static get type() {
  9541. return 'SpriteSheetUVNode';
  9542. }
  9543. constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) {
  9544. super( 'vec2' );
  9545. this.countNode = countNode;
  9546. this.uvNode = uvNode;
  9547. this.frameNode = frameNode;
  9548. }
  9549. setup() {
  9550. const { frameNode, uvNode, countNode } = this;
  9551. const { width, height } = countNode;
  9552. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  9553. const column = frameNum.mod( width );
  9554. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  9555. const scale = countNode.reciprocal();
  9556. const uvFrameOffset = vec2( column, row );
  9557. return uvNode.add( uvFrameOffset ).mul( scale );
  9558. }
  9559. }
  9560. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode );
  9561. class TriplanarTexturesNode extends Node {
  9562. static get type() {
  9563. return 'TriplanarTexturesNode';
  9564. }
  9565. constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) {
  9566. super( 'vec4' );
  9567. this.textureXNode = textureXNode;
  9568. this.textureYNode = textureYNode;
  9569. this.textureZNode = textureZNode;
  9570. this.scaleNode = scaleNode;
  9571. this.positionNode = positionNode;
  9572. this.normalNode = normalNode;
  9573. }
  9574. setup() {
  9575. const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this;
  9576. // Ref: https://github.com/keijiro/StandardTriplanar
  9577. // Blending factor of triplanar mapping
  9578. let bf = normalNode.abs().normalize();
  9579. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  9580. // Triplanar mapping
  9581. const tx = positionNode.yz.mul( scaleNode );
  9582. const ty = positionNode.zx.mul( scaleNode );
  9583. const tz = positionNode.xy.mul( scaleNode );
  9584. // Base color
  9585. const textureX = textureXNode.value;
  9586. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  9587. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  9588. const cx = texture( textureX, tx ).mul( bf.x );
  9589. const cy = texture( textureY, ty ).mul( bf.y );
  9590. const cz = texture( textureZ, tz ).mul( bf.z );
  9591. return add( cx, cy, cz );
  9592. }
  9593. }
  9594. const triplanarTextures = /*@__PURE__*/ nodeProxy( TriplanarTexturesNode );
  9595. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  9596. const _reflectorPlane = new Plane();
  9597. const _normal = new Vector3();
  9598. const _reflectorWorldPosition = new Vector3();
  9599. const _cameraWorldPosition = new Vector3();
  9600. const _rotationMatrix = new Matrix4();
  9601. const _lookAtPosition = new Vector3( 0, 0, - 1 );
  9602. const clipPlane = new Vector4();
  9603. const _view = new Vector3();
  9604. const _target = new Vector3();
  9605. const _q = new Vector4();
  9606. const _size$2 = new Vector2();
  9607. const _defaultRT = new RenderTarget();
  9608. const _defaultUV = screenUV.flipX();
  9609. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  9610. let _inReflector = false;
  9611. class ReflectorNode extends TextureNode {
  9612. static get type() {
  9613. return 'ReflectorNode';
  9614. }
  9615. constructor( parameters = {} ) {
  9616. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  9617. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  9618. this._depthNode = null;
  9619. this.setUpdateMatrix( false );
  9620. }
  9621. get reflector() {
  9622. return this._reflectorBaseNode;
  9623. }
  9624. get target() {
  9625. return this._reflectorBaseNode.target;
  9626. }
  9627. getDepthNode() {
  9628. if ( this._depthNode === null ) {
  9629. if ( this._reflectorBaseNode.depth !== true ) {
  9630. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  9631. }
  9632. this._depthNode = nodeObject( new ReflectorNode( {
  9633. defaultTexture: _defaultRT.depthTexture,
  9634. reflector: this._reflectorBaseNode
  9635. } ) );
  9636. }
  9637. return this._depthNode;
  9638. }
  9639. setup( builder ) {
  9640. // ignore if used in post-processing
  9641. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  9642. return super.setup( builder );
  9643. }
  9644. clone() {
  9645. const texture = new this.constructor( this.reflectorNode );
  9646. texture._reflectorBaseNode = this._reflectorBaseNode;
  9647. return texture;
  9648. }
  9649. }
  9650. class ReflectorBaseNode extends Node {
  9651. static get type() {
  9652. return 'ReflectorBaseNode';
  9653. }
  9654. constructor( textureNode, parameters = {} ) {
  9655. super();
  9656. const {
  9657. target = new Object3D(),
  9658. resolution = 1,
  9659. generateMipmaps = false,
  9660. bounces = true,
  9661. depth = false
  9662. } = parameters;
  9663. //
  9664. this.textureNode = textureNode;
  9665. this.target = target;
  9666. this.resolution = resolution;
  9667. this.generateMipmaps = generateMipmaps;
  9668. this.bounces = bounces;
  9669. this.depth = depth;
  9670. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  9671. this.virtualCameras = new WeakMap();
  9672. this.renderTargets = new WeakMap();
  9673. }
  9674. _updateResolution( renderTarget, renderer ) {
  9675. const resolution = this.resolution;
  9676. renderer.getDrawingBufferSize( _size$2 );
  9677. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  9678. }
  9679. setup( builder ) {
  9680. this._updateResolution( _defaultRT, builder.renderer );
  9681. return super.setup( builder );
  9682. }
  9683. getVirtualCamera( camera ) {
  9684. let virtualCamera = this.virtualCameras.get( camera );
  9685. if ( virtualCamera === undefined ) {
  9686. virtualCamera = camera.clone();
  9687. this.virtualCameras.set( camera, virtualCamera );
  9688. }
  9689. return virtualCamera;
  9690. }
  9691. getRenderTarget( camera ) {
  9692. let renderTarget = this.renderTargets.get( camera );
  9693. if ( renderTarget === undefined ) {
  9694. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } );
  9695. if ( this.generateMipmaps === true ) {
  9696. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  9697. renderTarget.texture.generateMipmaps = true;
  9698. }
  9699. if ( this.depth === true ) {
  9700. renderTarget.depthTexture = new DepthTexture();
  9701. }
  9702. this.renderTargets.set( camera, renderTarget );
  9703. }
  9704. return renderTarget;
  9705. }
  9706. updateBefore( frame ) {
  9707. if ( this.bounces === false && _inReflector ) return;
  9708. _inReflector = true;
  9709. const { scene, camera, renderer, material } = frame;
  9710. const { target } = this;
  9711. const virtualCamera = this.getVirtualCamera( camera );
  9712. const renderTarget = this.getRenderTarget( virtualCamera );
  9713. renderer.getDrawingBufferSize( _size$2 );
  9714. this._updateResolution( renderTarget, renderer );
  9715. //
  9716. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  9717. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  9718. _rotationMatrix.extractRotation( target.matrixWorld );
  9719. _normal.set( 0, 0, 1 );
  9720. _normal.applyMatrix4( _rotationMatrix );
  9721. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  9722. // Avoid rendering when reflector is facing away
  9723. if ( _view.dot( _normal ) > 0 ) return;
  9724. _view.reflect( _normal ).negate();
  9725. _view.add( _reflectorWorldPosition );
  9726. _rotationMatrix.extractRotation( camera.matrixWorld );
  9727. _lookAtPosition.set( 0, 0, - 1 );
  9728. _lookAtPosition.applyMatrix4( _rotationMatrix );
  9729. _lookAtPosition.add( _cameraWorldPosition );
  9730. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  9731. _target.reflect( _normal ).negate();
  9732. _target.add( _reflectorWorldPosition );
  9733. //
  9734. virtualCamera.coordinateSystem = camera.coordinateSystem;
  9735. virtualCamera.position.copy( _view );
  9736. virtualCamera.up.set( 0, 1, 0 );
  9737. virtualCamera.up.applyMatrix4( _rotationMatrix );
  9738. virtualCamera.up.reflect( _normal );
  9739. virtualCamera.lookAt( _target );
  9740. virtualCamera.near = camera.near;
  9741. virtualCamera.far = camera.far;
  9742. virtualCamera.updateMatrixWorld();
  9743. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  9744. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  9745. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  9746. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  9747. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  9748. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  9749. const projectionMatrix = virtualCamera.projectionMatrix;
  9750. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  9751. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  9752. _q.z = - 1.0;
  9753. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  9754. // Calculate the scaled plane vector
  9755. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  9756. const clipBias = 0;
  9757. // Replacing the third row of the projection matrix
  9758. projectionMatrix.elements[ 2 ] = clipPlane.x;
  9759. projectionMatrix.elements[ 6 ] = clipPlane.y;
  9760. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  9761. projectionMatrix.elements[ 14 ] = clipPlane.w;
  9762. //
  9763. this.textureNode.value = renderTarget.texture;
  9764. if ( this.depth === true ) {
  9765. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  9766. }
  9767. material.visible = false;
  9768. const currentRenderTarget = renderer.getRenderTarget();
  9769. const currentMRT = renderer.getMRT();
  9770. renderer.setMRT( null );
  9771. renderer.setRenderTarget( renderTarget );
  9772. renderer.render( scene, virtualCamera );
  9773. renderer.setMRT( currentMRT );
  9774. renderer.setRenderTarget( currentRenderTarget );
  9775. material.visible = true;
  9776. _inReflector = false;
  9777. }
  9778. }
  9779. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  9780. // Helper for passes that need to fill the viewport with a single quad.
  9781. const _camera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  9782. // https://github.com/mrdoob/three.js/pull/21358
  9783. class QuadGeometry extends BufferGeometry {
  9784. constructor( flipY = false ) {
  9785. super();
  9786. const uv = flipY === false ? [ 0, - 1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  9787. this.setAttribute( 'position', new Float32BufferAttribute( [ - 1, 3, 0, - 1, - 1, 0, 3, - 1, 0 ], 3 ) );
  9788. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  9789. }
  9790. }
  9791. const _geometry = /*@__PURE__*/ new QuadGeometry();
  9792. class QuadMesh extends Mesh {
  9793. constructor( material = null ) {
  9794. super( _geometry, material );
  9795. this.camera = _camera;
  9796. this.isQuadMesh = true;
  9797. }
  9798. renderAsync( renderer ) {
  9799. return renderer.renderAsync( this, _camera );
  9800. }
  9801. render( renderer ) {
  9802. renderer.render( this, _camera );
  9803. }
  9804. }
  9805. const _size$1 = /*@__PURE__*/ new Vector2();
  9806. class RTTNode extends TextureNode {
  9807. static get type() {
  9808. return 'RTTNode';
  9809. }
  9810. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  9811. const renderTarget = new RenderTarget( width, height, options );
  9812. super( renderTarget.texture, uv() );
  9813. this.node = node;
  9814. this.width = width;
  9815. this.height = height;
  9816. this.renderTarget = renderTarget;
  9817. this.textureNeedsUpdate = true;
  9818. this.autoUpdate = true;
  9819. this.updateMap = new WeakMap();
  9820. this._rttNode = null;
  9821. this._quadMesh = new QuadMesh( new NodeMaterial() );
  9822. this.updateBeforeType = NodeUpdateType.RENDER;
  9823. }
  9824. get autoSize() {
  9825. return this.width === null;
  9826. }
  9827. setup( builder ) {
  9828. this._rttNode = this.node.context( builder.getSharedContext() );
  9829. this._quadMesh.material.name = 'RTT';
  9830. this._quadMesh.material.needsUpdate = true;
  9831. return super.setup( builder );
  9832. }
  9833. setSize( width, height ) {
  9834. this.width = width;
  9835. this.height = height;
  9836. const effectiveWidth = width * this.pixelRatio;
  9837. const effectiveHeight = height * this.pixelRatio;
  9838. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  9839. this.textureNeedsUpdate = true;
  9840. }
  9841. setPixelRatio( pixelRatio ) {
  9842. this.pixelRatio = pixelRatio;
  9843. this.setSize( this.width, this.height );
  9844. }
  9845. updateBefore( { renderer } ) {
  9846. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  9847. this.textureNeedsUpdate = false;
  9848. //
  9849. if ( this.autoSize === true ) {
  9850. this.pixelRatio = renderer.getPixelRatio();
  9851. const size = renderer.getSize( _size$1 );
  9852. this.setSize( size.width, size.height );
  9853. }
  9854. //
  9855. this._quadMesh.material.fragmentNode = this._rttNode;
  9856. //
  9857. const currentRenderTarget = renderer.getRenderTarget();
  9858. renderer.setRenderTarget( this.renderTarget );
  9859. this._quadMesh.render( renderer );
  9860. renderer.setRenderTarget( currentRenderTarget );
  9861. }
  9862. clone() {
  9863. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  9864. newNode.sampler = this.sampler;
  9865. newNode.referenceNode = this;
  9866. return newNode;
  9867. }
  9868. }
  9869. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  9870. const convertToTexture = ( node, ...params ) => {
  9871. if ( node.isTextureNode ) return node;
  9872. if ( node.isPassNode ) return node.getTextureNode();
  9873. return rtt( node, ...params );
  9874. };
  9875. /**
  9876. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  9877. * depth value and the camera's inverse projection matrix.
  9878. *
  9879. * @param {vec2} screenPosition - The fragment's screen position expressed as uv coordinates.
  9880. * @param {float} depth - The fragment's depth value.
  9881. * @param {mat4} projectionMatrixInverse - The camera's inverse projection matrix.
  9882. * @return {vec3} The fragments position in view space.
  9883. */
  9884. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  9885. let clipSpacePosition;
  9886. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  9887. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  9888. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  9889. } else {
  9890. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  9891. }
  9892. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  9893. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  9894. } );
  9895. /**
  9896. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  9897. * and the camera's projection matrix
  9898. *
  9899. * @param {vec3} viewPosition - The fragments position in view space.
  9900. * @param {mat4} projectionMatrix - The camera's projection matrix.
  9901. * @return {vec2} The fragment's screen position expressed as uv coordinates.
  9902. */
  9903. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  9904. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  9905. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  9906. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  9907. } );
  9908. /**
  9909. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  9910. * target is available or if flat surface normals are required.
  9911. *
  9912. * @param {vec2} uv - The texture coordinate.
  9913. * @param {DepthTexture} depthTexture - The depth texture.
  9914. * @param {mat4} projectionMatrixInverse - The camera's inverse projection matrix.
  9915. * @return {vec3} The computed normal vector.
  9916. */
  9917. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  9918. const size = textureSize( textureLoad( depthTexture ) );
  9919. const p = ivec2( uv.mul( size ) ).toVar();
  9920. const c0 = textureLoad( depthTexture, p ).toVar();
  9921. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  9922. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  9923. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  9924. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  9925. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  9926. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  9927. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  9928. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  9929. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  9930. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  9931. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  9932. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  9933. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  9934. 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 ) ) );
  9935. 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 ) ) );
  9936. return normalize( cross( dpdx, dpdy ) );
  9937. } );
  9938. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  9939. constructor( array, itemSize, typeClass = Float32Array ) {
  9940. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  9941. super( array, itemSize );
  9942. this.isStorageInstancedBufferAttribute = true;
  9943. }
  9944. }
  9945. class StorageBufferAttribute extends BufferAttribute {
  9946. constructor( array, itemSize, typeClass = Float32Array ) {
  9947. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  9948. super( array, itemSize );
  9949. this.isStorageBufferAttribute = true;
  9950. }
  9951. }
  9952. class StorageArrayElementNode extends ArrayElementNode {
  9953. static get type() {
  9954. return 'StorageArrayElementNode';
  9955. }
  9956. constructor( storageBufferNode, indexNode ) {
  9957. super( storageBufferNode, indexNode );
  9958. this.isStorageArrayElementNode = true;
  9959. }
  9960. set storageBufferNode( value ) {
  9961. this.node = value;
  9962. }
  9963. get storageBufferNode() {
  9964. return this.node;
  9965. }
  9966. setup( builder ) {
  9967. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  9968. if ( this.node.isPBO === true ) {
  9969. builder.setupPBO( this.node );
  9970. }
  9971. }
  9972. return super.setup( builder );
  9973. }
  9974. generate( builder, output ) {
  9975. let snippet;
  9976. const isAssignContext = builder.context.assign;
  9977. //
  9978. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  9979. if ( this.node.isPBO === true && isAssignContext !== true && ( this.node.value.isInstancedBufferAttribute || builder.shaderStage !== 'compute' ) ) {
  9980. snippet = builder.generatePBO( this );
  9981. } else {
  9982. snippet = this.node.build( builder );
  9983. }
  9984. } else {
  9985. snippet = super.generate( builder );
  9986. }
  9987. if ( isAssignContext !== true ) {
  9988. const type = this.getNodeType( builder );
  9989. snippet = builder.format( snippet, type, output );
  9990. }
  9991. return snippet;
  9992. }
  9993. }
  9994. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode );
  9995. class StorageBufferNode extends BufferNode {
  9996. static get type() {
  9997. return 'StorageBufferNode';
  9998. }
  9999. constructor( value, bufferType = null, bufferCount = 0 ) {
  10000. if ( bufferType === null && ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) ) {
  10001. bufferType = getTypeFromLength( value.itemSize );
  10002. bufferCount = value.count;
  10003. }
  10004. super( value, bufferType, bufferCount );
  10005. this.isStorageBufferNode = true;
  10006. this.access = NodeAccess.READ_WRITE;
  10007. this.isAtomic = false;
  10008. this.isPBO = false;
  10009. this.bufferCount = bufferCount;
  10010. this._attribute = null;
  10011. this._varying = null;
  10012. this.global = true;
  10013. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  10014. // TOOD: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  10015. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  10016. else value.isStorageBufferAttribute = true;
  10017. }
  10018. }
  10019. getHash( builder ) {
  10020. if ( this.bufferCount === 0 ) {
  10021. let bufferData = builder.globalCache.getData( this.value );
  10022. if ( bufferData === undefined ) {
  10023. bufferData = {
  10024. node: this
  10025. };
  10026. builder.globalCache.setData( this.value, bufferData );
  10027. }
  10028. return bufferData.node.uuid;
  10029. }
  10030. return this.uuid;
  10031. }
  10032. getInputType( /*builder*/ ) {
  10033. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  10034. }
  10035. element( indexNode ) {
  10036. return storageElement( this, indexNode );
  10037. }
  10038. setPBO( value ) {
  10039. this.isPBO = value;
  10040. return this;
  10041. }
  10042. getPBO() {
  10043. return this.isPBO;
  10044. }
  10045. setAccess( value ) {
  10046. this.access = value;
  10047. return this;
  10048. }
  10049. toReadOnly() {
  10050. return this.setAccess( NodeAccess.READ_ONLY );
  10051. }
  10052. setAtomic( value ) {
  10053. this.isAtomic = value;
  10054. return this;
  10055. }
  10056. toAtomic() {
  10057. return this.setAtomic( true );
  10058. }
  10059. getAttributeData() {
  10060. if ( this._attribute === null ) {
  10061. this._attribute = bufferAttribute( this.value );
  10062. this._varying = varying( this._attribute );
  10063. }
  10064. return {
  10065. attribute: this._attribute,
  10066. varying: this._varying
  10067. };
  10068. }
  10069. getNodeType( builder ) {
  10070. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  10071. return super.getNodeType( builder );
  10072. }
  10073. const { attribute } = this.getAttributeData();
  10074. return attribute.getNodeType( builder );
  10075. }
  10076. generate( builder ) {
  10077. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  10078. return super.generate( builder );
  10079. }
  10080. const { attribute, varying } = this.getAttributeData();
  10081. const output = varying.build( builder );
  10082. builder.registerTransform( output, attribute );
  10083. return output;
  10084. }
  10085. }
  10086. const storage = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ) );
  10087. const storageObject = ( value, type, count ) => { // @deprecated, r171
  10088. console.warn( 'THREE.TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.' );
  10089. return storage( value, type, count ).setPBO( true );
  10090. };
  10091. const attributeArray = ( count, type = 'float' ) => {
  10092. const itemSize = getLengthFromType( type );
  10093. const buffer = new StorageBufferAttribute( count, itemSize );
  10094. const node = storage( buffer, type, count );
  10095. return node;
  10096. };
  10097. const instancedArray = ( count, type = 'float' ) => {
  10098. const itemSize = getLengthFromType( type );
  10099. const buffer = new StorageInstancedBufferAttribute( count, itemSize );
  10100. const node = storage( buffer, type, count );
  10101. return node;
  10102. };
  10103. class VertexColorNode extends AttributeNode {
  10104. static get type() {
  10105. return 'VertexColorNode';
  10106. }
  10107. constructor( index = 0 ) {
  10108. super( null, 'vec4' );
  10109. this.isVertexColorNode = true;
  10110. this.index = index;
  10111. }
  10112. getAttributeName( /*builder*/ ) {
  10113. const index = this.index;
  10114. return 'color' + ( index > 0 ? index : '' );
  10115. }
  10116. generate( builder ) {
  10117. const attributeName = this.getAttributeName( builder );
  10118. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  10119. let result;
  10120. if ( geometryAttribute === true ) {
  10121. result = super.generate( builder );
  10122. } else {
  10123. // Vertex color fallback should be white
  10124. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  10125. }
  10126. return result;
  10127. }
  10128. serialize( data ) {
  10129. super.serialize( data );
  10130. data.index = this.index;
  10131. }
  10132. deserialize( data ) {
  10133. super.deserialize( data );
  10134. this.index = data.index;
  10135. }
  10136. }
  10137. const vertexColor = ( ...params ) => nodeObject( new VertexColorNode( ...params ) );
  10138. class PointUVNode extends Node {
  10139. static get type() {
  10140. return 'PointUVNode';
  10141. }
  10142. constructor() {
  10143. super( 'vec2' );
  10144. this.isPointUVNode = true;
  10145. }
  10146. generate( /*builder*/ ) {
  10147. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  10148. }
  10149. }
  10150. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  10151. const _e1 = /*@__PURE__*/ new Euler();
  10152. const _m1 = /*@__PURE__*/ new Matrix4();
  10153. class SceneNode extends Node {
  10154. static get type() {
  10155. return 'SceneNode';
  10156. }
  10157. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  10158. super();
  10159. this.scope = scope;
  10160. this.scene = scene;
  10161. }
  10162. setup( builder ) {
  10163. const scope = this.scope;
  10164. const scene = this.scene !== null ? this.scene : builder.scene;
  10165. let output;
  10166. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  10167. output = reference( 'backgroundBlurriness', 'float', scene );
  10168. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  10169. output = reference( 'backgroundIntensity', 'float', scene );
  10170. } else if ( scope === SceneNode.BACKGROUND_ROTATION ) {
  10171. output = uniform( 'mat4' ).label( 'backgroundRotation' ).setGroup( renderGroup ).onRenderUpdate( () => {
  10172. const background = scene.background;
  10173. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  10174. _e1.copy( scene.backgroundRotation );
  10175. // accommodate left-handed frame
  10176. _e1.x *= - 1; _e1.y *= - 1; _e1.z *= - 1;
  10177. _m1.makeRotationFromEuler( _e1 );
  10178. } else {
  10179. _m1.identity();
  10180. }
  10181. return _m1;
  10182. } );
  10183. } else {
  10184. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  10185. }
  10186. return output;
  10187. }
  10188. }
  10189. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  10190. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  10191. SceneNode.BACKGROUND_ROTATION = 'backgroundRotation';
  10192. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  10193. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  10194. const backgroundRotation = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_ROTATION );
  10195. class StorageTextureNode extends TextureNode {
  10196. static get type() {
  10197. return 'StorageTextureNode';
  10198. }
  10199. constructor( value, uvNode, storeNode = null ) {
  10200. super( value, uvNode );
  10201. this.storeNode = storeNode;
  10202. this.isStorageTextureNode = true;
  10203. this.access = NodeAccess.WRITE_ONLY;
  10204. }
  10205. getInputType( /*builder*/ ) {
  10206. return 'storageTexture';
  10207. }
  10208. setup( builder ) {
  10209. super.setup( builder );
  10210. const properties = builder.getNodeProperties( this );
  10211. properties.storeNode = this.storeNode;
  10212. }
  10213. setAccess( value ) {
  10214. this.access = value;
  10215. return this;
  10216. }
  10217. generate( builder, output ) {
  10218. let snippet;
  10219. if ( this.storeNode !== null ) {
  10220. snippet = this.generateStore( builder );
  10221. } else {
  10222. snippet = super.generate( builder, output );
  10223. }
  10224. return snippet;
  10225. }
  10226. toReadWrite() {
  10227. return this.setAccess( NodeAccess.READ_WRITE );
  10228. }
  10229. toReadOnly() {
  10230. return this.setAccess( NodeAccess.READ_ONLY );
  10231. }
  10232. toWriteOnly() {
  10233. return this.setAccess( NodeAccess.WRITE_ONLY );
  10234. }
  10235. generateStore( builder ) {
  10236. const properties = builder.getNodeProperties( this );
  10237. const { uvNode, storeNode } = properties;
  10238. const textureProperty = super.generate( builder, 'property' );
  10239. const uvSnippet = uvNode.build( builder, 'uvec2' );
  10240. const storeSnippet = storeNode.build( builder, 'vec4' );
  10241. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, storeSnippet );
  10242. builder.addLineFlowCode( snippet, this );
  10243. }
  10244. }
  10245. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode );
  10246. const textureStore = ( value, uvNode, storeNode ) => {
  10247. const node = storageTexture( value, uvNode, storeNode );
  10248. if ( storeNode !== null ) node.append();
  10249. return node;
  10250. };
  10251. class UserDataNode extends ReferenceNode {
  10252. static get type() {
  10253. return 'UserDataNode';
  10254. }
  10255. constructor( property, inputType, userData = null ) {
  10256. super( property, inputType, userData );
  10257. this.userData = userData;
  10258. }
  10259. updateReference( state ) {
  10260. this.reference = this.userData !== null ? this.userData : state.object.userData;
  10261. return this.reference;
  10262. }
  10263. }
  10264. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  10265. const _objectData = new WeakMap();
  10266. class VelocityNode extends TempNode {
  10267. static get type() {
  10268. return 'VelocityNode';
  10269. }
  10270. constructor() {
  10271. super( 'vec2' );
  10272. this.projectionMatrix = null;
  10273. this.updateType = NodeUpdateType.OBJECT;
  10274. this.updateAfterType = NodeUpdateType.OBJECT;
  10275. this.previousModelWorldMatrix = uniform( new Matrix4() );
  10276. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  10277. this.previousCameraViewMatrix = uniform( new Matrix4() );
  10278. }
  10279. setProjectionMatrix( projectionMatrix ) {
  10280. this.projectionMatrix = projectionMatrix;
  10281. }
  10282. update( { frameId, camera, object } ) {
  10283. const previousModelMatrix = getPreviousMatrix( object );
  10284. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  10285. //
  10286. const cameraData = getData( camera );
  10287. if ( cameraData.frameId !== frameId ) {
  10288. cameraData.frameId = frameId;
  10289. if ( cameraData.previousProjectionMatrix === undefined ) {
  10290. cameraData.previousProjectionMatrix = new Matrix4();
  10291. cameraData.previousCameraViewMatrix = new Matrix4();
  10292. cameraData.currentProjectionMatrix = new Matrix4();
  10293. cameraData.currentCameraViewMatrix = new Matrix4();
  10294. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  10295. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  10296. } else {
  10297. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  10298. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  10299. }
  10300. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  10301. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  10302. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  10303. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  10304. }
  10305. }
  10306. updateAfter( { object } ) {
  10307. getPreviousMatrix( object ).copy( object.matrixWorld );
  10308. }
  10309. setup( /*builder*/ ) {
  10310. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  10311. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  10312. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  10313. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  10314. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  10315. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  10316. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  10317. return velocity;
  10318. }
  10319. }
  10320. function getData( object ) {
  10321. let objectData = _objectData.get( object );
  10322. if ( objectData === undefined ) {
  10323. objectData = {};
  10324. _objectData.set( object, objectData );
  10325. }
  10326. return objectData;
  10327. }
  10328. function getPreviousMatrix( object, index = 0 ) {
  10329. const objectData = getData( object );
  10330. let matrix = objectData[ index ];
  10331. if ( matrix === undefined ) {
  10332. objectData[ index ] = matrix = new Matrix4();
  10333. }
  10334. return matrix;
  10335. }
  10336. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  10337. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  10338. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  10339. } ).setLayout( {
  10340. name: 'blendBurn',
  10341. type: 'vec3',
  10342. inputs: [
  10343. { name: 'base', type: 'vec3' },
  10344. { name: 'blend', type: 'vec3' }
  10345. ]
  10346. } );
  10347. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  10348. return min$1( base.div( blend.oneMinus() ), 1.0 );
  10349. } ).setLayout( {
  10350. name: 'blendDodge',
  10351. type: 'vec3',
  10352. inputs: [
  10353. { name: 'base', type: 'vec3' },
  10354. { name: 'blend', type: 'vec3' }
  10355. ]
  10356. } );
  10357. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  10358. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  10359. } ).setLayout( {
  10360. name: 'blendScreen',
  10361. type: 'vec3',
  10362. inputs: [
  10363. { name: 'base', type: 'vec3' },
  10364. { name: 'blend', type: 'vec3' }
  10365. ]
  10366. } );
  10367. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  10368. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  10369. } ).setLayout( {
  10370. name: 'blendOverlay',
  10371. type: 'vec3',
  10372. inputs: [
  10373. { name: 'base', type: 'vec3' },
  10374. { name: 'blend', type: 'vec3' }
  10375. ]
  10376. } );
  10377. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  10378. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  10379. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  10380. } ).setLayout( {
  10381. name: 'blendColor',
  10382. type: 'vec4',
  10383. inputs: [
  10384. { name: 'base', type: 'vec4' },
  10385. { name: 'blend', type: 'vec4' }
  10386. ]
  10387. } );
  10388. // deprecated
  10389. const burn = ( ...params ) => { // @deprecated, r171
  10390. console.warn( 'THREE.TSL: "burn" has been renamed. Use "blendBurn" instead.' );
  10391. return blendBurn( params );
  10392. };
  10393. const dodge = ( ...params ) => { // @deprecated, r171
  10394. console.warn( 'THREE.TSL: "dodge" has been renamed. Use "blendDodge" instead.' );
  10395. return blendDodge( params );
  10396. };
  10397. const screen = ( ...params ) => { // @deprecated, r171
  10398. console.warn( 'THREE.TSL: "screen" has been renamed. Use "blendScreen" instead.' );
  10399. return blendScreen( params );
  10400. };
  10401. const overlay = ( ...params ) => { // @deprecated, r171
  10402. console.warn( 'THREE.TSL: "overlay" has been renamed. Use "blendOverlay" instead.' );
  10403. return blendOverlay( params );
  10404. };
  10405. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  10406. return luminance( color.rgb );
  10407. } );
  10408. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  10409. return adjustment.mix( luminance( color.rgb ), color.rgb );
  10410. } );
  10411. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  10412. const average = add( color.r, color.g, color.b ).div( 3.0 );
  10413. const mx = color.r.max( color.g.max( color.b ) );
  10414. const amt = mx.sub( average ).mul( adjustment ).mul( - 3.0 );
  10415. return mix( color.rgb, mx, amt );
  10416. } );
  10417. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  10418. const k = vec3( 0.57735, 0.57735, 0.57735 );
  10419. const cosAngle = adjustment.cos();
  10420. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  10421. } );
  10422. const luminance = (
  10423. color,
  10424. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  10425. ) => dot( color, luminanceCoefficients );
  10426. const threshold = ( color, threshold ) => mix( vec3( 0.0 ), color, luminance( color ).sub( threshold ).max( 0 ) );
  10427. /**
  10428. * Color Decision List (CDL) v1.2
  10429. *
  10430. * Compact representation of color grading information, defined by slope, offset, power, and
  10431. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  10432. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  10433. *
  10434. * @param {vec4} color Input (-Infinity < input < +Infinity)
  10435. * @param {number | vec3} slope Slope (0 ≤ slope < +Infinity)
  10436. * @param {number | vec3} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  10437. * @param {number | vec3} power Power (0 < power < +Infinity)
  10438. * @param {number} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  10439. * @param {vec3} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  10440. * @return Output, -Infinity < output < +Infinity
  10441. *
  10442. * References:
  10443. * - ASC CDL v1.2
  10444. * - https://blender.stackexchange.com/a/55239/43930
  10445. * - https://docs.acescentral.com/specifications/acescc/
  10446. */
  10447. const cdl = /*@__PURE__*/ Fn( ( [
  10448. color,
  10449. slope = vec3( 1 ),
  10450. offset = vec3( 0 ),
  10451. power = vec3( 1 ),
  10452. saturation = float( 1 ),
  10453. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  10454. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  10455. ] ) => {
  10456. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  10457. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  10458. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  10459. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  10460. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  10461. const pv = v.pow( power ).toVar();
  10462. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  10463. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  10464. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  10465. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  10466. return vec4( v.rgb, color.a );
  10467. } );
  10468. class PosterizeNode extends TempNode {
  10469. static get type() {
  10470. return 'PosterizeNode';
  10471. }
  10472. constructor( sourceNode, stepsNode ) {
  10473. super();
  10474. this.sourceNode = sourceNode;
  10475. this.stepsNode = stepsNode;
  10476. }
  10477. setup() {
  10478. const { sourceNode, stepsNode } = this;
  10479. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  10480. }
  10481. }
  10482. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode );
  10483. const _size = /*@__PURE__*/ new Vector2();
  10484. class PassTextureNode extends TextureNode {
  10485. static get type() {
  10486. return 'PassTextureNode';
  10487. }
  10488. constructor( passNode, texture ) {
  10489. super( texture );
  10490. this.passNode = passNode;
  10491. this.setUpdateMatrix( false );
  10492. }
  10493. setup( builder ) {
  10494. if ( builder.object.isQuadMesh ) this.passNode.build( builder );
  10495. return super.setup( builder );
  10496. }
  10497. clone() {
  10498. return new this.constructor( this.passNode, this.value );
  10499. }
  10500. }
  10501. class PassMultipleTextureNode extends PassTextureNode {
  10502. static get type() {
  10503. return 'PassMultipleTextureNode';
  10504. }
  10505. constructor( passNode, textureName, previousTexture = false ) {
  10506. super( passNode, null );
  10507. this.textureName = textureName;
  10508. this.previousTexture = previousTexture;
  10509. }
  10510. updateTexture() {
  10511. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  10512. }
  10513. setup( builder ) {
  10514. this.updateTexture();
  10515. return super.setup( builder );
  10516. }
  10517. clone() {
  10518. return new this.constructor( this.passNode, this.textureName, this.previousTexture );
  10519. }
  10520. }
  10521. class PassNode extends TempNode {
  10522. static get type() {
  10523. return 'PassNode';
  10524. }
  10525. constructor( scope, scene, camera, options = {} ) {
  10526. super( 'vec4' );
  10527. this.scope = scope;
  10528. this.scene = scene;
  10529. this.camera = camera;
  10530. this.options = options;
  10531. this._pixelRatio = 1;
  10532. this._width = 1;
  10533. this._height = 1;
  10534. const depthTexture = new DepthTexture();
  10535. depthTexture.isRenderTargetTexture = true;
  10536. //depthTexture.type = FloatType;
  10537. depthTexture.name = 'depth';
  10538. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  10539. renderTarget.texture.name = 'output';
  10540. renderTarget.depthTexture = depthTexture;
  10541. this.renderTarget = renderTarget;
  10542. this.updateBeforeType = NodeUpdateType.FRAME;
  10543. this._textures = {
  10544. output: renderTarget.texture,
  10545. depth: depthTexture
  10546. };
  10547. this._textureNodes = {};
  10548. this._linearDepthNodes = {};
  10549. this._viewZNodes = {};
  10550. this._previousTextures = {};
  10551. this._previousTextureNodes = {};
  10552. this._cameraNear = uniform( 0 );
  10553. this._cameraFar = uniform( 0 );
  10554. this._mrt = null;
  10555. this.isPassNode = true;
  10556. }
  10557. setMRT( mrt ) {
  10558. this._mrt = mrt;
  10559. return this;
  10560. }
  10561. getMRT() {
  10562. return this._mrt;
  10563. }
  10564. isGlobal() {
  10565. return true;
  10566. }
  10567. getTexture( name ) {
  10568. let texture = this._textures[ name ];
  10569. if ( texture === undefined ) {
  10570. const refTexture = this.renderTarget.texture;
  10571. texture = refTexture.clone();
  10572. texture.isRenderTargetTexture = true;
  10573. texture.name = name;
  10574. this._textures[ name ] = texture;
  10575. this.renderTarget.textures.push( texture );
  10576. }
  10577. return texture;
  10578. }
  10579. getPreviousTexture( name ) {
  10580. let texture = this._previousTextures[ name ];
  10581. if ( texture === undefined ) {
  10582. texture = this.getTexture( name ).clone();
  10583. texture.isRenderTargetTexture = true;
  10584. this._previousTextures[ name ] = texture;
  10585. }
  10586. return texture;
  10587. }
  10588. toggleTexture( name ) {
  10589. const prevTexture = this._previousTextures[ name ];
  10590. if ( prevTexture !== undefined ) {
  10591. const texture = this._textures[ name ];
  10592. const index = this.renderTarget.textures.indexOf( texture );
  10593. this.renderTarget.textures[ index ] = prevTexture;
  10594. this._textures[ name ] = prevTexture;
  10595. this._previousTextures[ name ] = texture;
  10596. this._textureNodes[ name ].updateTexture();
  10597. this._previousTextureNodes[ name ].updateTexture();
  10598. }
  10599. }
  10600. getTextureNode( name = 'output' ) {
  10601. let textureNode = this._textureNodes[ name ];
  10602. if ( textureNode === undefined ) {
  10603. textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  10604. textureNode.updateTexture();
  10605. this._textureNodes[ name ] = textureNode;
  10606. }
  10607. return textureNode;
  10608. }
  10609. getPreviousTextureNode( name = 'output' ) {
  10610. let textureNode = this._previousTextureNodes[ name ];
  10611. if ( textureNode === undefined ) {
  10612. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  10613. textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  10614. textureNode.updateTexture();
  10615. this._previousTextureNodes[ name ] = textureNode;
  10616. }
  10617. return textureNode;
  10618. }
  10619. getViewZNode( name = 'depth' ) {
  10620. let viewZNode = this._viewZNodes[ name ];
  10621. if ( viewZNode === undefined ) {
  10622. const cameraNear = this._cameraNear;
  10623. const cameraFar = this._cameraFar;
  10624. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  10625. }
  10626. return viewZNode;
  10627. }
  10628. getLinearDepthNode( name = 'depth' ) {
  10629. let linearDepthNode = this._linearDepthNodes[ name ];
  10630. if ( linearDepthNode === undefined ) {
  10631. const cameraNear = this._cameraNear;
  10632. const cameraFar = this._cameraFar;
  10633. const viewZNode = this.getViewZNode( name );
  10634. // TODO: just if ( builder.camera.isPerspectiveCamera )
  10635. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  10636. }
  10637. return linearDepthNode;
  10638. }
  10639. setup( { renderer } ) {
  10640. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  10641. // Disable MSAA for WebGL backend for now
  10642. if ( renderer.backend.isWebGLBackend === true ) {
  10643. this.renderTarget.samples = 0;
  10644. }
  10645. this.renderTarget.depthTexture.isMultisampleRenderTargetTexture = this.renderTarget.samples > 1;
  10646. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  10647. }
  10648. updateBefore( frame ) {
  10649. const { renderer } = frame;
  10650. const { scene, camera } = this;
  10651. this._pixelRatio = renderer.getPixelRatio();
  10652. const size = renderer.getSize( _size );
  10653. this.setSize( size.width, size.height );
  10654. const currentRenderTarget = renderer.getRenderTarget();
  10655. const currentMRT = renderer.getMRT();
  10656. this._cameraNear.value = camera.near;
  10657. this._cameraFar.value = camera.far;
  10658. for ( const name in this._previousTextures ) {
  10659. this.toggleTexture( name );
  10660. }
  10661. renderer.setRenderTarget( this.renderTarget );
  10662. renderer.setMRT( this._mrt );
  10663. renderer.render( scene, camera );
  10664. renderer.setRenderTarget( currentRenderTarget );
  10665. renderer.setMRT( currentMRT );
  10666. }
  10667. setSize( width, height ) {
  10668. this._width = width;
  10669. this._height = height;
  10670. const effectiveWidth = this._width * this._pixelRatio;
  10671. const effectiveHeight = this._height * this._pixelRatio;
  10672. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  10673. }
  10674. setPixelRatio( pixelRatio ) {
  10675. this._pixelRatio = pixelRatio;
  10676. this.setSize( this._width, this._height );
  10677. }
  10678. dispose() {
  10679. this.renderTarget.dispose();
  10680. }
  10681. }
  10682. PassNode.COLOR = 'color';
  10683. PassNode.DEPTH = 'depth';
  10684. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  10685. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  10686. const depthPass = ( scene, camera ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera ) );
  10687. class ToonOutlinePassNode extends PassNode {
  10688. static get type() {
  10689. return 'ToonOutlinePassNode';
  10690. }
  10691. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  10692. super( PassNode.COLOR, scene, camera );
  10693. this.colorNode = colorNode;
  10694. this.thicknessNode = thicknessNode;
  10695. this.alphaNode = alphaNode;
  10696. this._materialCache = new WeakMap();
  10697. }
  10698. updateBefore( frame ) {
  10699. const { renderer } = frame;
  10700. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  10701. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  10702. // only render outline for supported materials
  10703. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  10704. if ( material.wireframe === false ) {
  10705. const outlineMaterial = this._getOutlineMaterial( material );
  10706. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  10707. }
  10708. }
  10709. // default
  10710. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  10711. } );
  10712. super.updateBefore( frame );
  10713. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  10714. }
  10715. _createMaterial() {
  10716. const material = new NodeMaterial();
  10717. material.isMeshToonOutlineMaterial = true;
  10718. material.name = 'Toon_Outline';
  10719. material.side = BackSide;
  10720. // vertex node
  10721. const outlineNormal = normalLocal.negate();
  10722. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  10723. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  10724. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  10725. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  10726. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  10727. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  10728. // color node
  10729. material.colorNode = vec4( this.colorNode, this.alphaNode );
  10730. return material;
  10731. }
  10732. _getOutlineMaterial( originalMaterial ) {
  10733. let outlineMaterial = this._materialCache.get( originalMaterial );
  10734. if ( outlineMaterial === undefined ) {
  10735. outlineMaterial = this._createMaterial();
  10736. this._materialCache.set( originalMaterial, outlineMaterial );
  10737. }
  10738. return outlineMaterial;
  10739. }
  10740. }
  10741. 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 ) ) );
  10742. // exposure only
  10743. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  10744. return color.mul( exposure ).clamp();
  10745. } ).setLayout( {
  10746. name: 'linearToneMapping',
  10747. type: 'vec3',
  10748. inputs: [
  10749. { name: 'color', type: 'vec3' },
  10750. { name: 'exposure', type: 'float' }
  10751. ]
  10752. } );
  10753. // source: https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf
  10754. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  10755. color = color.mul( exposure );
  10756. return color.div( color.add( 1.0 ) ).clamp();
  10757. } ).setLayout( {
  10758. name: 'reinhardToneMapping',
  10759. type: 'vec3',
  10760. inputs: [
  10761. { name: 'color', type: 'vec3' },
  10762. { name: 'exposure', type: 'float' }
  10763. ]
  10764. } );
  10765. // source: http://filmicworlds.com/blog/filmic-tonemapping-operators/
  10766. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  10767. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  10768. color = color.mul( exposure );
  10769. color = color.sub( 0.004 ).max( 0.0 );
  10770. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  10771. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  10772. return a.div( b ).pow( 2.2 );
  10773. } ).setLayout( {
  10774. name: 'cineonToneMapping',
  10775. type: 'vec3',
  10776. inputs: [
  10777. { name: 'color', type: 'vec3' },
  10778. { name: 'exposure', type: 'float' }
  10779. ]
  10780. } );
  10781. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  10782. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  10783. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  10784. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  10785. return a.div( b );
  10786. } );
  10787. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  10788. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  10789. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  10790. const ACESInputMat = mat3(
  10791. 0.59719, 0.35458, 0.04823,
  10792. 0.07600, 0.90834, 0.01566,
  10793. 0.02840, 0.13383, 0.83777
  10794. );
  10795. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  10796. const ACESOutputMat = mat3(
  10797. 1.60475, - 0.53108, - 0.07367,
  10798. - 0.10208, 1.10813, - 0.00605,
  10799. - 0.00327, - 0.07276, 1.07602
  10800. );
  10801. color = color.mul( exposure ).div( 0.6 );
  10802. color = ACESInputMat.mul( color );
  10803. // Apply RRT and ODT
  10804. color = RRTAndODTFit( color );
  10805. color = ACESOutputMat.mul( color );
  10806. // Clamp to [0, 1]
  10807. return color.clamp();
  10808. } ).setLayout( {
  10809. name: 'acesFilmicToneMapping',
  10810. type: 'vec3',
  10811. inputs: [
  10812. { name: 'color', type: 'vec3' },
  10813. { name: 'exposure', type: 'float' }
  10814. ]
  10815. } );
  10816. 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 ) );
  10817. 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 ) );
  10818. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  10819. const x = vec3( x_immutable ).toVar();
  10820. const x2 = vec3( x.mul( x ) ).toVar();
  10821. const x4 = vec3( x2.mul( x2 ) ).toVar();
  10822. 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 ) ) ) );
  10823. } );
  10824. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  10825. const colortone = vec3( color ).toVar();
  10826. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  10827. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) );
  10828. const AgxMinEv = float( - 12.47393 );
  10829. const AgxMaxEv = float( 4.026069 );
  10830. colortone.mulAssign( exposure );
  10831. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  10832. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  10833. colortone.assign( max$1( colortone, 1e-10 ) );
  10834. colortone.assign( log2( colortone ) );
  10835. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  10836. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  10837. colortone.assign( agxDefaultContrastApprox( colortone ) );
  10838. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  10839. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  10840. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  10841. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  10842. return colortone;
  10843. } ).setLayout( {
  10844. name: 'agxToneMapping',
  10845. type: 'vec3',
  10846. inputs: [
  10847. { name: 'color', type: 'vec3' },
  10848. { name: 'exposure', type: 'float' }
  10849. ]
  10850. } );
  10851. // https://modelviewer.dev/examples/tone-mapping
  10852. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  10853. const StartCompression = float( 0.8 - 0.04 );
  10854. const Desaturation = float( 0.15 );
  10855. color = color.mul( exposure );
  10856. const x = min$1( color.r, min$1( color.g, color.b ) );
  10857. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  10858. color.subAssign( offset );
  10859. const peak = max$1( color.r, max$1( color.g, color.b ) );
  10860. If( peak.lessThan( StartCompression ), () => {
  10861. return color;
  10862. } );
  10863. const d = sub( 1, StartCompression );
  10864. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  10865. color.mulAssign( newPeak.div( peak ) );
  10866. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  10867. return mix( color, vec3( newPeak ), g );
  10868. } ).setLayout( {
  10869. name: 'neutralToneMapping',
  10870. type: 'vec3',
  10871. inputs: [
  10872. { name: 'color', type: 'vec3' },
  10873. { name: 'exposure', type: 'float' }
  10874. ]
  10875. } );
  10876. class CodeNode extends Node {
  10877. static get type() {
  10878. return 'CodeNode';
  10879. }
  10880. constructor( code = '', includes = [], language = '' ) {
  10881. super( 'code' );
  10882. this.isCodeNode = true;
  10883. this.code = code;
  10884. this.language = language;
  10885. this.includes = includes;
  10886. }
  10887. isGlobal() {
  10888. return true;
  10889. }
  10890. setIncludes( includes ) {
  10891. this.includes = includes;
  10892. return this;
  10893. }
  10894. getIncludes( /*builder*/ ) {
  10895. return this.includes;
  10896. }
  10897. generate( builder ) {
  10898. const includes = this.getIncludes( builder );
  10899. for ( const include of includes ) {
  10900. include.build( builder );
  10901. }
  10902. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  10903. nodeCode.code = this.code;
  10904. return nodeCode.code;
  10905. }
  10906. serialize( data ) {
  10907. super.serialize( data );
  10908. data.code = this.code;
  10909. data.language = this.language;
  10910. }
  10911. deserialize( data ) {
  10912. super.deserialize( data );
  10913. this.code = data.code;
  10914. this.language = data.language;
  10915. }
  10916. }
  10917. const code = /*@__PURE__*/ nodeProxy( CodeNode );
  10918. const js = ( src, includes ) => code( src, includes, 'js' );
  10919. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  10920. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  10921. class FunctionNode extends CodeNode {
  10922. static get type() {
  10923. return 'FunctionNode';
  10924. }
  10925. constructor( code = '', includes = [], language = '' ) {
  10926. super( code, includes, language );
  10927. }
  10928. getNodeType( builder ) {
  10929. return this.getNodeFunction( builder ).type;
  10930. }
  10931. getInputs( builder ) {
  10932. return this.getNodeFunction( builder ).inputs;
  10933. }
  10934. getNodeFunction( builder ) {
  10935. const nodeData = builder.getDataFromNode( this );
  10936. let nodeFunction = nodeData.nodeFunction;
  10937. if ( nodeFunction === undefined ) {
  10938. nodeFunction = builder.parser.parseFunction( this.code );
  10939. nodeData.nodeFunction = nodeFunction;
  10940. }
  10941. return nodeFunction;
  10942. }
  10943. generate( builder, output ) {
  10944. super.generate( builder );
  10945. const nodeFunction = this.getNodeFunction( builder );
  10946. const name = nodeFunction.name;
  10947. const type = nodeFunction.type;
  10948. const nodeCode = builder.getCodeFromNode( this, type );
  10949. if ( name !== '' ) {
  10950. // use a custom property name
  10951. nodeCode.name = name;
  10952. }
  10953. const propertyName = builder.getPropertyName( nodeCode );
  10954. const code = this.getNodeFunction( builder ).getCode( propertyName );
  10955. nodeCode.code = code + '\n';
  10956. if ( output === 'property' ) {
  10957. return propertyName;
  10958. } else {
  10959. return builder.format( `${ propertyName }()`, type, output );
  10960. }
  10961. }
  10962. }
  10963. const nativeFn = ( code, includes = [], language = '' ) => {
  10964. for ( let i = 0; i < includes.length; i ++ ) {
  10965. const include = includes[ i ];
  10966. // TSL Function: glslFn, wgslFn
  10967. if ( typeof include === 'function' ) {
  10968. includes[ i ] = include.functionNode;
  10969. }
  10970. }
  10971. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  10972. const fn = ( ...params ) => functionNode.call( ...params );
  10973. fn.functionNode = functionNode;
  10974. return fn;
  10975. };
  10976. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  10977. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  10978. class ScriptableValueNode extends Node {
  10979. static get type() {
  10980. return 'ScriptableValueNode';
  10981. }
  10982. constructor( value = null ) {
  10983. super();
  10984. this._value = value;
  10985. this._cache = null;
  10986. this.inputType = null;
  10987. this.outpuType = null;
  10988. this.events = new EventDispatcher();
  10989. this.isScriptableValueNode = true;
  10990. }
  10991. get isScriptableOutputNode() {
  10992. return this.outputType !== null;
  10993. }
  10994. set value( val ) {
  10995. if ( this._value === val ) return;
  10996. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  10997. URL.revokeObjectURL( this._cache );
  10998. this._cache = null;
  10999. }
  11000. this._value = val;
  11001. this.events.dispatchEvent( { type: 'change' } );
  11002. this.refresh();
  11003. }
  11004. get value() {
  11005. return this._value;
  11006. }
  11007. refresh() {
  11008. this.events.dispatchEvent( { type: 'refresh' } );
  11009. }
  11010. getValue() {
  11011. const value = this.value;
  11012. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  11013. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  11014. } else if ( value && value.value !== null && value.value !== undefined && (
  11015. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  11016. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  11017. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  11018. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  11019. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  11020. ( this.inputType === 'Color' && value.value.isColor ) ||
  11021. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  11022. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  11023. ) ) {
  11024. return value.value;
  11025. }
  11026. return this._cache || value;
  11027. }
  11028. getNodeType( builder ) {
  11029. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  11030. }
  11031. setup() {
  11032. return this.value && this.value.isNode ? this.value : float();
  11033. }
  11034. serialize( data ) {
  11035. super.serialize( data );
  11036. if ( this.value !== null ) {
  11037. if ( this.inputType === 'ArrayBuffer' ) {
  11038. data.value = arrayBufferToBase64( this.value );
  11039. } else {
  11040. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  11041. }
  11042. } else {
  11043. data.value = null;
  11044. }
  11045. data.inputType = this.inputType;
  11046. data.outputType = this.outputType;
  11047. }
  11048. deserialize( data ) {
  11049. super.deserialize( data );
  11050. let value = null;
  11051. if ( data.value !== null ) {
  11052. if ( data.inputType === 'ArrayBuffer' ) {
  11053. value = base64ToArrayBuffer( data.value );
  11054. } else if ( data.inputType === 'Texture' ) {
  11055. value = data.meta.textures[ data.value ];
  11056. } else {
  11057. value = data.meta.nodes[ data.value ] || null;
  11058. }
  11059. }
  11060. this.value = value;
  11061. this.inputType = data.inputType;
  11062. this.outputType = data.outputType;
  11063. }
  11064. }
  11065. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode );
  11066. class Resources extends Map {
  11067. get( key, callback = null, ...params ) {
  11068. if ( this.has( key ) ) return super.get( key );
  11069. if ( callback !== null ) {
  11070. const value = callback( ...params );
  11071. this.set( key, value );
  11072. return value;
  11073. }
  11074. }
  11075. }
  11076. class Parameters {
  11077. constructor( scriptableNode ) {
  11078. this.scriptableNode = scriptableNode;
  11079. }
  11080. get parameters() {
  11081. return this.scriptableNode.parameters;
  11082. }
  11083. get layout() {
  11084. return this.scriptableNode.getLayout();
  11085. }
  11086. getInputLayout( id ) {
  11087. return this.scriptableNode.getInputLayout( id );
  11088. }
  11089. get( name ) {
  11090. const param = this.parameters[ name ];
  11091. const value = param ? param.getValue() : null;
  11092. return value;
  11093. }
  11094. }
  11095. const ScriptableNodeResources = new Resources();
  11096. class ScriptableNode extends Node {
  11097. static get type() {
  11098. return 'ScriptableNode';
  11099. }
  11100. constructor( codeNode = null, parameters = {} ) {
  11101. super();
  11102. this.codeNode = codeNode;
  11103. this.parameters = parameters;
  11104. this._local = new Resources();
  11105. this._output = scriptableValue();
  11106. this._outputs = {};
  11107. this._source = this.source;
  11108. this._method = null;
  11109. this._object = null;
  11110. this._value = null;
  11111. this._needsOutputUpdate = true;
  11112. this.onRefresh = this.onRefresh.bind( this );
  11113. this.isScriptableNode = true;
  11114. }
  11115. get source() {
  11116. return this.codeNode ? this.codeNode.code : '';
  11117. }
  11118. setLocal( name, value ) {
  11119. return this._local.set( name, value );
  11120. }
  11121. getLocal( name ) {
  11122. return this._local.get( name );
  11123. }
  11124. onRefresh() {
  11125. this._refresh();
  11126. }
  11127. getInputLayout( id ) {
  11128. for ( const element of this.getLayout() ) {
  11129. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  11130. return element;
  11131. }
  11132. }
  11133. }
  11134. getOutputLayout( id ) {
  11135. for ( const element of this.getLayout() ) {
  11136. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  11137. return element;
  11138. }
  11139. }
  11140. }
  11141. setOutput( name, value ) {
  11142. const outputs = this._outputs;
  11143. if ( outputs[ name ] === undefined ) {
  11144. outputs[ name ] = scriptableValue( value );
  11145. } else {
  11146. outputs[ name ].value = value;
  11147. }
  11148. return this;
  11149. }
  11150. getOutput( name ) {
  11151. return this._outputs[ name ];
  11152. }
  11153. getParameter( name ) {
  11154. return this.parameters[ name ];
  11155. }
  11156. setParameter( name, value ) {
  11157. const parameters = this.parameters;
  11158. if ( value && value.isScriptableNode ) {
  11159. this.deleteParameter( name );
  11160. parameters[ name ] = value;
  11161. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  11162. } else if ( value && value.isScriptableValueNode ) {
  11163. this.deleteParameter( name );
  11164. parameters[ name ] = value;
  11165. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  11166. } else if ( parameters[ name ] === undefined ) {
  11167. parameters[ name ] = scriptableValue( value );
  11168. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  11169. } else {
  11170. parameters[ name ].value = value;
  11171. }
  11172. return this;
  11173. }
  11174. getValue() {
  11175. return this.getDefaultOutput().getValue();
  11176. }
  11177. deleteParameter( name ) {
  11178. let valueNode = this.parameters[ name ];
  11179. if ( valueNode ) {
  11180. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  11181. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  11182. }
  11183. return this;
  11184. }
  11185. clearParameters() {
  11186. for ( const name of Object.keys( this.parameters ) ) {
  11187. this.deleteParameter( name );
  11188. }
  11189. this.needsUpdate = true;
  11190. return this;
  11191. }
  11192. call( name, ...params ) {
  11193. const object = this.getObject();
  11194. const method = object[ name ];
  11195. if ( typeof method === 'function' ) {
  11196. return method( ...params );
  11197. }
  11198. }
  11199. async callAsync( name, ...params ) {
  11200. const object = this.getObject();
  11201. const method = object[ name ];
  11202. if ( typeof method === 'function' ) {
  11203. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  11204. }
  11205. }
  11206. getNodeType( builder ) {
  11207. return this.getDefaultOutputNode().getNodeType( builder );
  11208. }
  11209. refresh( output = null ) {
  11210. if ( output !== null ) {
  11211. this.getOutput( output ).refresh();
  11212. } else {
  11213. this._refresh();
  11214. }
  11215. }
  11216. getObject() {
  11217. if ( this.needsUpdate ) this.dispose();
  11218. if ( this._object !== null ) return this._object;
  11219. //
  11220. const refresh = () => this.refresh();
  11221. const setOutput = ( id, value ) => this.setOutput( id, value );
  11222. const parameters = new Parameters( this );
  11223. const THREE = ScriptableNodeResources.get( 'THREE' );
  11224. const TSL = ScriptableNodeResources.get( 'TSL' );
  11225. const method = this.getMethod( this.codeNode );
  11226. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  11227. this._object = method( ...params );
  11228. const layout = this._object.layout;
  11229. if ( layout ) {
  11230. if ( layout.cache === false ) {
  11231. this._local.clear();
  11232. }
  11233. // default output
  11234. this._output.outputType = layout.outputType || null;
  11235. if ( Array.isArray( layout.elements ) ) {
  11236. for ( const element of layout.elements ) {
  11237. const id = element.id || element.name;
  11238. if ( element.inputType ) {
  11239. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  11240. this.getParameter( id ).inputType = element.inputType;
  11241. }
  11242. if ( element.outputType ) {
  11243. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  11244. this.getOutput( id ).outputType = element.outputType;
  11245. }
  11246. }
  11247. }
  11248. }
  11249. return this._object;
  11250. }
  11251. deserialize( data ) {
  11252. super.deserialize( data );
  11253. for ( const name in this.parameters ) {
  11254. let valueNode = this.parameters[ name ];
  11255. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  11256. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  11257. }
  11258. }
  11259. getLayout() {
  11260. return this.getObject().layout;
  11261. }
  11262. getDefaultOutputNode() {
  11263. const output = this.getDefaultOutput().value;
  11264. if ( output && output.isNode ) {
  11265. return output;
  11266. }
  11267. return float();
  11268. }
  11269. getDefaultOutput() {
  11270. return this._exec()._output;
  11271. }
  11272. getMethod() {
  11273. if ( this.needsUpdate ) this.dispose();
  11274. if ( this._method !== null ) return this._method;
  11275. //
  11276. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  11277. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  11278. const properties = interfaceProps.join( ', ' );
  11279. const declarations = 'var ' + properties + '; var output = {};\n';
  11280. const returns = '\nreturn { ...output, ' + properties + ' };';
  11281. const code = declarations + this.codeNode.code + returns;
  11282. //
  11283. this._method = new Function( ...parametersProps, code );
  11284. return this._method;
  11285. }
  11286. dispose() {
  11287. if ( this._method === null ) return;
  11288. if ( this._object && typeof this._object.dispose === 'function' ) {
  11289. this._object.dispose();
  11290. }
  11291. this._method = null;
  11292. this._object = null;
  11293. this._source = null;
  11294. this._value = null;
  11295. this._needsOutputUpdate = true;
  11296. this._output.value = null;
  11297. this._outputs = {};
  11298. }
  11299. setup() {
  11300. return this.getDefaultOutputNode();
  11301. }
  11302. getCacheKey( force ) {
  11303. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  11304. for ( const param in this.parameters ) {
  11305. values.push( this.parameters[ param ].getCacheKey( force ) );
  11306. }
  11307. return hashArray( values );
  11308. }
  11309. set needsUpdate( value ) {
  11310. if ( value === true ) this.dispose();
  11311. }
  11312. get needsUpdate() {
  11313. return this.source !== this._source;
  11314. }
  11315. _exec() {
  11316. if ( this.codeNode === null ) return this;
  11317. if ( this._needsOutputUpdate === true ) {
  11318. this._value = this.call( 'main' );
  11319. this._needsOutputUpdate = false;
  11320. }
  11321. this._output.value = this._value;
  11322. return this;
  11323. }
  11324. _refresh() {
  11325. this.needsUpdate = true;
  11326. this._exec();
  11327. this._output.refresh();
  11328. }
  11329. }
  11330. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode );
  11331. class FogNode extends Node {
  11332. static get type() {
  11333. return 'FogNode';
  11334. }
  11335. constructor( colorNode, factorNode ) {
  11336. super( 'float' );
  11337. this.isFogNode = true;
  11338. this.colorNode = colorNode;
  11339. this.factorNode = factorNode;
  11340. }
  11341. getViewZNode( builder ) {
  11342. let viewZ;
  11343. const getViewZ = builder.context.getViewZ;
  11344. if ( getViewZ !== undefined ) {
  11345. viewZ = getViewZ( this );
  11346. }
  11347. return ( viewZ || positionView.z ).negate();
  11348. }
  11349. setup() {
  11350. return this.factorNode;
  11351. }
  11352. }
  11353. const fog = /*@__PURE__*/ nodeProxy( FogNode );
  11354. class FogRangeNode extends FogNode {
  11355. static get type() {
  11356. return 'FogRangeNode';
  11357. }
  11358. constructor( colorNode, nearNode, farNode ) {
  11359. super( colorNode );
  11360. this.isFogRangeNode = true;
  11361. this.nearNode = nearNode;
  11362. this.farNode = farNode;
  11363. }
  11364. setup( builder ) {
  11365. const viewZ = this.getViewZNode( builder );
  11366. return smoothstep( this.nearNode, this.farNode, viewZ );
  11367. }
  11368. }
  11369. const rangeFog = /*@__PURE__*/ nodeProxy( FogRangeNode );
  11370. class FogExp2Node extends FogNode {
  11371. static get type() {
  11372. return 'FogExp2Node';
  11373. }
  11374. constructor( colorNode, densityNode ) {
  11375. super( colorNode );
  11376. this.isFogExp2Node = true;
  11377. this.densityNode = densityNode;
  11378. }
  11379. setup( builder ) {
  11380. const viewZ = this.getViewZNode( builder );
  11381. const density = this.densityNode;
  11382. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  11383. }
  11384. }
  11385. const densityFog = /*@__PURE__*/ nodeProxy( FogExp2Node );
  11386. let min = null;
  11387. let max = null;
  11388. class RangeNode extends Node {
  11389. static get type() {
  11390. return 'RangeNode';
  11391. }
  11392. constructor( minNode = float(), maxNode = float() ) {
  11393. super();
  11394. this.minNode = minNode;
  11395. this.maxNode = maxNode;
  11396. }
  11397. getVectorLength( builder ) {
  11398. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  11399. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  11400. return minLength > maxLength ? minLength : maxLength;
  11401. }
  11402. getNodeType( builder ) {
  11403. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  11404. }
  11405. setup( builder ) {
  11406. const object = builder.object;
  11407. let output = null;
  11408. if ( object.count > 1 ) {
  11409. const minValue = this.minNode.value;
  11410. const maxValue = this.maxNode.value;
  11411. const minLength = builder.getTypeLength( getValueType( minValue ) );
  11412. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  11413. min = min || new Vector4();
  11414. max = max || new Vector4();
  11415. min.setScalar( 0 );
  11416. max.setScalar( 0 );
  11417. if ( minLength === 1 ) min.setScalar( minValue );
  11418. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b );
  11419. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  11420. if ( maxLength === 1 ) max.setScalar( maxValue );
  11421. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b );
  11422. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  11423. const stride = 4;
  11424. const length = stride * object.count;
  11425. const array = new Float32Array( length );
  11426. for ( let i = 0; i < length; i ++ ) {
  11427. const index = i % stride;
  11428. const minElementValue = min.getComponent( index );
  11429. const maxElementValue = max.getComponent( index );
  11430. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  11431. }
  11432. const nodeType = this.getNodeType( builder );
  11433. if ( object.count <= 4096 ) {
  11434. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  11435. } else {
  11436. // TODO: Improve anonymous buffer attribute creation removing this part
  11437. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  11438. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  11439. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  11440. }
  11441. } else {
  11442. output = float( 0 );
  11443. }
  11444. return output;
  11445. }
  11446. }
  11447. const range = /*@__PURE__*/ nodeProxy( RangeNode );
  11448. class ComputeBuiltinNode extends Node {
  11449. static get type() {
  11450. return 'ComputeBuiltinNode';
  11451. }
  11452. constructor( builtinName, nodeType ) {
  11453. super( nodeType );
  11454. this._builtinName = builtinName;
  11455. }
  11456. getHash( builder ) {
  11457. return this.getBuiltinName( builder );
  11458. }
  11459. getNodeType( /*builder*/ ) {
  11460. return this.nodeType;
  11461. }
  11462. setBuiltinName( builtinName ) {
  11463. this._builtinName = builtinName;
  11464. return this;
  11465. }
  11466. getBuiltinName( /*builder*/ ) {
  11467. return this._builtinName;
  11468. }
  11469. hasBuiltin( builder ) {
  11470. builder.hasBuiltin( this._builtinName );
  11471. }
  11472. generate( builder, output ) {
  11473. const builtinName = this.getBuiltinName( builder );
  11474. const nodeType = this.getNodeType( builder );
  11475. if ( builder.shaderStage === 'compute' ) {
  11476. return builder.format( builtinName, nodeType, output );
  11477. } else {
  11478. console.warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  11479. return builder.generateConst( nodeType );
  11480. }
  11481. }
  11482. serialize( data ) {
  11483. super.serialize( data );
  11484. data.global = this.global;
  11485. data._builtinName = this._builtinName;
  11486. }
  11487. deserialize( data ) {
  11488. super.deserialize( data );
  11489. this.global = data.global;
  11490. this._builtinName = data._builtinName;
  11491. }
  11492. }
  11493. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  11494. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  11495. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  11496. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  11497. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  11498. class BarrierNode extends Node {
  11499. constructor( scope ) {
  11500. super();
  11501. this.scope = scope;
  11502. }
  11503. generate( builder ) {
  11504. const { scope } = this;
  11505. const { renderer } = builder;
  11506. if ( renderer.backend.isWebGLBackend === true ) {
  11507. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  11508. } else {
  11509. builder.addLineFlowCode( `${scope}Barrier()`, this );
  11510. }
  11511. }
  11512. }
  11513. const barrier = nodeProxy( BarrierNode );
  11514. const workgroupBarrier = () => barrier( 'workgroup' ).append();
  11515. const storageBarrier = () => barrier( 'storage' ).append();
  11516. const textureBarrier = () => barrier( 'texture' ).append();
  11517. class WorkgroupInfoElementNode extends ArrayElementNode {
  11518. constructor( workgroupInfoNode, indexNode ) {
  11519. super( workgroupInfoNode, indexNode );
  11520. this.isWorkgroupInfoElementNode = true;
  11521. }
  11522. generate( builder, output ) {
  11523. let snippet;
  11524. const isAssignContext = builder.context.assign;
  11525. snippet = super.generate( builder );
  11526. if ( isAssignContext !== true ) {
  11527. const type = this.getNodeType( builder );
  11528. snippet = builder.format( snippet, type, output );
  11529. }
  11530. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  11531. return snippet;
  11532. }
  11533. }
  11534. class WorkgroupInfoNode extends Node {
  11535. constructor( scope, bufferType, bufferCount = 0 ) {
  11536. super( bufferType );
  11537. this.bufferType = bufferType;
  11538. this.bufferCount = bufferCount;
  11539. this.isWorkgroupInfoNode = true;
  11540. this.scope = scope;
  11541. }
  11542. label( name ) {
  11543. this.name = name;
  11544. return this;
  11545. }
  11546. getHash() {
  11547. return this.uuid;
  11548. }
  11549. setScope( scope ) {
  11550. this.scope = scope;
  11551. return this;
  11552. }
  11553. getInputType( /*builder*/ ) {
  11554. return `${this.scope}Array`;
  11555. }
  11556. element( indexNode ) {
  11557. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  11558. }
  11559. generate( builder ) {
  11560. return builder.getScopedArray( this.name || `${this.scope}Array_${this.id}`, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  11561. }
  11562. }
  11563. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  11564. class AtomicFunctionNode extends TempNode {
  11565. static get type() {
  11566. return 'AtomicFunctionNode';
  11567. }
  11568. constructor( method, pointerNode, valueNode, storeNode = null ) {
  11569. super( 'uint' );
  11570. this.method = method;
  11571. this.pointerNode = pointerNode;
  11572. this.valueNode = valueNode;
  11573. this.storeNode = storeNode;
  11574. }
  11575. getInputType( builder ) {
  11576. return this.pointerNode.getNodeType( builder );
  11577. }
  11578. getNodeType( builder ) {
  11579. return this.getInputType( builder );
  11580. }
  11581. generate( builder ) {
  11582. const method = this.method;
  11583. const type = this.getNodeType( builder );
  11584. const inputType = this.getInputType( builder );
  11585. const a = this.pointerNode;
  11586. const b = this.valueNode;
  11587. const params = [];
  11588. params.push( `&${ a.build( builder, inputType ) }` );
  11589. params.push( b.build( builder, inputType ) );
  11590. const methodSnippet = `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`;
  11591. if ( this.storeNode !== null ) {
  11592. const varSnippet = this.storeNode.build( builder, inputType );
  11593. builder.addLineFlowCode( `${varSnippet} = ${methodSnippet}`, this );
  11594. } else {
  11595. builder.addLineFlowCode( methodSnippet, this );
  11596. }
  11597. }
  11598. }
  11599. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  11600. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  11601. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  11602. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  11603. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  11604. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  11605. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  11606. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  11607. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  11608. const atomicNode = nodeProxy( AtomicFunctionNode );
  11609. const atomicFunc = ( method, pointerNode, valueNode, storeNode ) => {
  11610. const node = atomicNode( method, pointerNode, valueNode, storeNode );
  11611. node.append();
  11612. return node;
  11613. };
  11614. const atomicStore = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode, storeNode );
  11615. const atomicAdd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode, storeNode );
  11616. const atomicSub = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode, storeNode );
  11617. const atomicMax = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode, storeNode );
  11618. const atomicMin = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode, storeNode );
  11619. const atomicAnd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode, storeNode );
  11620. const atomicOr = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode, storeNode );
  11621. const atomicXor = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode, storeNode );
  11622. let uniformsLib;
  11623. function getLightData( light ) {
  11624. uniformsLib = uniformsLib || new WeakMap();
  11625. let uniforms = uniformsLib.get( light );
  11626. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  11627. return uniforms;
  11628. }
  11629. function lightShadowMatrix( light ) {
  11630. const data = getLightData( light );
  11631. return data.shadowMatrix || ( data.shadowMatrix = uniform( 'mat4' ).setGroup( renderGroup ).onRenderUpdate( () => {
  11632. light.shadow.updateMatrices( light );
  11633. return light.shadow.matrix;
  11634. } ) );
  11635. }
  11636. function lightProjectionUV( light ) {
  11637. const data = getLightData( light );
  11638. if ( data.projectionUV === undefined ) {
  11639. const spotLightCoord = lightShadowMatrix( light ).mul( positionWorld );
  11640. data.projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  11641. }
  11642. return data.projectionUV;
  11643. }
  11644. function lightPosition( light ) {
  11645. const data = getLightData( light );
  11646. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  11647. }
  11648. function lightTargetPosition( light ) {
  11649. const data = getLightData( light );
  11650. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  11651. }
  11652. function lightViewPosition( light ) {
  11653. const data = getLightData( light );
  11654. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  11655. self.value = self.value || new Vector3();
  11656. self.value.setFromMatrixPosition( light.matrixWorld );
  11657. self.value.applyMatrix4( camera.matrixWorldInverse );
  11658. } ) );
  11659. }
  11660. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  11661. const sortLights = ( lights ) => {
  11662. return lights.sort( ( a, b ) => a.id - b.id );
  11663. };
  11664. const getLightNodeById = ( id, lightNodes ) => {
  11665. for ( const lightNode of lightNodes ) {
  11666. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  11667. return lightNode;
  11668. }
  11669. }
  11670. return null;
  11671. };
  11672. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  11673. class LightsNode extends Node {
  11674. static get type() {
  11675. return 'LightsNode';
  11676. }
  11677. constructor() {
  11678. super( 'vec3' );
  11679. this.totalDiffuseNode = vec3().toVar( 'totalDiffuse' );
  11680. this.totalSpecularNode = vec3().toVar( 'totalSpecular' );
  11681. this.outgoingLightNode = vec3().toVar( 'outgoingLight' );
  11682. this._lights = [];
  11683. this._lightNodes = null;
  11684. this._lightNodesHash = null;
  11685. this.global = true;
  11686. }
  11687. getHash( builder ) {
  11688. if ( this._lightNodesHash === null ) {
  11689. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  11690. const hash = [];
  11691. for ( const lightNode of this._lightNodes ) {
  11692. hash.push( lightNode.getSelf().getHash() );
  11693. }
  11694. this._lightNodesHash = 'lights-' + hash.join( ',' );
  11695. }
  11696. return this._lightNodesHash;
  11697. }
  11698. analyze( builder ) {
  11699. const properties = builder.getDataFromNode( this );
  11700. for ( const node of properties.nodes ) {
  11701. node.build( builder );
  11702. }
  11703. }
  11704. setupLightsNode( builder ) {
  11705. const lightNodes = [];
  11706. const previousLightNodes = this._lightNodes;
  11707. const lights = sortLights( this._lights );
  11708. const nodeLibrary = builder.renderer.library;
  11709. for ( const light of lights ) {
  11710. if ( light.isNode ) {
  11711. lightNodes.push( nodeObject( light ) );
  11712. } else {
  11713. let lightNode = null;
  11714. if ( previousLightNodes !== null ) {
  11715. lightNode = getLightNodeById( light.id, previousLightNodes ); // resuse existing light node
  11716. }
  11717. if ( lightNode === null ) {
  11718. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  11719. if ( lightNodeClass === null ) {
  11720. console.warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  11721. continue;
  11722. }
  11723. let lightNode = null;
  11724. if ( ! _lightsNodeRef.has( light ) ) {
  11725. lightNode = nodeObject( new lightNodeClass( light ) );
  11726. _lightsNodeRef.set( light, lightNode );
  11727. } else {
  11728. lightNode = _lightsNodeRef.get( light );
  11729. }
  11730. lightNodes.push( lightNode );
  11731. }
  11732. }
  11733. }
  11734. this._lightNodes = lightNodes;
  11735. }
  11736. setupLights( builder, lightNodes ) {
  11737. for ( const lightNode of lightNodes ) {
  11738. lightNode.build( builder );
  11739. }
  11740. }
  11741. setup( builder ) {
  11742. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  11743. const context = builder.context;
  11744. const lightingModel = context.lightingModel;
  11745. let outgoingLightNode = this.outgoingLightNode;
  11746. if ( lightingModel ) {
  11747. const { _lightNodes, totalDiffuseNode, totalSpecularNode } = this;
  11748. context.outgoingLight = outgoingLightNode;
  11749. const stack = builder.addStack();
  11750. //
  11751. const properties = builder.getDataFromNode( this );
  11752. properties.nodes = stack.nodes;
  11753. //
  11754. lightingModel.start( context, stack, builder );
  11755. // lights
  11756. this.setupLights( builder, _lightNodes );
  11757. //
  11758. lightingModel.indirect( context, stack, builder );
  11759. //
  11760. const { backdrop, backdropAlpha } = context;
  11761. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  11762. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  11763. if ( backdrop !== null ) {
  11764. if ( backdropAlpha !== null ) {
  11765. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  11766. } else {
  11767. totalDiffuse = vec3( backdrop );
  11768. }
  11769. context.material.transparent = true;
  11770. }
  11771. totalDiffuseNode.assign( totalDiffuse );
  11772. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  11773. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  11774. //
  11775. lightingModel.finish( context, stack, builder );
  11776. //
  11777. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  11778. }
  11779. return outgoingLightNode;
  11780. }
  11781. setLights( lights ) {
  11782. this._lights = lights;
  11783. this._lightNodes = null;
  11784. this._lightNodesHash = null;
  11785. return this;
  11786. }
  11787. getLights() {
  11788. return this._lights;
  11789. }
  11790. get hasLights() {
  11791. return this._lights.length > 0;
  11792. }
  11793. }
  11794. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  11795. const shadowMaterialLib = /*@__PURE__*/ new WeakMap();
  11796. const shadowWorldPosition = /*@__PURE__*/ vec3().toVar( 'shadowWorldPosition' );
  11797. const linearDistance = /*@__PURE__*/ Fn( ( [ position, cameraNear, cameraFar ] ) => {
  11798. let dist = positionWorld.sub( position ).length();
  11799. dist = dist.sub( cameraNear ).div( cameraFar.sub( cameraNear ) );
  11800. dist = dist.saturate(); // clamp to [ 0, 1 ]
  11801. return dist;
  11802. } );
  11803. const linearShadowDistance = ( light ) => {
  11804. const camera = light.shadow.camera;
  11805. const nearDistance = reference( 'near', 'float', camera ).setGroup( renderGroup );
  11806. const farDistance = reference( 'far', 'float', camera ).setGroup( renderGroup );
  11807. const referencePosition = objectPosition( light );
  11808. return linearDistance( referencePosition, nearDistance, farDistance );
  11809. };
  11810. const getShadowMaterial = ( light ) => {
  11811. let material = shadowMaterialLib.get( light );
  11812. if ( material === undefined ) {
  11813. const depthNode = light.isPointLight ? linearShadowDistance( light ) : null;
  11814. material = new NodeMaterial();
  11815. material.colorNode = vec4( 0, 0, 0, 1 );
  11816. material.depthNode = depthNode;
  11817. material.isShadowNodeMaterial = true; // Use to avoid other overrideMaterial override material.colorNode unintentionally when using material.shadowNode
  11818. material.blending = NoBlending;
  11819. material.name = 'ShadowMaterial';
  11820. shadowMaterialLib.set( light, material );
  11821. }
  11822. return material;
  11823. };
  11824. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord } ) => {
  11825. return texture( depthTexture, shadowCoord.xy ).compare( shadowCoord.z );
  11826. } );
  11827. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  11828. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  11829. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  11830. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  11831. const texelSize = vec2( 1 ).div( mapSize );
  11832. const dx0 = texelSize.x.negate().mul( radius );
  11833. const dy0 = texelSize.y.negate().mul( radius );
  11834. const dx1 = texelSize.x.mul( radius );
  11835. const dy1 = texelSize.y.mul( radius );
  11836. const dx2 = dx0.div( 2 );
  11837. const dy2 = dy0.div( 2 );
  11838. const dx3 = dx1.div( 2 );
  11839. const dy3 = dy1.div( 2 );
  11840. return add(
  11841. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  11842. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  11843. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  11844. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  11845. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  11846. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  11847. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  11848. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  11849. depthCompare( shadowCoord.xy, shadowCoord.z ),
  11850. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  11851. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  11852. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  11853. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  11854. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  11855. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  11856. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  11857. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  11858. ).mul( 1 / 17 );
  11859. } );
  11860. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  11861. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  11862. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  11863. const texelSize = vec2( 1 ).div( mapSize );
  11864. const dx = texelSize.x;
  11865. const dy = texelSize.y;
  11866. const uv = shadowCoord.xy;
  11867. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  11868. uv.subAssign( f.mul( texelSize ) );
  11869. return add(
  11870. depthCompare( uv, shadowCoord.z ),
  11871. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  11872. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  11873. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  11874. mix(
  11875. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  11876. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  11877. f.x
  11878. ),
  11879. mix(
  11880. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  11881. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  11882. f.x
  11883. ),
  11884. mix(
  11885. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  11886. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  11887. f.y
  11888. ),
  11889. mix(
  11890. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  11891. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  11892. f.y
  11893. ),
  11894. mix(
  11895. mix(
  11896. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  11897. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  11898. f.x
  11899. ),
  11900. mix(
  11901. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  11902. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  11903. f.x
  11904. ),
  11905. f.y
  11906. )
  11907. ).mul( 1 / 9 );
  11908. } );
  11909. // VSM
  11910. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord } ) => {
  11911. const occlusion = float( 1 ).toVar();
  11912. const distribution = texture( depthTexture ).uv( shadowCoord.xy ).rg;
  11913. const hardShadow = step( shadowCoord.z, distribution.x );
  11914. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  11915. const distance = shadowCoord.z.sub( distribution.x );
  11916. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  11917. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  11918. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  11919. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  11920. } );
  11921. return occlusion;
  11922. } );
  11923. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass } ) => {
  11924. const mean = float( 0 ).toVar();
  11925. const squaredMean = float( 0 ).toVar();
  11926. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  11927. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  11928. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  11929. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  11930. const depth = shadowPass.uv( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) ).x;
  11931. mean.addAssign( depth );
  11932. squaredMean.addAssign( depth.mul( depth ) );
  11933. } );
  11934. mean.divAssign( samples );
  11935. squaredMean.divAssign( samples );
  11936. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  11937. return vec2( mean, std_dev );
  11938. } );
  11939. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass } ) => {
  11940. const mean = float( 0 ).toVar();
  11941. const squaredMean = float( 0 ).toVar();
  11942. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  11943. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  11944. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  11945. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  11946. const distribution = shadowPass.uv( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  11947. mean.addAssign( distribution.x );
  11948. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  11949. } );
  11950. mean.divAssign( samples );
  11951. squaredMean.divAssign( samples );
  11952. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  11953. return vec2( mean, std_dev );
  11954. } );
  11955. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  11956. //
  11957. const _quadMesh$1 = /*@__PURE__*/ new QuadMesh();
  11958. class ShadowNode extends Node {
  11959. static get type() {
  11960. return 'ShadowNode';
  11961. }
  11962. constructor( light, shadow = null ) {
  11963. super();
  11964. this.light = light;
  11965. this.shadow = shadow || light.shadow;
  11966. this.shadowMap = null;
  11967. this.vsmShadowMapVertical = null;
  11968. this.vsmShadowMapHorizontal = null;
  11969. this.vsmMaterialVertical = null;
  11970. this.vsmMaterialHorizontal = null;
  11971. this.updateBeforeType = NodeUpdateType.RENDER;
  11972. this._node = null;
  11973. this.isShadowNode = true;
  11974. }
  11975. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow } ) {
  11976. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  11977. .and( shadowCoord.x.lessThanEqual( 1 ) )
  11978. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  11979. .and( shadowCoord.y.lessThanEqual( 1 ) )
  11980. .and( shadowCoord.z.lessThanEqual( 1 ) );
  11981. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow } );
  11982. return frustumTest.select( shadowNode, float( 1 ) );
  11983. }
  11984. setupShadowCoord( builder, shadowPosition ) {
  11985. const { shadow } = this;
  11986. const { renderer } = builder;
  11987. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  11988. let shadowCoord = shadowPosition;
  11989. let coordZ;
  11990. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  11991. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  11992. coordZ = shadowCoord.z;
  11993. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  11994. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  11995. }
  11996. } else {
  11997. const w = shadowCoord.w;
  11998. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  11999. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  12000. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  12001. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  12002. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  12003. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  12004. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  12005. }
  12006. shadowCoord = vec3(
  12007. shadowCoord.x,
  12008. shadowCoord.y.oneMinus(), // follow webgpu standards
  12009. coordZ.add( bias )
  12010. );
  12011. return shadowCoord;
  12012. }
  12013. getShadowFilterFn( type ) {
  12014. return _shadowFilterLib[ type ];
  12015. }
  12016. setupShadow( builder ) {
  12017. const { renderer } = builder;
  12018. const { light, shadow } = this;
  12019. const shadowMapType = renderer.shadowMap.type;
  12020. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  12021. depthTexture.compareFunction = LessCompare;
  12022. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  12023. shadowMap.depthTexture = depthTexture;
  12024. shadow.camera.updateProjectionMatrix();
  12025. // VSM
  12026. if ( shadowMapType === VSMShadowMap ) {
  12027. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  12028. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  12029. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  12030. const shadowPassVertical = texture( depthTexture );
  12031. const shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  12032. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  12033. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  12034. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  12035. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  12036. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical } ).context( builder.getSharedContext() );
  12037. material.name = 'VSMVertical';
  12038. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  12039. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal } ).context( builder.getSharedContext() );
  12040. material.name = 'VSMHorizontal';
  12041. }
  12042. //
  12043. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  12044. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  12045. const shadowPosition = lightShadowMatrix( light ).mul( shadowWorldPosition.add( transformedNormalWorld.mul( normalBias ) ) );
  12046. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  12047. //
  12048. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  12049. if ( filterFn === null ) {
  12050. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  12051. }
  12052. const shadowDepthTexture = ( shadowMapType === VSMShadowMap ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  12053. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow } );
  12054. const shadowColor = texture( shadowMap.texture, shadowCoord );
  12055. const shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  12056. this.shadowMap = shadowMap;
  12057. this.shadow.map = shadowMap;
  12058. return shadowOutput;
  12059. }
  12060. setup( builder ) {
  12061. if ( builder.renderer.shadowMap.enabled === false ) return;
  12062. return Fn( ( { material } ) => {
  12063. shadowWorldPosition.assign( material.shadowPositionNode || positionWorld );
  12064. let node = this._node;
  12065. if ( node === null ) {
  12066. this._node = node = this.setupShadow( builder );
  12067. }
  12068. if ( builder.material.shadowNode ) { // @deprecated, r171
  12069. console.warn( 'THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.' );
  12070. }
  12071. if ( builder.material.receivedShadowNode ) {
  12072. node = builder.material.receivedShadowNode( node );
  12073. }
  12074. return node;
  12075. } )();
  12076. }
  12077. renderShadow( frame ) {
  12078. const { shadow, shadowMap } = this;
  12079. const { renderer, scene } = frame;
  12080. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height );
  12081. renderer.render( scene, shadow.camera );
  12082. }
  12083. updateShadow( frame ) {
  12084. const { shadowMap, light, shadow } = this;
  12085. const { renderer, scene, camera } = frame;
  12086. const shadowType = renderer.shadowMap.type;
  12087. const depthVersion = shadowMap.depthTexture.version;
  12088. this._depthVersionCached = depthVersion;
  12089. const currentOverrideMaterial = scene.overrideMaterial;
  12090. scene.overrideMaterial = getShadowMaterial( light );
  12091. shadow.camera.layers.mask = camera.layers.mask;
  12092. const currentRenderTarget = renderer.getRenderTarget();
  12093. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  12094. const currentMRT = renderer.getMRT();
  12095. renderer.setMRT( null );
  12096. renderer.setRenderObjectFunction( ( object, ...params ) => {
  12097. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  12098. renderer.renderObject( object, ...params );
  12099. }
  12100. } );
  12101. renderer.setRenderTarget( shadowMap );
  12102. this.renderShadow( frame );
  12103. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  12104. // vsm blur pass
  12105. if ( light.isPointLight !== true && shadowType === VSMShadowMap ) {
  12106. this.vsmPass( renderer );
  12107. }
  12108. renderer.setRenderTarget( currentRenderTarget );
  12109. renderer.setMRT( currentMRT );
  12110. scene.overrideMaterial = currentOverrideMaterial;
  12111. }
  12112. vsmPass( renderer ) {
  12113. const { shadow } = this;
  12114. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height );
  12115. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height );
  12116. renderer.setRenderTarget( this.vsmShadowMapVertical );
  12117. _quadMesh$1.material = this.vsmMaterialVertical;
  12118. _quadMesh$1.render( renderer );
  12119. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  12120. _quadMesh$1.material = this.vsmMaterialHorizontal;
  12121. _quadMesh$1.render( renderer );
  12122. }
  12123. dispose() {
  12124. this.shadowMap.dispose();
  12125. this.shadowMap = null;
  12126. if ( this.vsmShadowMapVertical !== null ) {
  12127. this.vsmShadowMapVertical.dispose();
  12128. this.vsmShadowMapVertical = null;
  12129. this.vsmMaterialVertical.dispose();
  12130. this.vsmMaterialVertical = null;
  12131. }
  12132. if ( this.vsmShadowMapHorizontal !== null ) {
  12133. this.vsmShadowMapHorizontal.dispose();
  12134. this.vsmShadowMapHorizontal = null;
  12135. this.vsmMaterialHorizontal.dispose();
  12136. this.vsmMaterialHorizontal = null;
  12137. }
  12138. this.updateBeforeType = NodeUpdateType.NONE;
  12139. }
  12140. updateBefore( frame ) {
  12141. const { shadow } = this;
  12142. const needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  12143. if ( needsUpdate ) {
  12144. this.updateShadow( frame );
  12145. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  12146. shadow.needsUpdate = false;
  12147. }
  12148. }
  12149. }
  12150. }
  12151. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  12152. class AnalyticLightNode extends LightingNode {
  12153. static get type() {
  12154. return 'AnalyticLightNode';
  12155. }
  12156. constructor( light = null ) {
  12157. super();
  12158. this.light = light;
  12159. this.color = new Color();
  12160. this.colorNode = ( light && light.colorNode ) || uniform( this.color ).setGroup( renderGroup );
  12161. this.baseColorNode = null;
  12162. this.shadowNode = null;
  12163. this.shadowColorNode = null;
  12164. this.isAnalyticLightNode = true;
  12165. this.updateType = NodeUpdateType.FRAME;
  12166. }
  12167. getCacheKey() {
  12168. return hash$1( super.getCacheKey(), this.light.id, this.light.castShadow ? 1 : 0 );
  12169. }
  12170. getHash() {
  12171. return this.light.uuid;
  12172. }
  12173. setupShadowNode() {
  12174. return shadow( this.light );
  12175. }
  12176. setupShadow( builder ) {
  12177. const { renderer } = builder;
  12178. if ( renderer.shadowMap.enabled === false ) return;
  12179. let shadowColorNode = this.shadowColorNode;
  12180. if ( shadowColorNode === null ) {
  12181. const customShadowNode = this.light.shadow.shadowNode;
  12182. let shadowNode;
  12183. if ( customShadowNode !== undefined ) {
  12184. shadowNode = nodeObject( customShadowNode );
  12185. } else {
  12186. shadowNode = this.setupShadowNode( builder );
  12187. }
  12188. this.shadowNode = shadowNode;
  12189. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  12190. this.baseColorNode = this.colorNode;
  12191. }
  12192. //
  12193. this.colorNode = shadowColorNode;
  12194. }
  12195. setup( builder ) {
  12196. this.colorNode = this.baseColorNode || this.colorNode;
  12197. if ( this.light.castShadow ) {
  12198. if ( builder.object.receiveShadow ) {
  12199. this.setupShadow( builder );
  12200. }
  12201. } else if ( this.shadowNode !== null ) {
  12202. this.shadowNode.dispose();
  12203. this.shadowNode = null;
  12204. this.shadowColorNode = null;
  12205. }
  12206. }
  12207. update( /*frame*/ ) {
  12208. const { light } = this;
  12209. this.color.copy( light.color ).multiplyScalar( light.intensity );
  12210. }
  12211. }
  12212. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( inputs ) => {
  12213. const { lightDistance, cutoffDistance, decayExponent } = inputs;
  12214. // based upon Frostbite 3 Moving to Physically-based Rendering
  12215. // page 32, equation 26: E[window1]
  12216. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  12217. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  12218. return cutoffDistance.greaterThan( 0 ).select(
  12219. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  12220. distanceFalloff
  12221. );
  12222. } ); // validated
  12223. const _clearColor$2 = /*@__PURE__*/ new Color();
  12224. // cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D
  12225. // vector suitable for 2D texture mapping. This code uses the following layout for the
  12226. // 2D texture:
  12227. //
  12228. // xzXZ
  12229. // y Y
  12230. //
  12231. // Y - Positive y direction
  12232. // y - Negative y direction
  12233. // X - Positive x direction
  12234. // x - Negative x direction
  12235. // Z - Positive z direction
  12236. // z - Negative z direction
  12237. //
  12238. // Source and test bed:
  12239. // https://gist.github.com/tschw/da10c43c467ce8afd0c4
  12240. const cubeToUV = /*@__PURE__*/ Fn( ( [ pos, texelSizeY ] ) => {
  12241. const v = pos.toVar();
  12242. // Number of texels to avoid at the edge of each square
  12243. const absV = abs( v );
  12244. // Intersect unit cube
  12245. const scaleToCube = div( 1.0, max$1( absV.x, max$1( absV.y, absV.z ) ) );
  12246. absV.mulAssign( scaleToCube );
  12247. // Apply scale to avoid seams
  12248. // two texels less per square (one texel will do for NEAREST)
  12249. v.mulAssign( scaleToCube.mul( texelSizeY.mul( 2 ).oneMinus() ) );
  12250. // Unwrap
  12251. // space: -1 ... 1 range for each square
  12252. //
  12253. // #X## dim := ( 4 , 2 )
  12254. // # # center := ( 1 , 1 )
  12255. const planar = vec2( v.xy ).toVar();
  12256. const almostATexel = texelSizeY.mul( 1.5 );
  12257. const almostOne = almostATexel.oneMinus();
  12258. If( absV.z.greaterThanEqual( almostOne ), () => {
  12259. If( v.z.greaterThan( 0.0 ), () => {
  12260. planar.x.assign( sub( 4.0, v.x ) );
  12261. } );
  12262. } ).ElseIf( absV.x.greaterThanEqual( almostOne ), () => {
  12263. const signX = sign( v.x );
  12264. planar.x.assign( v.z.mul( signX ).add( signX.mul( 2.0 ) ) );
  12265. } ).ElseIf( absV.y.greaterThanEqual( almostOne ), () => {
  12266. const signY = sign( v.y );
  12267. planar.x.assign( v.x.add( signY.mul( 2.0 ) ).add( 2.0 ) );
  12268. planar.y.assign( v.z.mul( signY ).sub( 2.0 ) );
  12269. } );
  12270. // Transform to UV space
  12271. // scale := 0.5 / dim
  12272. // translate := ( center + 0.5 ) / dim
  12273. return vec2( 0.125, 0.25 ).mul( planar ).add( vec2( 0.375, 0.75 ) ).flipY();
  12274. } ).setLayout( {
  12275. name: 'cubeToUV',
  12276. type: 'vec2',
  12277. inputs: [
  12278. { name: 'pos', type: 'vec3' },
  12279. { name: 'texelSizeY', type: 'float' }
  12280. ]
  12281. } );
  12282. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize } ) => {
  12283. return texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp );
  12284. } );
  12285. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize, shadow } ) => {
  12286. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  12287. const offset = vec2( - 1.0, 1.0 ).mul( radius ).mul( texelSize.y );
  12288. return texture( depthTexture, cubeToUV( bd3D.add( offset.xyy ), texelSize.y ) ).compare( dp )
  12289. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyy ), texelSize.y ) ).compare( dp ) )
  12290. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xyx ), texelSize.y ) ).compare( dp ) )
  12291. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyx ), texelSize.y ) ).compare( dp ) )
  12292. .add( texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp ) )
  12293. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxy ), texelSize.y ) ).compare( dp ) )
  12294. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxy ), texelSize.y ) ).compare( dp ) )
  12295. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxx ), texelSize.y ) ).compare( dp ) )
  12296. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxx ), texelSize.y ) ).compare( dp ) )
  12297. .mul( 1.0 / 9.0 );
  12298. } );
  12299. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow } ) => {
  12300. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  12301. // the vector from the light to the world-space position of the fragment.
  12302. const lightToPosition = shadowCoord.xyz.toVar();
  12303. const lightToPositionLength = lightToPosition.length();
  12304. const cameraNearLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.near );
  12305. const cameraFarLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.far );
  12306. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  12307. const mapSize = uniform( shadow.mapSize ).setGroup( renderGroup );
  12308. const result = float( 1.0 ).toVar();
  12309. If( lightToPositionLength.sub( cameraFarLocal ).lessThanEqual( 0.0 ).and( lightToPositionLength.sub( cameraNearLocal ).greaterThanEqual( 0.0 ) ), () => {
  12310. // dp = normalized distance from light to fragment position
  12311. const dp = lightToPositionLength.sub( cameraNearLocal ).div( cameraFarLocal.sub( cameraNearLocal ) ).toVar(); // need to clamp?
  12312. dp.addAssign( bias );
  12313. // bd3D = base direction 3D
  12314. const bd3D = lightToPosition.normalize();
  12315. const texelSize = vec2( 1.0 ).div( mapSize.mul( vec2( 4.0, 2.0 ) ) );
  12316. // percentage-closer filtering
  12317. result.assign( filterFn( { depthTexture, bd3D, dp, texelSize, shadow } ) );
  12318. } );
  12319. return result;
  12320. } );
  12321. const _viewport = /*@__PURE__*/ new Vector4();
  12322. const _viewportSize = /*@__PURE__*/ new Vector2();
  12323. const _shadowMapSize = /*@__PURE__*/ new Vector2();
  12324. //
  12325. class PointShadowNode extends ShadowNode {
  12326. static get type() {
  12327. return 'PointShadowNode';
  12328. }
  12329. constructor( light, shadow = null ) {
  12330. super( light, shadow );
  12331. }
  12332. getShadowFilterFn( type ) {
  12333. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  12334. }
  12335. setupShadowCoord( builder, shadowPosition ) {
  12336. return shadowPosition;
  12337. }
  12338. setupShadowFilter( builder, { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } ) {
  12339. return pointShadowFilter( { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } );
  12340. }
  12341. renderShadow( frame ) {
  12342. const { shadow, shadowMap, light } = this;
  12343. const { renderer, scene } = frame;
  12344. const shadowFrameExtents = shadow.getFrameExtents();
  12345. _shadowMapSize.copy( shadow.mapSize );
  12346. _shadowMapSize.multiply( shadowFrameExtents );
  12347. shadowMap.setSize( _shadowMapSize.width, _shadowMapSize.height );
  12348. _viewportSize.copy( shadow.mapSize );
  12349. //
  12350. const previousAutoClear = renderer.autoClear;
  12351. const previousClearColor = renderer.getClearColor( _clearColor$2 );
  12352. const previousClearAlpha = renderer.getClearAlpha();
  12353. renderer.autoClear = false;
  12354. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  12355. renderer.clear();
  12356. const viewportCount = shadow.getViewportCount();
  12357. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  12358. const viewport = shadow.getViewport( vp );
  12359. const x = _viewportSize.x * viewport.x;
  12360. const y = _shadowMapSize.y - _viewportSize.y - ( _viewportSize.y * viewport.y );
  12361. _viewport.set(
  12362. x,
  12363. y,
  12364. _viewportSize.x * viewport.z,
  12365. _viewportSize.y * viewport.w
  12366. );
  12367. shadowMap.viewport.copy( _viewport );
  12368. shadow.updateMatrices( light, vp );
  12369. renderer.render( scene, shadow.camera );
  12370. }
  12371. //
  12372. renderer.autoClear = previousAutoClear;
  12373. renderer.setClearColor( previousClearColor, previousClearAlpha );
  12374. }
  12375. }
  12376. const pointShadow = ( light, shadow ) => nodeObject( new PointShadowNode( light, shadow ) );
  12377. const directPointLight = Fn( ( { color, lightViewPosition, cutoffDistance, decayExponent }, builder ) => {
  12378. const lightingModel = builder.context.lightingModel;
  12379. const lVector = lightViewPosition.sub( positionView ); // @TODO: Add it into LightNode
  12380. const lightDirection = lVector.normalize();
  12381. const lightDistance = lVector.length();
  12382. const lightAttenuation = getDistanceAttenuation( {
  12383. lightDistance,
  12384. cutoffDistance,
  12385. decayExponent
  12386. } );
  12387. const lightColor = color.mul( lightAttenuation );
  12388. const reflectedLight = builder.context.reflectedLight;
  12389. lightingModel.direct( {
  12390. lightDirection,
  12391. lightColor,
  12392. reflectedLight
  12393. }, builder.stack, builder );
  12394. } );
  12395. class PointLightNode extends AnalyticLightNode {
  12396. static get type() {
  12397. return 'PointLightNode';
  12398. }
  12399. constructor( light = null ) {
  12400. super( light );
  12401. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  12402. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  12403. }
  12404. update( frame ) {
  12405. const { light } = this;
  12406. super.update( frame );
  12407. this.cutoffDistanceNode.value = light.distance;
  12408. this.decayExponentNode.value = light.decay;
  12409. }
  12410. setupShadowNode() {
  12411. return pointShadow( this.light );
  12412. }
  12413. setup( builder ) {
  12414. super.setup( builder );
  12415. directPointLight( {
  12416. color: this.colorNode,
  12417. lightViewPosition: lightViewPosition( this.light ),
  12418. cutoffDistance: this.cutoffDistanceNode,
  12419. decayExponent: this.decayExponentNode
  12420. } ).append();
  12421. }
  12422. }
  12423. const checker = /*@__PURE__*/ Fn( ( [ coord = uv() ] ) => {
  12424. const uv = coord.mul( 2.0 );
  12425. const cx = uv.x.floor();
  12426. const cy = uv.y.floor();
  12427. const result = cx.add( cy ).mod( 2.0 );
  12428. return result.sign();
  12429. } );
  12430. // Three.js Transpiler
  12431. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  12432. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  12433. const f = float( f_immutable ).toVar();
  12434. const t = float( t_immutable ).toVar();
  12435. const b = bool( b_immutable ).toVar();
  12436. return select( b, t, f );
  12437. } ).setLayout( {
  12438. name: 'mx_select',
  12439. type: 'float',
  12440. inputs: [
  12441. { name: 'b', type: 'bool' },
  12442. { name: 't', type: 'float' },
  12443. { name: 'f', type: 'float' }
  12444. ]
  12445. } );
  12446. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  12447. const b = bool( b_immutable ).toVar();
  12448. const val = float( val_immutable ).toVar();
  12449. return select( b, val.negate(), val );
  12450. } ).setLayout( {
  12451. name: 'mx_negate_if',
  12452. type: 'float',
  12453. inputs: [
  12454. { name: 'val', type: 'float' },
  12455. { name: 'b', type: 'bool' }
  12456. ]
  12457. } );
  12458. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  12459. const x = float( x_immutable ).toVar();
  12460. return int( floor( x ) );
  12461. } ).setLayout( {
  12462. name: 'mx_floor',
  12463. type: 'int',
  12464. inputs: [
  12465. { name: 'x', type: 'float' }
  12466. ]
  12467. } );
  12468. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  12469. const x = float( x_immutable ).toVar();
  12470. i.assign( mx_floor( x ) );
  12471. return x.sub( float( i ) );
  12472. } );
  12473. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  12474. const t = float( t_immutable ).toVar();
  12475. const s = float( s_immutable ).toVar();
  12476. const v3 = float( v3_immutable ).toVar();
  12477. const v2 = float( v2_immutable ).toVar();
  12478. const v1 = float( v1_immutable ).toVar();
  12479. const v0 = float( v0_immutable ).toVar();
  12480. const s1 = float( sub( 1.0, s ) ).toVar();
  12481. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  12482. } ).setLayout( {
  12483. name: 'mx_bilerp_0',
  12484. type: 'float',
  12485. inputs: [
  12486. { name: 'v0', type: 'float' },
  12487. { name: 'v1', type: 'float' },
  12488. { name: 'v2', type: 'float' },
  12489. { name: 'v3', type: 'float' },
  12490. { name: 's', type: 'float' },
  12491. { name: 't', type: 'float' }
  12492. ]
  12493. } );
  12494. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  12495. const t = float( t_immutable ).toVar();
  12496. const s = float( s_immutable ).toVar();
  12497. const v3 = vec3( v3_immutable ).toVar();
  12498. const v2 = vec3( v2_immutable ).toVar();
  12499. const v1 = vec3( v1_immutable ).toVar();
  12500. const v0 = vec3( v0_immutable ).toVar();
  12501. const s1 = float( sub( 1.0, s ) ).toVar();
  12502. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  12503. } ).setLayout( {
  12504. name: 'mx_bilerp_1',
  12505. type: 'vec3',
  12506. inputs: [
  12507. { name: 'v0', type: 'vec3' },
  12508. { name: 'v1', type: 'vec3' },
  12509. { name: 'v2', type: 'vec3' },
  12510. { name: 'v3', type: 'vec3' },
  12511. { name: 's', type: 'float' },
  12512. { name: 't', type: 'float' }
  12513. ]
  12514. } );
  12515. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  12516. 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 ] ) => {
  12517. const r = float( r_immutable ).toVar();
  12518. const t = float( t_immutable ).toVar();
  12519. const s = float( s_immutable ).toVar();
  12520. const v7 = float( v7_immutable ).toVar();
  12521. const v6 = float( v6_immutable ).toVar();
  12522. const v5 = float( v5_immutable ).toVar();
  12523. const v4 = float( v4_immutable ).toVar();
  12524. const v3 = float( v3_immutable ).toVar();
  12525. const v2 = float( v2_immutable ).toVar();
  12526. const v1 = float( v1_immutable ).toVar();
  12527. const v0 = float( v0_immutable ).toVar();
  12528. const s1 = float( sub( 1.0, s ) ).toVar();
  12529. const t1 = float( sub( 1.0, t ) ).toVar();
  12530. const r1 = float( sub( 1.0, r ) ).toVar();
  12531. 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 ) ) ) ) ) );
  12532. } ).setLayout( {
  12533. name: 'mx_trilerp_0',
  12534. type: 'float',
  12535. inputs: [
  12536. { name: 'v0', type: 'float' },
  12537. { name: 'v1', type: 'float' },
  12538. { name: 'v2', type: 'float' },
  12539. { name: 'v3', type: 'float' },
  12540. { name: 'v4', type: 'float' },
  12541. { name: 'v5', type: 'float' },
  12542. { name: 'v6', type: 'float' },
  12543. { name: 'v7', type: 'float' },
  12544. { name: 's', type: 'float' },
  12545. { name: 't', type: 'float' },
  12546. { name: 'r', type: 'float' }
  12547. ]
  12548. } );
  12549. 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 ] ) => {
  12550. const r = float( r_immutable ).toVar();
  12551. const t = float( t_immutable ).toVar();
  12552. const s = float( s_immutable ).toVar();
  12553. const v7 = vec3( v7_immutable ).toVar();
  12554. const v6 = vec3( v6_immutable ).toVar();
  12555. const v5 = vec3( v5_immutable ).toVar();
  12556. const v4 = vec3( v4_immutable ).toVar();
  12557. const v3 = vec3( v3_immutable ).toVar();
  12558. const v2 = vec3( v2_immutable ).toVar();
  12559. const v1 = vec3( v1_immutable ).toVar();
  12560. const v0 = vec3( v0_immutable ).toVar();
  12561. const s1 = float( sub( 1.0, s ) ).toVar();
  12562. const t1 = float( sub( 1.0, t ) ).toVar();
  12563. const r1 = float( sub( 1.0, r ) ).toVar();
  12564. 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 ) ) ) ) ) );
  12565. } ).setLayout( {
  12566. name: 'mx_trilerp_1',
  12567. type: 'vec3',
  12568. inputs: [
  12569. { name: 'v0', type: 'vec3' },
  12570. { name: 'v1', type: 'vec3' },
  12571. { name: 'v2', type: 'vec3' },
  12572. { name: 'v3', type: 'vec3' },
  12573. { name: 'v4', type: 'vec3' },
  12574. { name: 'v5', type: 'vec3' },
  12575. { name: 'v6', type: 'vec3' },
  12576. { name: 'v7', type: 'vec3' },
  12577. { name: 's', type: 'float' },
  12578. { name: 't', type: 'float' },
  12579. { name: 'r', type: 'float' }
  12580. ]
  12581. } );
  12582. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  12583. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  12584. const y = float( y_immutable ).toVar();
  12585. const x = float( x_immutable ).toVar();
  12586. const hash = uint( hash_immutable ).toVar();
  12587. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  12588. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  12589. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  12590. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  12591. } ).setLayout( {
  12592. name: 'mx_gradient_float_0',
  12593. type: 'float',
  12594. inputs: [
  12595. { name: 'hash', type: 'uint' },
  12596. { name: 'x', type: 'float' },
  12597. { name: 'y', type: 'float' }
  12598. ]
  12599. } );
  12600. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  12601. const z = float( z_immutable ).toVar();
  12602. const y = float( y_immutable ).toVar();
  12603. const x = float( x_immutable ).toVar();
  12604. const hash = uint( hash_immutable ).toVar();
  12605. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  12606. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  12607. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  12608. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  12609. } ).setLayout( {
  12610. name: 'mx_gradient_float_1',
  12611. type: 'float',
  12612. inputs: [
  12613. { name: 'hash', type: 'uint' },
  12614. { name: 'x', type: 'float' },
  12615. { name: 'y', type: 'float' },
  12616. { name: 'z', type: 'float' }
  12617. ]
  12618. } );
  12619. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  12620. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  12621. const y = float( y_immutable ).toVar();
  12622. const x = float( x_immutable ).toVar();
  12623. const hash = uvec3( hash_immutable ).toVar();
  12624. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  12625. } ).setLayout( {
  12626. name: 'mx_gradient_vec3_0',
  12627. type: 'vec3',
  12628. inputs: [
  12629. { name: 'hash', type: 'uvec3' },
  12630. { name: 'x', type: 'float' },
  12631. { name: 'y', type: 'float' }
  12632. ]
  12633. } );
  12634. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  12635. const z = float( z_immutable ).toVar();
  12636. const y = float( y_immutable ).toVar();
  12637. const x = float( x_immutable ).toVar();
  12638. const hash = uvec3( hash_immutable ).toVar();
  12639. 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 ) );
  12640. } ).setLayout( {
  12641. name: 'mx_gradient_vec3_1',
  12642. type: 'vec3',
  12643. inputs: [
  12644. { name: 'hash', type: 'uvec3' },
  12645. { name: 'x', type: 'float' },
  12646. { name: 'y', type: 'float' },
  12647. { name: 'z', type: 'float' }
  12648. ]
  12649. } );
  12650. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  12651. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  12652. const v = float( v_immutable ).toVar();
  12653. return mul( 0.6616, v );
  12654. } ).setLayout( {
  12655. name: 'mx_gradient_scale2d_0',
  12656. type: 'float',
  12657. inputs: [
  12658. { name: 'v', type: 'float' }
  12659. ]
  12660. } );
  12661. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  12662. const v = float( v_immutable ).toVar();
  12663. return mul( 0.9820, v );
  12664. } ).setLayout( {
  12665. name: 'mx_gradient_scale3d_0',
  12666. type: 'float',
  12667. inputs: [
  12668. { name: 'v', type: 'float' }
  12669. ]
  12670. } );
  12671. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  12672. const v = vec3( v_immutable ).toVar();
  12673. return mul( 0.6616, v );
  12674. } ).setLayout( {
  12675. name: 'mx_gradient_scale2d_1',
  12676. type: 'vec3',
  12677. inputs: [
  12678. { name: 'v', type: 'vec3' }
  12679. ]
  12680. } );
  12681. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  12682. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  12683. const v = vec3( v_immutable ).toVar();
  12684. return mul( 0.9820, v );
  12685. } ).setLayout( {
  12686. name: 'mx_gradient_scale3d_1',
  12687. type: 'vec3',
  12688. inputs: [
  12689. { name: 'v', type: 'vec3' }
  12690. ]
  12691. } );
  12692. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  12693. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  12694. const k = int( k_immutable ).toVar();
  12695. const x = uint( x_immutable ).toVar();
  12696. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  12697. } ).setLayout( {
  12698. name: 'mx_rotl32',
  12699. type: 'uint',
  12700. inputs: [
  12701. { name: 'x', type: 'uint' },
  12702. { name: 'k', type: 'int' }
  12703. ]
  12704. } );
  12705. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  12706. a.subAssign( c );
  12707. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  12708. c.addAssign( b );
  12709. b.subAssign( a );
  12710. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  12711. a.addAssign( c );
  12712. c.subAssign( b );
  12713. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  12714. b.addAssign( a );
  12715. a.subAssign( c );
  12716. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  12717. c.addAssign( b );
  12718. b.subAssign( a );
  12719. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  12720. a.addAssign( c );
  12721. c.subAssign( b );
  12722. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  12723. b.addAssign( a );
  12724. } );
  12725. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  12726. const c = uint( c_immutable ).toVar();
  12727. const b = uint( b_immutable ).toVar();
  12728. const a = uint( a_immutable ).toVar();
  12729. c.bitXorAssign( b );
  12730. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  12731. a.bitXorAssign( c );
  12732. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  12733. b.bitXorAssign( a );
  12734. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  12735. c.bitXorAssign( b );
  12736. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  12737. a.bitXorAssign( c );
  12738. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  12739. b.bitXorAssign( a );
  12740. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  12741. c.bitXorAssign( b );
  12742. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  12743. return c;
  12744. } ).setLayout( {
  12745. name: 'mx_bjfinal',
  12746. type: 'uint',
  12747. inputs: [
  12748. { name: 'a', type: 'uint' },
  12749. { name: 'b', type: 'uint' },
  12750. { name: 'c', type: 'uint' }
  12751. ]
  12752. } );
  12753. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  12754. const bits = uint( bits_immutable ).toVar();
  12755. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  12756. } ).setLayout( {
  12757. name: 'mx_bits_to_01',
  12758. type: 'float',
  12759. inputs: [
  12760. { name: 'bits', type: 'uint' }
  12761. ]
  12762. } );
  12763. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  12764. const t = float( t_immutable ).toVar();
  12765. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  12766. } ).setLayout( {
  12767. name: 'mx_fade',
  12768. type: 'float',
  12769. inputs: [
  12770. { name: 't', type: 'float' }
  12771. ]
  12772. } );
  12773. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  12774. const x = int( x_immutable ).toVar();
  12775. const len = uint( uint( 1 ) ).toVar();
  12776. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  12777. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  12778. } ).setLayout( {
  12779. name: 'mx_hash_int_0',
  12780. type: 'uint',
  12781. inputs: [
  12782. { name: 'x', type: 'int' }
  12783. ]
  12784. } );
  12785. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  12786. const y = int( y_immutable ).toVar();
  12787. const x = int( x_immutable ).toVar();
  12788. const len = uint( uint( 2 ) ).toVar();
  12789. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  12790. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  12791. a.addAssign( uint( x ) );
  12792. b.addAssign( uint( y ) );
  12793. return mx_bjfinal( a, b, c );
  12794. } ).setLayout( {
  12795. name: 'mx_hash_int_1',
  12796. type: 'uint',
  12797. inputs: [
  12798. { name: 'x', type: 'int' },
  12799. { name: 'y', type: 'int' }
  12800. ]
  12801. } );
  12802. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  12803. const z = int( z_immutable ).toVar();
  12804. const y = int( y_immutable ).toVar();
  12805. const x = int( x_immutable ).toVar();
  12806. const len = uint( uint( 3 ) ).toVar();
  12807. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  12808. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  12809. a.addAssign( uint( x ) );
  12810. b.addAssign( uint( y ) );
  12811. c.addAssign( uint( z ) );
  12812. return mx_bjfinal( a, b, c );
  12813. } ).setLayout( {
  12814. name: 'mx_hash_int_2',
  12815. type: 'uint',
  12816. inputs: [
  12817. { name: 'x', type: 'int' },
  12818. { name: 'y', type: 'int' },
  12819. { name: 'z', type: 'int' }
  12820. ]
  12821. } );
  12822. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  12823. const xx = int( xx_immutable ).toVar();
  12824. const z = int( z_immutable ).toVar();
  12825. const y = int( y_immutable ).toVar();
  12826. const x = int( x_immutable ).toVar();
  12827. const len = uint( uint( 4 ) ).toVar();
  12828. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  12829. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  12830. a.addAssign( uint( x ) );
  12831. b.addAssign( uint( y ) );
  12832. c.addAssign( uint( z ) );
  12833. mx_bjmix( a, b, c );
  12834. a.addAssign( uint( xx ) );
  12835. return mx_bjfinal( a, b, c );
  12836. } ).setLayout( {
  12837. name: 'mx_hash_int_3',
  12838. type: 'uint',
  12839. inputs: [
  12840. { name: 'x', type: 'int' },
  12841. { name: 'y', type: 'int' },
  12842. { name: 'z', type: 'int' },
  12843. { name: 'xx', type: 'int' }
  12844. ]
  12845. } );
  12846. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  12847. const yy = int( yy_immutable ).toVar();
  12848. const xx = int( xx_immutable ).toVar();
  12849. const z = int( z_immutable ).toVar();
  12850. const y = int( y_immutable ).toVar();
  12851. const x = int( x_immutable ).toVar();
  12852. const len = uint( uint( 5 ) ).toVar();
  12853. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  12854. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  12855. a.addAssign( uint( x ) );
  12856. b.addAssign( uint( y ) );
  12857. c.addAssign( uint( z ) );
  12858. mx_bjmix( a, b, c );
  12859. a.addAssign( uint( xx ) );
  12860. b.addAssign( uint( yy ) );
  12861. return mx_bjfinal( a, b, c );
  12862. } ).setLayout( {
  12863. name: 'mx_hash_int_4',
  12864. type: 'uint',
  12865. inputs: [
  12866. { name: 'x', type: 'int' },
  12867. { name: 'y', type: 'int' },
  12868. { name: 'z', type: 'int' },
  12869. { name: 'xx', type: 'int' },
  12870. { name: 'yy', type: 'int' }
  12871. ]
  12872. } );
  12873. 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 ] );
  12874. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  12875. const y = int( y_immutable ).toVar();
  12876. const x = int( x_immutable ).toVar();
  12877. const h = uint( mx_hash_int( x, y ) ).toVar();
  12878. const result = uvec3().toVar();
  12879. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  12880. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  12881. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  12882. return result;
  12883. } ).setLayout( {
  12884. name: 'mx_hash_vec3_0',
  12885. type: 'uvec3',
  12886. inputs: [
  12887. { name: 'x', type: 'int' },
  12888. { name: 'y', type: 'int' }
  12889. ]
  12890. } );
  12891. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  12892. const z = int( z_immutable ).toVar();
  12893. const y = int( y_immutable ).toVar();
  12894. const x = int( x_immutable ).toVar();
  12895. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  12896. const result = uvec3().toVar();
  12897. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  12898. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  12899. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  12900. return result;
  12901. } ).setLayout( {
  12902. name: 'mx_hash_vec3_1',
  12903. type: 'uvec3',
  12904. inputs: [
  12905. { name: 'x', type: 'int' },
  12906. { name: 'y', type: 'int' },
  12907. { name: 'z', type: 'int' }
  12908. ]
  12909. } );
  12910. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  12911. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  12912. const p = vec2( p_immutable ).toVar();
  12913. const X = int().toVar(), Y = int().toVar();
  12914. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  12915. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  12916. const u = float( mx_fade( fx ) ).toVar();
  12917. const v = float( mx_fade( fy ) ).toVar();
  12918. 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();
  12919. return mx_gradient_scale2d( result );
  12920. } ).setLayout( {
  12921. name: 'mx_perlin_noise_float_0',
  12922. type: 'float',
  12923. inputs: [
  12924. { name: 'p', type: 'vec2' }
  12925. ]
  12926. } );
  12927. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  12928. const p = vec3( p_immutable ).toVar();
  12929. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  12930. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  12931. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  12932. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  12933. const u = float( mx_fade( fx ) ).toVar();
  12934. const v = float( mx_fade( fy ) ).toVar();
  12935. const w = float( mx_fade( fz ) ).toVar();
  12936. 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();
  12937. return mx_gradient_scale3d( result );
  12938. } ).setLayout( {
  12939. name: 'mx_perlin_noise_float_1',
  12940. type: 'float',
  12941. inputs: [
  12942. { name: 'p', type: 'vec3' }
  12943. ]
  12944. } );
  12945. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  12946. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  12947. const p = vec2( p_immutable ).toVar();
  12948. const X = int().toVar(), Y = int().toVar();
  12949. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  12950. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  12951. const u = float( mx_fade( fx ) ).toVar();
  12952. const v = float( mx_fade( fy ) ).toVar();
  12953. 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();
  12954. return mx_gradient_scale2d( result );
  12955. } ).setLayout( {
  12956. name: 'mx_perlin_noise_vec3_0',
  12957. type: 'vec3',
  12958. inputs: [
  12959. { name: 'p', type: 'vec2' }
  12960. ]
  12961. } );
  12962. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  12963. const p = vec3( p_immutable ).toVar();
  12964. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  12965. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  12966. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  12967. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  12968. const u = float( mx_fade( fx ) ).toVar();
  12969. const v = float( mx_fade( fy ) ).toVar();
  12970. const w = float( mx_fade( fz ) ).toVar();
  12971. 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();
  12972. return mx_gradient_scale3d( result );
  12973. } ).setLayout( {
  12974. name: 'mx_perlin_noise_vec3_1',
  12975. type: 'vec3',
  12976. inputs: [
  12977. { name: 'p', type: 'vec3' }
  12978. ]
  12979. } );
  12980. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  12981. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  12982. const p = float( p_immutable ).toVar();
  12983. const ix = int( mx_floor( p ) ).toVar();
  12984. return mx_bits_to_01( mx_hash_int( ix ) );
  12985. } ).setLayout( {
  12986. name: 'mx_cell_noise_float_0',
  12987. type: 'float',
  12988. inputs: [
  12989. { name: 'p', type: 'float' }
  12990. ]
  12991. } );
  12992. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  12993. const p = vec2( p_immutable ).toVar();
  12994. const ix = int( mx_floor( p.x ) ).toVar();
  12995. const iy = int( mx_floor( p.y ) ).toVar();
  12996. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  12997. } ).setLayout( {
  12998. name: 'mx_cell_noise_float_1',
  12999. type: 'float',
  13000. inputs: [
  13001. { name: 'p', type: 'vec2' }
  13002. ]
  13003. } );
  13004. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  13005. const p = vec3( p_immutable ).toVar();
  13006. const ix = int( mx_floor( p.x ) ).toVar();
  13007. const iy = int( mx_floor( p.y ) ).toVar();
  13008. const iz = int( mx_floor( p.z ) ).toVar();
  13009. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  13010. } ).setLayout( {
  13011. name: 'mx_cell_noise_float_2',
  13012. type: 'float',
  13013. inputs: [
  13014. { name: 'p', type: 'vec3' }
  13015. ]
  13016. } );
  13017. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  13018. const p = vec4( p_immutable ).toVar();
  13019. const ix = int( mx_floor( p.x ) ).toVar();
  13020. const iy = int( mx_floor( p.y ) ).toVar();
  13021. const iz = int( mx_floor( p.z ) ).toVar();
  13022. const iw = int( mx_floor( p.w ) ).toVar();
  13023. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  13024. } ).setLayout( {
  13025. name: 'mx_cell_noise_float_3',
  13026. type: 'float',
  13027. inputs: [
  13028. { name: 'p', type: 'vec4' }
  13029. ]
  13030. } );
  13031. 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 ] );
  13032. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  13033. const p = float( p_immutable ).toVar();
  13034. const ix = int( mx_floor( p ) ).toVar();
  13035. 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 ) ) ) );
  13036. } ).setLayout( {
  13037. name: 'mx_cell_noise_vec3_0',
  13038. type: 'vec3',
  13039. inputs: [
  13040. { name: 'p', type: 'float' }
  13041. ]
  13042. } );
  13043. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  13044. const p = vec2( p_immutable ).toVar();
  13045. const ix = int( mx_floor( p.x ) ).toVar();
  13046. const iy = int( mx_floor( p.y ) ).toVar();
  13047. 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 ) ) ) );
  13048. } ).setLayout( {
  13049. name: 'mx_cell_noise_vec3_1',
  13050. type: 'vec3',
  13051. inputs: [
  13052. { name: 'p', type: 'vec2' }
  13053. ]
  13054. } );
  13055. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  13056. const p = vec3( p_immutable ).toVar();
  13057. const ix = int( mx_floor( p.x ) ).toVar();
  13058. const iy = int( mx_floor( p.y ) ).toVar();
  13059. const iz = int( mx_floor( p.z ) ).toVar();
  13060. 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 ) ) ) );
  13061. } ).setLayout( {
  13062. name: 'mx_cell_noise_vec3_2',
  13063. type: 'vec3',
  13064. inputs: [
  13065. { name: 'p', type: 'vec3' }
  13066. ]
  13067. } );
  13068. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  13069. const p = vec4( p_immutable ).toVar();
  13070. const ix = int( mx_floor( p.x ) ).toVar();
  13071. const iy = int( mx_floor( p.y ) ).toVar();
  13072. const iz = int( mx_floor( p.z ) ).toVar();
  13073. const iw = int( mx_floor( p.w ) ).toVar();
  13074. 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 ) ) ) );
  13075. } ).setLayout( {
  13076. name: 'mx_cell_noise_vec3_3',
  13077. type: 'vec3',
  13078. inputs: [
  13079. { name: 'p', type: 'vec4' }
  13080. ]
  13081. } );
  13082. 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 ] );
  13083. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  13084. const diminish = float( diminish_immutable ).toVar();
  13085. const lacunarity = float( lacunarity_immutable ).toVar();
  13086. const octaves = int( octaves_immutable ).toVar();
  13087. const p = vec3( p_immutable ).toVar();
  13088. const result = float( 0.0 ).toVar();
  13089. const amplitude = float( 1.0 ).toVar();
  13090. Loop( octaves, () => {
  13091. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  13092. amplitude.mulAssign( diminish );
  13093. p.mulAssign( lacunarity );
  13094. } );
  13095. return result;
  13096. } ).setLayout( {
  13097. name: 'mx_fractal_noise_float',
  13098. type: 'float',
  13099. inputs: [
  13100. { name: 'p', type: 'vec3' },
  13101. { name: 'octaves', type: 'int' },
  13102. { name: 'lacunarity', type: 'float' },
  13103. { name: 'diminish', type: 'float' }
  13104. ]
  13105. } );
  13106. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  13107. const diminish = float( diminish_immutable ).toVar();
  13108. const lacunarity = float( lacunarity_immutable ).toVar();
  13109. const octaves = int( octaves_immutable ).toVar();
  13110. const p = vec3( p_immutable ).toVar();
  13111. const result = vec3( 0.0 ).toVar();
  13112. const amplitude = float( 1.0 ).toVar();
  13113. Loop( octaves, () => {
  13114. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  13115. amplitude.mulAssign( diminish );
  13116. p.mulAssign( lacunarity );
  13117. } );
  13118. return result;
  13119. } ).setLayout( {
  13120. name: 'mx_fractal_noise_vec3',
  13121. type: 'vec3',
  13122. inputs: [
  13123. { name: 'p', type: 'vec3' },
  13124. { name: 'octaves', type: 'int' },
  13125. { name: 'lacunarity', type: 'float' },
  13126. { name: 'diminish', type: 'float' }
  13127. ]
  13128. } );
  13129. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  13130. const diminish = float( diminish_immutable ).toVar();
  13131. const lacunarity = float( lacunarity_immutable ).toVar();
  13132. const octaves = int( octaves_immutable ).toVar();
  13133. const p = vec3( p_immutable ).toVar();
  13134. 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 ) );
  13135. } ).setLayout( {
  13136. name: 'mx_fractal_noise_vec2',
  13137. type: 'vec2',
  13138. inputs: [
  13139. { name: 'p', type: 'vec3' },
  13140. { name: 'octaves', type: 'int' },
  13141. { name: 'lacunarity', type: 'float' },
  13142. { name: 'diminish', type: 'float' }
  13143. ]
  13144. } );
  13145. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  13146. const diminish = float( diminish_immutable ).toVar();
  13147. const lacunarity = float( lacunarity_immutable ).toVar();
  13148. const octaves = int( octaves_immutable ).toVar();
  13149. const p = vec3( p_immutable ).toVar();
  13150. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  13151. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  13152. return vec4( c, f );
  13153. } ).setLayout( {
  13154. name: 'mx_fractal_noise_vec4',
  13155. type: 'vec4',
  13156. inputs: [
  13157. { name: 'p', type: 'vec3' },
  13158. { name: 'octaves', type: 'int' },
  13159. { name: 'lacunarity', type: 'float' },
  13160. { name: 'diminish', type: 'float' }
  13161. ]
  13162. } );
  13163. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  13164. const metric = int( metric_immutable ).toVar();
  13165. const jitter = float( jitter_immutable ).toVar();
  13166. const yoff = int( yoff_immutable ).toVar();
  13167. const xoff = int( xoff_immutable ).toVar();
  13168. const y = int( y_immutable ).toVar();
  13169. const x = int( x_immutable ).toVar();
  13170. const p = vec2( p_immutable ).toVar();
  13171. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  13172. const off = vec2( tmp.x, tmp.y ).toVar();
  13173. off.subAssign( 0.5 );
  13174. off.mulAssign( jitter );
  13175. off.addAssign( 0.5 );
  13176. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  13177. const diff = vec2( cellpos.sub( p ) ).toVar();
  13178. If( metric.equal( int( 2 ) ), () => {
  13179. return abs( diff.x ).add( abs( diff.y ) );
  13180. } );
  13181. If( metric.equal( int( 3 ) ), () => {
  13182. return max$1( abs( diff.x ), abs( diff.y ) );
  13183. } );
  13184. return dot( diff, diff );
  13185. } ).setLayout( {
  13186. name: 'mx_worley_distance_0',
  13187. type: 'float',
  13188. inputs: [
  13189. { name: 'p', type: 'vec2' },
  13190. { name: 'x', type: 'int' },
  13191. { name: 'y', type: 'int' },
  13192. { name: 'xoff', type: 'int' },
  13193. { name: 'yoff', type: 'int' },
  13194. { name: 'jitter', type: 'float' },
  13195. { name: 'metric', type: 'int' }
  13196. ]
  13197. } );
  13198. 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 ] ) => {
  13199. const metric = int( metric_immutable ).toVar();
  13200. const jitter = float( jitter_immutable ).toVar();
  13201. const zoff = int( zoff_immutable ).toVar();
  13202. const yoff = int( yoff_immutable ).toVar();
  13203. const xoff = int( xoff_immutable ).toVar();
  13204. const z = int( z_immutable ).toVar();
  13205. const y = int( y_immutable ).toVar();
  13206. const x = int( x_immutable ).toVar();
  13207. const p = vec3( p_immutable ).toVar();
  13208. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  13209. off.subAssign( 0.5 );
  13210. off.mulAssign( jitter );
  13211. off.addAssign( 0.5 );
  13212. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  13213. const diff = vec3( cellpos.sub( p ) ).toVar();
  13214. If( metric.equal( int( 2 ) ), () => {
  13215. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  13216. } );
  13217. If( metric.equal( int( 3 ) ), () => {
  13218. return max$1( max$1( abs( diff.x ), abs( diff.y ) ), abs( diff.z ) );
  13219. } );
  13220. return dot( diff, diff );
  13221. } ).setLayout( {
  13222. name: 'mx_worley_distance_1',
  13223. type: 'float',
  13224. inputs: [
  13225. { name: 'p', type: 'vec3' },
  13226. { name: 'x', type: 'int' },
  13227. { name: 'y', type: 'int' },
  13228. { name: 'z', type: 'int' },
  13229. { name: 'xoff', type: 'int' },
  13230. { name: 'yoff', type: 'int' },
  13231. { name: 'zoff', type: 'int' },
  13232. { name: 'jitter', type: 'float' },
  13233. { name: 'metric', type: 'int' }
  13234. ]
  13235. } );
  13236. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  13237. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  13238. const metric = int( metric_immutable ).toVar();
  13239. const jitter = float( jitter_immutable ).toVar();
  13240. const p = vec2( p_immutable ).toVar();
  13241. const X = int().toVar(), Y = int().toVar();
  13242. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  13243. const sqdist = float( 1e6 ).toVar();
  13244. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  13245. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  13246. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  13247. sqdist.assign( min$1( sqdist, dist ) );
  13248. } );
  13249. } );
  13250. If( metric.equal( int( 0 ) ), () => {
  13251. sqdist.assign( sqrt( sqdist ) );
  13252. } );
  13253. return sqdist;
  13254. } ).setLayout( {
  13255. name: 'mx_worley_noise_float_0',
  13256. type: 'float',
  13257. inputs: [
  13258. { name: 'p', type: 'vec2' },
  13259. { name: 'jitter', type: 'float' },
  13260. { name: 'metric', type: 'int' }
  13261. ]
  13262. } );
  13263. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  13264. const metric = int( metric_immutable ).toVar();
  13265. const jitter = float( jitter_immutable ).toVar();
  13266. const p = vec2( p_immutable ).toVar();
  13267. const X = int().toVar(), Y = int().toVar();
  13268. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  13269. const sqdist = vec2( 1e6, 1e6 ).toVar();
  13270. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  13271. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  13272. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  13273. If( dist.lessThan( sqdist.x ), () => {
  13274. sqdist.y.assign( sqdist.x );
  13275. sqdist.x.assign( dist );
  13276. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  13277. sqdist.y.assign( dist );
  13278. } );
  13279. } );
  13280. } );
  13281. If( metric.equal( int( 0 ) ), () => {
  13282. sqdist.assign( sqrt( sqdist ) );
  13283. } );
  13284. return sqdist;
  13285. } ).setLayout( {
  13286. name: 'mx_worley_noise_vec2_0',
  13287. type: 'vec2',
  13288. inputs: [
  13289. { name: 'p', type: 'vec2' },
  13290. { name: 'jitter', type: 'float' },
  13291. { name: 'metric', type: 'int' }
  13292. ]
  13293. } );
  13294. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  13295. const metric = int( metric_immutable ).toVar();
  13296. const jitter = float( jitter_immutable ).toVar();
  13297. const p = vec2( p_immutable ).toVar();
  13298. const X = int().toVar(), Y = int().toVar();
  13299. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  13300. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  13301. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  13302. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  13303. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  13304. If( dist.lessThan( sqdist.x ), () => {
  13305. sqdist.z.assign( sqdist.y );
  13306. sqdist.y.assign( sqdist.x );
  13307. sqdist.x.assign( dist );
  13308. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  13309. sqdist.z.assign( sqdist.y );
  13310. sqdist.y.assign( dist );
  13311. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  13312. sqdist.z.assign( dist );
  13313. } );
  13314. } );
  13315. } );
  13316. If( metric.equal( int( 0 ) ), () => {
  13317. sqdist.assign( sqrt( sqdist ) );
  13318. } );
  13319. return sqdist;
  13320. } ).setLayout( {
  13321. name: 'mx_worley_noise_vec3_0',
  13322. type: 'vec3',
  13323. inputs: [
  13324. { name: 'p', type: 'vec2' },
  13325. { name: 'jitter', type: 'float' },
  13326. { name: 'metric', type: 'int' }
  13327. ]
  13328. } );
  13329. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  13330. const metric = int( metric_immutable ).toVar();
  13331. const jitter = float( jitter_immutable ).toVar();
  13332. const p = vec3( p_immutable ).toVar();
  13333. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  13334. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  13335. const sqdist = float( 1e6 ).toVar();
  13336. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  13337. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  13338. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  13339. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  13340. sqdist.assign( min$1( sqdist, dist ) );
  13341. } );
  13342. } );
  13343. } );
  13344. If( metric.equal( int( 0 ) ), () => {
  13345. sqdist.assign( sqrt( sqdist ) );
  13346. } );
  13347. return sqdist;
  13348. } ).setLayout( {
  13349. name: 'mx_worley_noise_float_1',
  13350. type: 'float',
  13351. inputs: [
  13352. { name: 'p', type: 'vec3' },
  13353. { name: 'jitter', type: 'float' },
  13354. { name: 'metric', type: 'int' }
  13355. ]
  13356. } );
  13357. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  13358. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  13359. const metric = int( metric_immutable ).toVar();
  13360. const jitter = float( jitter_immutable ).toVar();
  13361. const p = vec3( p_immutable ).toVar();
  13362. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  13363. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  13364. const sqdist = vec2( 1e6, 1e6 ).toVar();
  13365. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  13366. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  13367. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  13368. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  13369. If( dist.lessThan( sqdist.x ), () => {
  13370. sqdist.y.assign( sqdist.x );
  13371. sqdist.x.assign( dist );
  13372. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  13373. sqdist.y.assign( dist );
  13374. } );
  13375. } );
  13376. } );
  13377. } );
  13378. If( metric.equal( int( 0 ) ), () => {
  13379. sqdist.assign( sqrt( sqdist ) );
  13380. } );
  13381. return sqdist;
  13382. } ).setLayout( {
  13383. name: 'mx_worley_noise_vec2_1',
  13384. type: 'vec2',
  13385. inputs: [
  13386. { name: 'p', type: 'vec3' },
  13387. { name: 'jitter', type: 'float' },
  13388. { name: 'metric', type: 'int' }
  13389. ]
  13390. } );
  13391. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  13392. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  13393. const metric = int( metric_immutable ).toVar();
  13394. const jitter = float( jitter_immutable ).toVar();
  13395. const p = vec3( p_immutable ).toVar();
  13396. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  13397. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  13398. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  13399. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  13400. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  13401. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  13402. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  13403. If( dist.lessThan( sqdist.x ), () => {
  13404. sqdist.z.assign( sqdist.y );
  13405. sqdist.y.assign( sqdist.x );
  13406. sqdist.x.assign( dist );
  13407. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  13408. sqdist.z.assign( sqdist.y );
  13409. sqdist.y.assign( dist );
  13410. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  13411. sqdist.z.assign( dist );
  13412. } );
  13413. } );
  13414. } );
  13415. } );
  13416. If( metric.equal( int( 0 ) ), () => {
  13417. sqdist.assign( sqrt( sqdist ) );
  13418. } );
  13419. return sqdist;
  13420. } ).setLayout( {
  13421. name: 'mx_worley_noise_vec3_1',
  13422. type: 'vec3',
  13423. inputs: [
  13424. { name: 'p', type: 'vec3' },
  13425. { name: 'jitter', type: 'float' },
  13426. { name: 'metric', type: 'int' }
  13427. ]
  13428. } );
  13429. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  13430. // Three.js Transpiler
  13431. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  13432. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  13433. const s = hsv.y;
  13434. const v = hsv.z;
  13435. const result = vec3().toVar();
  13436. If( s.lessThan( 0.0001 ), () => {
  13437. result.assign( vec3( v, v, v ) );
  13438. } ).Else( () => {
  13439. let h = hsv.x;
  13440. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  13441. const hi = int( trunc( h ) );
  13442. const f = h.sub( float( hi ) );
  13443. const p = v.mul( s.oneMinus() );
  13444. const q = v.mul( s.mul( f ).oneMinus() );
  13445. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  13446. If( hi.equal( int( 0 ) ), () => {
  13447. result.assign( vec3( v, t, p ) );
  13448. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  13449. result.assign( vec3( q, v, p ) );
  13450. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  13451. result.assign( vec3( p, v, t ) );
  13452. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  13453. result.assign( vec3( p, q, v ) );
  13454. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  13455. result.assign( vec3( t, p, v ) );
  13456. } ).Else( () => {
  13457. result.assign( vec3( v, p, q ) );
  13458. } );
  13459. } );
  13460. return result;
  13461. } ).setLayout( {
  13462. name: 'mx_hsvtorgb',
  13463. type: 'vec3',
  13464. inputs: [
  13465. { name: 'hsv', type: 'vec3' }
  13466. ]
  13467. } );
  13468. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  13469. const c = vec3( c_immutable ).toVar();
  13470. const r = float( c.x ).toVar();
  13471. const g = float( c.y ).toVar();
  13472. const b = float( c.z ).toVar();
  13473. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  13474. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  13475. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  13476. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  13477. v.assign( maxcomp );
  13478. If( maxcomp.greaterThan( 0.0 ), () => {
  13479. s.assign( delta.div( maxcomp ) );
  13480. } ).Else( () => {
  13481. s.assign( 0.0 );
  13482. } );
  13483. If( s.lessThanEqual( 0.0 ), () => {
  13484. h.assign( 0.0 );
  13485. } ).Else( () => {
  13486. If( r.greaterThanEqual( maxcomp ), () => {
  13487. h.assign( g.sub( b ).div( delta ) );
  13488. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  13489. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  13490. } ).Else( () => {
  13491. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  13492. } );
  13493. h.mulAssign( 1.0 / 6.0 );
  13494. If( h.lessThan( 0.0 ), () => {
  13495. h.addAssign( 1.0 );
  13496. } );
  13497. } );
  13498. return vec3( h, s, v );
  13499. } ).setLayout( {
  13500. name: 'mx_rgbtohsv',
  13501. type: 'vec3',
  13502. inputs: [
  13503. { name: 'c', type: 'vec3' }
  13504. ]
  13505. } );
  13506. // Three.js Transpiler
  13507. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  13508. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  13509. const color = vec3( color_immutable ).toVar();
  13510. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  13511. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  13512. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  13513. return mix( linSeg, powSeg, isAbove );
  13514. } ).setLayout( {
  13515. name: 'mx_srgb_texture_to_lin_rec709',
  13516. type: 'vec3',
  13517. inputs: [
  13518. { name: 'color', type: 'vec3' }
  13519. ]
  13520. } );
  13521. const mx_aastep = ( threshold, value ) => {
  13522. threshold = float( threshold );
  13523. value = float( value );
  13524. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  13525. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  13526. };
  13527. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  13528. const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' );
  13529. const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' );
  13530. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  13531. const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' );
  13532. const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' );
  13533. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  13534. const mx_safepower = ( in1, in2 = 1 ) => {
  13535. in1 = float( in1 );
  13536. return in1.abs().pow( in2 ).mul( in1.sign() );
  13537. };
  13538. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  13539. const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  13540. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  13541. const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  13542. const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => {
  13543. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  13544. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  13545. return noise_vec4.mul( amplitude ).add( pivot );
  13546. };
  13547. const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  13548. const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  13549. const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  13550. const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  13551. 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 );
  13552. 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 );
  13553. 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 );
  13554. 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 );
  13555. // https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html
  13556. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  13557. const nDir = normalize( normal ).toVar( 'nDir' );
  13558. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmax' );
  13559. const rbmin = sub( float( - 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmin' );
  13560. const rbminmax = vec3().toVar( 'rbminmax' );
  13561. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  13562. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  13563. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  13564. const correction = min$1( min$1( rbminmax.x, rbminmax.y ), rbminmax.z ).toVar( 'correction' );
  13565. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar( 'boxIntersection' );
  13566. return boxIntersection.sub( cubePos );
  13567. } );
  13568. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  13569. // normal is assumed to have unit length
  13570. const x = normal.x, y = normal.y, z = normal.z;
  13571. // band 0
  13572. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  13573. // band 1
  13574. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  13575. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  13576. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  13577. // band 2
  13578. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  13579. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  13580. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  13581. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  13582. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  13583. return result;
  13584. } );
  13585. // constants
  13586. var TSL = /*#__PURE__*/Object.freeze({
  13587. __proto__: null,
  13588. BRDF_GGX: BRDF_GGX,
  13589. BRDF_Lambert: BRDF_Lambert,
  13590. BasicShadowFilter: BasicShadowFilter,
  13591. Break: Break,
  13592. Continue: Continue,
  13593. DFGApprox: DFGApprox,
  13594. D_GGX: D_GGX,
  13595. Discard: Discard,
  13596. EPSILON: EPSILON,
  13597. F_Schlick: F_Schlick,
  13598. Fn: Fn,
  13599. INFINITY: INFINITY,
  13600. If: If,
  13601. Loop: Loop,
  13602. NodeAccess: NodeAccess,
  13603. NodeShaderStage: NodeShaderStage,
  13604. NodeType: NodeType,
  13605. NodeUpdateType: NodeUpdateType,
  13606. PCFShadowFilter: PCFShadowFilter,
  13607. PCFSoftShadowFilter: PCFSoftShadowFilter,
  13608. PI: PI,
  13609. PI2: PI2,
  13610. Return: Return,
  13611. Schlick_to_F0: Schlick_to_F0,
  13612. ScriptableNodeResources: ScriptableNodeResources,
  13613. ShaderNode: ShaderNode,
  13614. TBNViewMatrix: TBNViewMatrix,
  13615. VSMShadowFilter: VSMShadowFilter,
  13616. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  13617. abs: abs,
  13618. acesFilmicToneMapping: acesFilmicToneMapping,
  13619. acos: acos,
  13620. add: add,
  13621. addMethodChaining: addMethodChaining,
  13622. addNodeElement: addNodeElement,
  13623. agxToneMapping: agxToneMapping,
  13624. all: all,
  13625. alphaT: alphaT,
  13626. and: and,
  13627. anisotropy: anisotropy,
  13628. anisotropyB: anisotropyB,
  13629. anisotropyT: anisotropyT,
  13630. any: any,
  13631. append: append,
  13632. arrayBuffer: arrayBuffer,
  13633. asin: asin,
  13634. assign: assign,
  13635. atan: atan,
  13636. atan2: atan2,
  13637. atomicAdd: atomicAdd,
  13638. atomicAnd: atomicAnd,
  13639. atomicFunc: atomicFunc,
  13640. atomicMax: atomicMax,
  13641. atomicMin: atomicMin,
  13642. atomicOr: atomicOr,
  13643. atomicStore: atomicStore,
  13644. atomicSub: atomicSub,
  13645. atomicXor: atomicXor,
  13646. attenuationColor: attenuationColor,
  13647. attenuationDistance: attenuationDistance,
  13648. attribute: attribute,
  13649. attributeArray: attributeArray,
  13650. backgroundBlurriness: backgroundBlurriness,
  13651. backgroundIntensity: backgroundIntensity,
  13652. backgroundRotation: backgroundRotation,
  13653. batch: batch,
  13654. billboarding: billboarding,
  13655. bitAnd: bitAnd,
  13656. bitNot: bitNot,
  13657. bitOr: bitOr,
  13658. bitXor: bitXor,
  13659. bitangentGeometry: bitangentGeometry,
  13660. bitangentLocal: bitangentLocal,
  13661. bitangentView: bitangentView,
  13662. bitangentWorld: bitangentWorld,
  13663. bitcast: bitcast,
  13664. blendBurn: blendBurn,
  13665. blendColor: blendColor,
  13666. blendDodge: blendDodge,
  13667. blendOverlay: blendOverlay,
  13668. blendScreen: blendScreen,
  13669. blur: blur,
  13670. bool: bool,
  13671. buffer: buffer,
  13672. bufferAttribute: bufferAttribute,
  13673. bumpMap: bumpMap,
  13674. burn: burn,
  13675. bvec2: bvec2,
  13676. bvec3: bvec3,
  13677. bvec4: bvec4,
  13678. bypass: bypass,
  13679. cache: cache,
  13680. call: call,
  13681. cameraFar: cameraFar,
  13682. cameraNear: cameraNear,
  13683. cameraNormalMatrix: cameraNormalMatrix,
  13684. cameraPosition: cameraPosition,
  13685. cameraProjectionMatrix: cameraProjectionMatrix,
  13686. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  13687. cameraViewMatrix: cameraViewMatrix,
  13688. cameraWorldMatrix: cameraWorldMatrix,
  13689. cbrt: cbrt,
  13690. cdl: cdl,
  13691. ceil: ceil,
  13692. checker: checker,
  13693. cineonToneMapping: cineonToneMapping,
  13694. clamp: clamp,
  13695. clearcoat: clearcoat,
  13696. clearcoatRoughness: clearcoatRoughness,
  13697. code: code,
  13698. color: color,
  13699. colorSpaceToWorking: colorSpaceToWorking,
  13700. colorToDirection: colorToDirection,
  13701. compute: compute,
  13702. cond: cond,
  13703. context: context,
  13704. convert: convert,
  13705. convertColorSpace: convertColorSpace,
  13706. convertToTexture: convertToTexture,
  13707. cos: cos,
  13708. cross: cross,
  13709. cubeTexture: cubeTexture,
  13710. dFdx: dFdx,
  13711. dFdy: dFdy,
  13712. dashSize: dashSize,
  13713. defaultBuildStages: defaultBuildStages,
  13714. defaultShaderStages: defaultShaderStages,
  13715. defined: defined,
  13716. degrees: degrees,
  13717. deltaTime: deltaTime,
  13718. densityFog: densityFog,
  13719. depth: depth,
  13720. depthPass: depthPass,
  13721. difference: difference,
  13722. diffuseColor: diffuseColor,
  13723. directPointLight: directPointLight,
  13724. directionToColor: directionToColor,
  13725. dispersion: dispersion,
  13726. distance: distance,
  13727. div: div,
  13728. dodge: dodge,
  13729. dot: dot,
  13730. drawIndex: drawIndex,
  13731. dynamicBufferAttribute: dynamicBufferAttribute,
  13732. element: element,
  13733. emissive: emissive,
  13734. equal: equal,
  13735. equals: equals,
  13736. equirectUV: equirectUV,
  13737. exp: exp,
  13738. exp2: exp2,
  13739. expression: expression,
  13740. faceDirection: faceDirection,
  13741. faceForward: faceForward,
  13742. float: float,
  13743. floor: floor,
  13744. fog: fog,
  13745. fract: fract,
  13746. frameGroup: frameGroup,
  13747. frameId: frameId,
  13748. frontFacing: frontFacing,
  13749. fwidth: fwidth,
  13750. gain: gain,
  13751. gapSize: gapSize,
  13752. getConstNodeType: getConstNodeType,
  13753. getCurrentStack: getCurrentStack,
  13754. getDirection: getDirection,
  13755. getDistanceAttenuation: getDistanceAttenuation,
  13756. getGeometryRoughness: getGeometryRoughness,
  13757. getNormalFromDepth: getNormalFromDepth,
  13758. getParallaxCorrectNormal: getParallaxCorrectNormal,
  13759. getRoughness: getRoughness,
  13760. getScreenPosition: getScreenPosition,
  13761. getShIrradianceAt: getShIrradianceAt,
  13762. getTextureIndex: getTextureIndex,
  13763. getViewPosition: getViewPosition,
  13764. glsl: glsl,
  13765. glslFn: glslFn,
  13766. grayscale: grayscale,
  13767. greaterThan: greaterThan,
  13768. greaterThanEqual: greaterThanEqual,
  13769. hash: hash,
  13770. highPrecisionModelNormalViewMatrix: highPrecisionModelNormalViewMatrix,
  13771. highPrecisionModelViewMatrix: highPrecisionModelViewMatrix,
  13772. hue: hue,
  13773. instance: instance,
  13774. instanceIndex: instanceIndex,
  13775. instancedArray: instancedArray,
  13776. instancedBufferAttribute: instancedBufferAttribute,
  13777. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  13778. instancedMesh: instancedMesh,
  13779. int: int,
  13780. inverseSqrt: inverseSqrt,
  13781. invocationLocalIndex: invocationLocalIndex,
  13782. invocationSubgroupIndex: invocationSubgroupIndex,
  13783. ior: ior,
  13784. iridescence: iridescence,
  13785. iridescenceIOR: iridescenceIOR,
  13786. iridescenceThickness: iridescenceThickness,
  13787. ivec2: ivec2,
  13788. ivec3: ivec3,
  13789. ivec4: ivec4,
  13790. js: js,
  13791. label: label,
  13792. length: length,
  13793. lengthSq: lengthSq,
  13794. lessThan: lessThan,
  13795. lessThanEqual: lessThanEqual,
  13796. lightPosition: lightPosition,
  13797. lightProjectionUV: lightProjectionUV,
  13798. lightShadowMatrix: lightShadowMatrix,
  13799. lightTargetDirection: lightTargetDirection,
  13800. lightTargetPosition: lightTargetPosition,
  13801. lightViewPosition: lightViewPosition,
  13802. lightingContext: lightingContext,
  13803. lights: lights,
  13804. linearDepth: linearDepth,
  13805. linearToneMapping: linearToneMapping,
  13806. localId: localId,
  13807. log: log,
  13808. log2: log2,
  13809. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  13810. loop: loop,
  13811. luminance: luminance,
  13812. mat2: mat2,
  13813. mat3: mat3,
  13814. mat4: mat4,
  13815. matcapUV: matcapUV,
  13816. materialAOMap: materialAOMap,
  13817. materialAlphaTest: materialAlphaTest,
  13818. materialAnisotropy: materialAnisotropy,
  13819. materialAnisotropyVector: materialAnisotropyVector,
  13820. materialAttenuationColor: materialAttenuationColor,
  13821. materialAttenuationDistance: materialAttenuationDistance,
  13822. materialClearcoat: materialClearcoat,
  13823. materialClearcoatNormal: materialClearcoatNormal,
  13824. materialClearcoatRoughness: materialClearcoatRoughness,
  13825. materialColor: materialColor,
  13826. materialDispersion: materialDispersion,
  13827. materialEmissive: materialEmissive,
  13828. materialIOR: materialIOR,
  13829. materialIridescence: materialIridescence,
  13830. materialIridescenceIOR: materialIridescenceIOR,
  13831. materialIridescenceThickness: materialIridescenceThickness,
  13832. materialLightMap: materialLightMap,
  13833. materialLineDashOffset: materialLineDashOffset,
  13834. materialLineDashSize: materialLineDashSize,
  13835. materialLineGapSize: materialLineGapSize,
  13836. materialLineScale: materialLineScale,
  13837. materialLineWidth: materialLineWidth,
  13838. materialMetalness: materialMetalness,
  13839. materialNormal: materialNormal,
  13840. materialOpacity: materialOpacity,
  13841. materialPointWidth: materialPointWidth,
  13842. materialReference: materialReference,
  13843. materialReflectivity: materialReflectivity,
  13844. materialRefractionRatio: materialRefractionRatio,
  13845. materialRotation: materialRotation,
  13846. materialRoughness: materialRoughness,
  13847. materialSheen: materialSheen,
  13848. materialSheenRoughness: materialSheenRoughness,
  13849. materialShininess: materialShininess,
  13850. materialSpecular: materialSpecular,
  13851. materialSpecularColor: materialSpecularColor,
  13852. materialSpecularIntensity: materialSpecularIntensity,
  13853. materialSpecularStrength: materialSpecularStrength,
  13854. materialThickness: materialThickness,
  13855. materialTransmission: materialTransmission,
  13856. max: max$1,
  13857. maxMipLevel: maxMipLevel,
  13858. metalness: metalness,
  13859. min: min$1,
  13860. mix: mix,
  13861. mixElement: mixElement,
  13862. mod: mod,
  13863. modInt: modInt,
  13864. modelDirection: modelDirection,
  13865. modelNormalMatrix: modelNormalMatrix,
  13866. modelPosition: modelPosition,
  13867. modelScale: modelScale,
  13868. modelViewMatrix: modelViewMatrix,
  13869. modelViewPosition: modelViewPosition,
  13870. modelViewProjection: modelViewProjection,
  13871. modelWorldMatrix: modelWorldMatrix,
  13872. modelWorldMatrixInverse: modelWorldMatrixInverse,
  13873. morphReference: morphReference,
  13874. mrt: mrt,
  13875. mul: mul,
  13876. mx_aastep: mx_aastep,
  13877. mx_cell_noise_float: mx_cell_noise_float,
  13878. mx_contrast: mx_contrast,
  13879. mx_fractal_noise_float: mx_fractal_noise_float,
  13880. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  13881. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  13882. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  13883. mx_hsvtorgb: mx_hsvtorgb,
  13884. mx_noise_float: mx_noise_float,
  13885. mx_noise_vec3: mx_noise_vec3,
  13886. mx_noise_vec4: mx_noise_vec4,
  13887. mx_ramplr: mx_ramplr,
  13888. mx_ramptb: mx_ramptb,
  13889. mx_rgbtohsv: mx_rgbtohsv,
  13890. mx_safepower: mx_safepower,
  13891. mx_splitlr: mx_splitlr,
  13892. mx_splittb: mx_splittb,
  13893. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  13894. mx_transform_uv: mx_transform_uv,
  13895. mx_worley_noise_float: mx_worley_noise_float,
  13896. mx_worley_noise_vec2: mx_worley_noise_vec2,
  13897. mx_worley_noise_vec3: mx_worley_noise_vec3,
  13898. negate: negate,
  13899. neutralToneMapping: neutralToneMapping,
  13900. nodeArray: nodeArray,
  13901. nodeImmutable: nodeImmutable,
  13902. nodeObject: nodeObject,
  13903. nodeObjects: nodeObjects,
  13904. nodeProxy: nodeProxy,
  13905. normalFlat: normalFlat,
  13906. normalGeometry: normalGeometry,
  13907. normalLocal: normalLocal,
  13908. normalMap: normalMap,
  13909. normalView: normalView,
  13910. normalWorld: normalWorld,
  13911. normalize: normalize,
  13912. not: not,
  13913. notEqual: notEqual,
  13914. numWorkgroups: numWorkgroups,
  13915. objectDirection: objectDirection,
  13916. objectGroup: objectGroup,
  13917. objectPosition: objectPosition,
  13918. objectScale: objectScale,
  13919. objectViewPosition: objectViewPosition,
  13920. objectWorldMatrix: objectWorldMatrix,
  13921. oneMinus: oneMinus,
  13922. or: or,
  13923. orthographicDepthToViewZ: orthographicDepthToViewZ,
  13924. oscSawtooth: oscSawtooth,
  13925. oscSine: oscSine,
  13926. oscSquare: oscSquare,
  13927. oscTriangle: oscTriangle,
  13928. output: output,
  13929. outputStruct: outputStruct,
  13930. overlay: overlay,
  13931. overloadingFn: overloadingFn,
  13932. parabola: parabola,
  13933. parallaxDirection: parallaxDirection,
  13934. parallaxUV: parallaxUV,
  13935. parameter: parameter,
  13936. pass: pass,
  13937. passTexture: passTexture,
  13938. pcurve: pcurve,
  13939. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  13940. pmremTexture: pmremTexture,
  13941. pointUV: pointUV,
  13942. pointWidth: pointWidth,
  13943. positionGeometry: positionGeometry,
  13944. positionLocal: positionLocal,
  13945. positionPrevious: positionPrevious,
  13946. positionView: positionView,
  13947. positionViewDirection: positionViewDirection,
  13948. positionWorld: positionWorld,
  13949. positionWorldDirection: positionWorldDirection,
  13950. posterize: posterize,
  13951. pow: pow,
  13952. pow2: pow2,
  13953. pow3: pow3,
  13954. pow4: pow4,
  13955. property: property,
  13956. radians: radians,
  13957. rand: rand,
  13958. range: range,
  13959. rangeFog: rangeFog,
  13960. reciprocal: reciprocal,
  13961. reference: reference,
  13962. referenceBuffer: referenceBuffer,
  13963. reflect: reflect,
  13964. reflectVector: reflectVector,
  13965. reflectView: reflectView,
  13966. reflector: reflector,
  13967. refract: refract,
  13968. refractVector: refractVector,
  13969. refractView: refractView,
  13970. reinhardToneMapping: reinhardToneMapping,
  13971. remainder: remainder,
  13972. remap: remap,
  13973. remapClamp: remapClamp,
  13974. renderGroup: renderGroup,
  13975. renderOutput: renderOutput,
  13976. rendererReference: rendererReference,
  13977. rotate: rotate,
  13978. rotateUV: rotateUV,
  13979. roughness: roughness,
  13980. round: round,
  13981. rtt: rtt,
  13982. sRGBTransferEOTF: sRGBTransferEOTF,
  13983. sRGBTransferOETF: sRGBTransferOETF,
  13984. sampler: sampler,
  13985. saturate: saturate,
  13986. saturation: saturation,
  13987. screen: screen,
  13988. screenCoordinate: screenCoordinate,
  13989. screenSize: screenSize,
  13990. screenUV: screenUV,
  13991. scriptable: scriptable,
  13992. scriptableValue: scriptableValue,
  13993. select: select,
  13994. setCurrentStack: setCurrentStack,
  13995. shaderStages: shaderStages,
  13996. shadow: shadow,
  13997. sharedUniformGroup: sharedUniformGroup,
  13998. sheen: sheen,
  13999. sheenRoughness: sheenRoughness,
  14000. shiftLeft: shiftLeft,
  14001. shiftRight: shiftRight,
  14002. shininess: shininess,
  14003. sign: sign,
  14004. sin: sin,
  14005. sinc: sinc,
  14006. skinning: skinning,
  14007. skinningReference: skinningReference,
  14008. smoothstep: smoothstep,
  14009. smoothstepElement: smoothstepElement,
  14010. specularColor: specularColor,
  14011. specularF90: specularF90,
  14012. spherizeUV: spherizeUV,
  14013. split: split,
  14014. spritesheetUV: spritesheetUV,
  14015. sqrt: sqrt,
  14016. stack: stack,
  14017. step: step,
  14018. storage: storage,
  14019. storageBarrier: storageBarrier,
  14020. storageObject: storageObject,
  14021. storageTexture: storageTexture,
  14022. string: string,
  14023. sub: sub,
  14024. subgroupIndex: subgroupIndex,
  14025. subgroupSize: subgroupSize,
  14026. tan: tan,
  14027. tangentGeometry: tangentGeometry,
  14028. tangentLocal: tangentLocal,
  14029. tangentView: tangentView,
  14030. tangentWorld: tangentWorld,
  14031. temp: temp,
  14032. texture: texture,
  14033. texture3D: texture3D,
  14034. textureBarrier: textureBarrier,
  14035. textureBicubic: textureBicubic,
  14036. textureCubeUV: textureCubeUV,
  14037. textureLoad: textureLoad,
  14038. textureSize: textureSize,
  14039. textureStore: textureStore,
  14040. thickness: thickness,
  14041. threshold: threshold,
  14042. time: time,
  14043. timerDelta: timerDelta,
  14044. timerGlobal: timerGlobal,
  14045. timerLocal: timerLocal,
  14046. toOutputColorSpace: toOutputColorSpace,
  14047. toWorkingColorSpace: toWorkingColorSpace,
  14048. toneMapping: toneMapping,
  14049. toneMappingExposure: toneMappingExposure,
  14050. toonOutlinePass: toonOutlinePass,
  14051. transformDirection: transformDirection,
  14052. transformNormal: transformNormal,
  14053. transformNormalToView: transformNormalToView,
  14054. transformedBentNormalView: transformedBentNormalView,
  14055. transformedBitangentView: transformedBitangentView,
  14056. transformedBitangentWorld: transformedBitangentWorld,
  14057. transformedClearcoatNormalView: transformedClearcoatNormalView,
  14058. transformedNormalView: transformedNormalView,
  14059. transformedNormalWorld: transformedNormalWorld,
  14060. transformedTangentView: transformedTangentView,
  14061. transformedTangentWorld: transformedTangentWorld,
  14062. transmission: transmission,
  14063. transpose: transpose,
  14064. tri: tri,
  14065. tri3: tri3,
  14066. triNoise3D: triNoise3D,
  14067. triplanarTexture: triplanarTexture,
  14068. triplanarTextures: triplanarTextures,
  14069. trunc: trunc,
  14070. tslFn: tslFn,
  14071. uint: uint,
  14072. uniform: uniform,
  14073. uniformArray: uniformArray,
  14074. uniformGroup: uniformGroup,
  14075. uniforms: uniforms,
  14076. userData: userData,
  14077. uv: uv,
  14078. uvec2: uvec2,
  14079. uvec3: uvec3,
  14080. uvec4: uvec4,
  14081. varying: varying,
  14082. varyingProperty: varyingProperty,
  14083. vec2: vec2,
  14084. vec3: vec3,
  14085. vec4: vec4,
  14086. vectorComponents: vectorComponents,
  14087. velocity: velocity,
  14088. vertexColor: vertexColor,
  14089. vertexIndex: vertexIndex,
  14090. vibrance: vibrance,
  14091. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  14092. viewZToOrthographicDepth: viewZToOrthographicDepth,
  14093. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  14094. viewport: viewport,
  14095. viewportBottomLeft: viewportBottomLeft,
  14096. viewportCoordinate: viewportCoordinate,
  14097. viewportDepthTexture: viewportDepthTexture,
  14098. viewportLinearDepth: viewportLinearDepth,
  14099. viewportMipTexture: viewportMipTexture,
  14100. viewportResolution: viewportResolution,
  14101. viewportSafeUV: viewportSafeUV,
  14102. viewportSharedTexture: viewportSharedTexture,
  14103. viewportSize: viewportSize,
  14104. viewportTexture: viewportTexture,
  14105. viewportTopLeft: viewportTopLeft,
  14106. viewportUV: viewportUV,
  14107. wgsl: wgsl,
  14108. wgslFn: wgslFn,
  14109. workgroupArray: workgroupArray,
  14110. workgroupBarrier: workgroupBarrier,
  14111. workgroupId: workgroupId,
  14112. workingToColorSpace: workingToColorSpace,
  14113. xor: xor
  14114. });
  14115. const _clearColor$1 = /*@__PURE__*/ new Color4();
  14116. class Background extends DataMap {
  14117. constructor( renderer, nodes ) {
  14118. super();
  14119. this.renderer = renderer;
  14120. this.nodes = nodes;
  14121. }
  14122. update( scene, renderList, renderContext ) {
  14123. const renderer = this.renderer;
  14124. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  14125. let forceClear = false;
  14126. if ( background === null ) {
  14127. // no background settings, use clear color configuration from the renderer
  14128. renderer._clearColor.getRGB( _clearColor$1, LinearSRGBColorSpace );
  14129. _clearColor$1.a = renderer._clearColor.a;
  14130. } else if ( background.isColor === true ) {
  14131. // background is an opaque color
  14132. background.getRGB( _clearColor$1, LinearSRGBColorSpace );
  14133. _clearColor$1.a = 1;
  14134. forceClear = true;
  14135. } else if ( background.isNode === true ) {
  14136. const sceneData = this.get( scene );
  14137. const backgroundNode = background;
  14138. _clearColor$1.copy( renderer._clearColor );
  14139. let backgroundMesh = sceneData.backgroundMesh;
  14140. if ( backgroundMesh === undefined ) {
  14141. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  14142. // @TODO: Add Texture2D support using node context
  14143. getUV: () => backgroundRotation.mul( normalWorld ),
  14144. getTextureLevel: () => backgroundBlurriness
  14145. } );
  14146. let viewProj = modelViewProjection();
  14147. viewProj = viewProj.setZ( viewProj.w );
  14148. const nodeMaterial = new NodeMaterial();
  14149. nodeMaterial.name = 'Background.material';
  14150. nodeMaterial.side = BackSide;
  14151. nodeMaterial.depthTest = false;
  14152. nodeMaterial.depthWrite = false;
  14153. nodeMaterial.fog = false;
  14154. nodeMaterial.lights = false;
  14155. nodeMaterial.vertexNode = viewProj;
  14156. nodeMaterial.colorNode = backgroundMeshNode;
  14157. sceneData.backgroundMeshNode = backgroundMeshNode;
  14158. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  14159. backgroundMesh.frustumCulled = false;
  14160. backgroundMesh.name = 'Background.mesh';
  14161. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  14162. this.matrixWorld.copyPosition( camera.matrixWorld );
  14163. };
  14164. }
  14165. const backgroundCacheKey = backgroundNode.getCacheKey();
  14166. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  14167. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  14168. sceneData.backgroundMeshNode.needsUpdate = true;
  14169. backgroundMesh.material.needsUpdate = true;
  14170. sceneData.backgroundCacheKey = backgroundCacheKey;
  14171. }
  14172. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  14173. } else {
  14174. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  14175. }
  14176. //
  14177. if ( renderer.autoClear === true || forceClear === true ) {
  14178. const clearColorValue = renderContext.clearColorValue;
  14179. clearColorValue.r = _clearColor$1.r;
  14180. clearColorValue.g = _clearColor$1.g;
  14181. clearColorValue.b = _clearColor$1.b;
  14182. clearColorValue.a = _clearColor$1.a;
  14183. // premultiply alpha
  14184. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  14185. clearColorValue.r *= clearColorValue.a;
  14186. clearColorValue.g *= clearColorValue.a;
  14187. clearColorValue.b *= clearColorValue.a;
  14188. }
  14189. //
  14190. renderContext.depthClearValue = renderer._clearDepth;
  14191. renderContext.stencilClearValue = renderer._clearStencil;
  14192. renderContext.clearColor = renderer.autoClearColor === true;
  14193. renderContext.clearDepth = renderer.autoClearDepth === true;
  14194. renderContext.clearStencil = renderer.autoClearStencil === true;
  14195. } else {
  14196. renderContext.clearColor = false;
  14197. renderContext.clearDepth = false;
  14198. renderContext.clearStencil = false;
  14199. }
  14200. }
  14201. }
  14202. let _id$5 = 0;
  14203. class BindGroup {
  14204. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  14205. this.name = name;
  14206. this.bindings = bindings;
  14207. this.index = index;
  14208. this.bindingsReference = bindingsReference;
  14209. this.id = _id$5 ++;
  14210. }
  14211. }
  14212. class NodeBuilderState {
  14213. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, monitor, transforms = [] ) {
  14214. this.vertexShader = vertexShader;
  14215. this.fragmentShader = fragmentShader;
  14216. this.computeShader = computeShader;
  14217. this.transforms = transforms;
  14218. this.nodeAttributes = nodeAttributes;
  14219. this.bindings = bindings;
  14220. this.updateNodes = updateNodes;
  14221. this.updateBeforeNodes = updateBeforeNodes;
  14222. this.updateAfterNodes = updateAfterNodes;
  14223. this.monitor = monitor;
  14224. this.usedTimes = 0;
  14225. }
  14226. createBindings() {
  14227. const bindings = [];
  14228. for ( const instanceGroup of this.bindings ) {
  14229. const shared = instanceGroup.bindings[ 0 ].groupNode.shared;
  14230. if ( shared !== true ) {
  14231. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup );
  14232. bindings.push( bindingsGroup );
  14233. for ( const instanceBinding of instanceGroup.bindings ) {
  14234. bindingsGroup.bindings.push( instanceBinding.clone() );
  14235. }
  14236. } else {
  14237. bindings.push( instanceGroup );
  14238. }
  14239. }
  14240. return bindings;
  14241. }
  14242. }
  14243. class NodeAttribute {
  14244. constructor( name, type, node = null ) {
  14245. this.isNodeAttribute = true;
  14246. this.name = name;
  14247. this.type = type;
  14248. this.node = node;
  14249. }
  14250. }
  14251. class NodeUniform {
  14252. constructor( name, type, node ) {
  14253. this.isNodeUniform = true;
  14254. this.name = name;
  14255. this.type = type;
  14256. this.node = node.getSelf();
  14257. }
  14258. get value() {
  14259. return this.node.value;
  14260. }
  14261. set value( val ) {
  14262. this.node.value = val;
  14263. }
  14264. get id() {
  14265. return this.node.id;
  14266. }
  14267. get groupNode() {
  14268. return this.node.groupNode;
  14269. }
  14270. }
  14271. class NodeVar {
  14272. constructor( name, type ) {
  14273. this.isNodeVar = true;
  14274. this.name = name;
  14275. this.type = type;
  14276. }
  14277. }
  14278. class NodeVarying extends NodeVar {
  14279. constructor( name, type ) {
  14280. super( name, type );
  14281. this.needsInterpolation = false;
  14282. this.isNodeVarying = true;
  14283. }
  14284. }
  14285. class NodeCode {
  14286. constructor( name, type, code = '' ) {
  14287. this.name = name;
  14288. this.type = type;
  14289. this.code = code;
  14290. Object.defineProperty( this, 'isNodeCode', { value: true } );
  14291. }
  14292. }
  14293. let id = 0;
  14294. class NodeCache {
  14295. constructor( parent = null ) {
  14296. this.id = id ++;
  14297. this.nodesData = new WeakMap();
  14298. this.parent = parent;
  14299. }
  14300. getData( node ) {
  14301. let data = this.nodesData.get( node );
  14302. if ( data === undefined && this.parent !== null ) {
  14303. data = this.parent.getData( node );
  14304. }
  14305. return data;
  14306. }
  14307. setData( node, data ) {
  14308. this.nodesData.set( node, data );
  14309. }
  14310. }
  14311. class Uniform {
  14312. constructor( name, value ) {
  14313. this.name = name;
  14314. this.value = value;
  14315. this.boundary = 0; // used to build the uniform buffer according to the STD140 layout
  14316. this.itemSize = 0;
  14317. this.offset = 0; // this property is set by WebGPUUniformsGroup and marks the start position in the uniform buffer
  14318. }
  14319. setValue( value ) {
  14320. this.value = value;
  14321. }
  14322. getValue() {
  14323. return this.value;
  14324. }
  14325. }
  14326. class NumberUniform extends Uniform {
  14327. constructor( name, value = 0 ) {
  14328. super( name, value );
  14329. this.isNumberUniform = true;
  14330. this.boundary = 4;
  14331. this.itemSize = 1;
  14332. }
  14333. }
  14334. class Vector2Uniform extends Uniform {
  14335. constructor( name, value = new Vector2() ) {
  14336. super( name, value );
  14337. this.isVector2Uniform = true;
  14338. this.boundary = 8;
  14339. this.itemSize = 2;
  14340. }
  14341. }
  14342. class Vector3Uniform extends Uniform {
  14343. constructor( name, value = new Vector3() ) {
  14344. super( name, value );
  14345. this.isVector3Uniform = true;
  14346. this.boundary = 16;
  14347. this.itemSize = 3;
  14348. }
  14349. }
  14350. class Vector4Uniform extends Uniform {
  14351. constructor( name, value = new Vector4() ) {
  14352. super( name, value );
  14353. this.isVector4Uniform = true;
  14354. this.boundary = 16;
  14355. this.itemSize = 4;
  14356. }
  14357. }
  14358. class ColorUniform extends Uniform {
  14359. constructor( name, value = new Color() ) {
  14360. super( name, value );
  14361. this.isColorUniform = true;
  14362. this.boundary = 16;
  14363. this.itemSize = 3;
  14364. }
  14365. }
  14366. class Matrix3Uniform extends Uniform {
  14367. constructor( name, value = new Matrix3() ) {
  14368. super( name, value );
  14369. this.isMatrix3Uniform = true;
  14370. this.boundary = 48;
  14371. this.itemSize = 12;
  14372. }
  14373. }
  14374. class Matrix4Uniform extends Uniform {
  14375. constructor( name, value = new Matrix4() ) {
  14376. super( name, value );
  14377. this.isMatrix4Uniform = true;
  14378. this.boundary = 64;
  14379. this.itemSize = 16;
  14380. }
  14381. }
  14382. class NumberNodeUniform extends NumberUniform {
  14383. constructor( nodeUniform ) {
  14384. super( nodeUniform.name, nodeUniform.value );
  14385. this.nodeUniform = nodeUniform;
  14386. }
  14387. getValue() {
  14388. return this.nodeUniform.value;
  14389. }
  14390. getType() {
  14391. return this.nodeUniform.type;
  14392. }
  14393. }
  14394. class Vector2NodeUniform extends Vector2Uniform {
  14395. constructor( nodeUniform ) {
  14396. super( nodeUniform.name, nodeUniform.value );
  14397. this.nodeUniform = nodeUniform;
  14398. }
  14399. getValue() {
  14400. return this.nodeUniform.value;
  14401. }
  14402. getType() {
  14403. return this.nodeUniform.type;
  14404. }
  14405. }
  14406. class Vector3NodeUniform extends Vector3Uniform {
  14407. constructor( nodeUniform ) {
  14408. super( nodeUniform.name, nodeUniform.value );
  14409. this.nodeUniform = nodeUniform;
  14410. }
  14411. getValue() {
  14412. return this.nodeUniform.value;
  14413. }
  14414. getType() {
  14415. return this.nodeUniform.type;
  14416. }
  14417. }
  14418. class Vector4NodeUniform extends Vector4Uniform {
  14419. constructor( nodeUniform ) {
  14420. super( nodeUniform.name, nodeUniform.value );
  14421. this.nodeUniform = nodeUniform;
  14422. }
  14423. getValue() {
  14424. return this.nodeUniform.value;
  14425. }
  14426. getType() {
  14427. return this.nodeUniform.type;
  14428. }
  14429. }
  14430. class ColorNodeUniform extends ColorUniform {
  14431. constructor( nodeUniform ) {
  14432. super( nodeUniform.name, nodeUniform.value );
  14433. this.nodeUniform = nodeUniform;
  14434. }
  14435. getValue() {
  14436. return this.nodeUniform.value;
  14437. }
  14438. getType() {
  14439. return this.nodeUniform.type;
  14440. }
  14441. }
  14442. class Matrix3NodeUniform extends Matrix3Uniform {
  14443. constructor( nodeUniform ) {
  14444. super( nodeUniform.name, nodeUniform.value );
  14445. this.nodeUniform = nodeUniform;
  14446. }
  14447. getValue() {
  14448. return this.nodeUniform.value;
  14449. }
  14450. getType() {
  14451. return this.nodeUniform.type;
  14452. }
  14453. }
  14454. class Matrix4NodeUniform extends Matrix4Uniform {
  14455. constructor( nodeUniform ) {
  14456. super( nodeUniform.name, nodeUniform.value );
  14457. this.nodeUniform = nodeUniform;
  14458. }
  14459. getValue() {
  14460. return this.nodeUniform.value;
  14461. }
  14462. getType() {
  14463. return this.nodeUniform.type;
  14464. }
  14465. }
  14466. const LOD_MIN = 4;
  14467. // The standard deviations (radians) associated with the extra mips. These are
  14468. // chosen to approximate a Trowbridge-Reitz distribution function times the
  14469. // geometric shadowing function. These sigma values squared must match the
  14470. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  14471. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  14472. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  14473. // samples and exit early, but not recompile the shader.
  14474. const MAX_SAMPLES = 20;
  14475. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  14476. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  14477. const _clearColor = /*@__PURE__*/ new Color();
  14478. let _oldTarget = null;
  14479. let _oldActiveCubeFace = 0;
  14480. let _oldActiveMipmapLevel = 0;
  14481. // Golden Ratio
  14482. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  14483. const INV_PHI = 1 / PHI;
  14484. // Vertices of a dodecahedron (except the opposites, which represent the
  14485. // same axis), used as axis directions evenly spread on a sphere.
  14486. const _axisDirections = [
  14487. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  14488. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  14489. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  14490. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  14491. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  14492. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  14493. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  14494. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  14495. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  14496. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  14497. ];
  14498. //
  14499. // WebGPU Face indices
  14500. const _faceLib = [
  14501. 3, 1, 5,
  14502. 0, 4, 2
  14503. ];
  14504. const direction = getDirection( uv(), attribute( 'faceIndex' ) ).normalize();
  14505. const outputDirection = vec3( direction.x, direction.y.negate(), direction.z );
  14506. /**
  14507. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  14508. * (PMREM) from a cubeMap environment texture. This allows different levels of
  14509. * blur to be quickly accessed based on material roughness. It is packed into a
  14510. * special CubeUV format that allows us to perform custom interpolation so that
  14511. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  14512. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  14513. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  14514. * higher roughness levels. In this way we maintain resolution to smoothly
  14515. * interpolate diffuse lighting while limiting sampling computation.
  14516. *
  14517. * Paper: Fast, Accurate Image-Based Lighting
  14518. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  14519. */
  14520. class PMREMGenerator {
  14521. constructor( renderer ) {
  14522. this._renderer = renderer;
  14523. this._pingPongRenderTarget = null;
  14524. this._lodMax = 0;
  14525. this._cubeSize = 0;
  14526. this._lodPlanes = [];
  14527. this._sizeLods = [];
  14528. this._sigmas = [];
  14529. this._lodMeshes = [];
  14530. this._blurMaterial = null;
  14531. this._cubemapMaterial = null;
  14532. this._equirectMaterial = null;
  14533. this._backgroundBox = null;
  14534. }
  14535. get _hasInitialized() {
  14536. return this._renderer.hasInitialized();
  14537. }
  14538. /**
  14539. * Generates a PMREM from a supplied Scene, which can be faster than using an
  14540. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  14541. * in radians to be applied to the scene before PMREM generation. Optional near
  14542. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  14543. * is placed at the origin).
  14544. */
  14545. fromScene( scene, sigma = 0, near = 0.1, far = 100, renderTarget = null ) {
  14546. this._setSize( 256 );
  14547. if ( this._hasInitialized === false ) {
  14548. console.warn( 'THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.' );
  14549. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  14550. this.fromSceneAsync( scene, sigma, near, far, cubeUVRenderTarget );
  14551. return cubeUVRenderTarget;
  14552. }
  14553. _oldTarget = this._renderer.getRenderTarget();
  14554. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  14555. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  14556. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  14557. cubeUVRenderTarget.depthBuffer = true;
  14558. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  14559. if ( sigma > 0 ) {
  14560. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  14561. }
  14562. this._applyPMREM( cubeUVRenderTarget );
  14563. this._cleanup( cubeUVRenderTarget );
  14564. return cubeUVRenderTarget;
  14565. }
  14566. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, renderTarget = null ) {
  14567. if ( this._hasInitialized === false ) await this._renderer.init();
  14568. return this.fromScene( scene, sigma, near, far, renderTarget );
  14569. }
  14570. /**
  14571. * Generates a PMREM from an equirectangular texture, which can be either LDR
  14572. * or HDR. The ideal input image size is 1k (1024 x 512),
  14573. * as this matches best with the 256 x 256 cubemap output.
  14574. */
  14575. fromEquirectangular( equirectangular, renderTarget = null ) {
  14576. if ( this._hasInitialized === false ) {
  14577. console.warn( 'THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead.' );
  14578. this._setSizeFromTexture( equirectangular );
  14579. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  14580. this.fromEquirectangularAsync( equirectangular, cubeUVRenderTarget );
  14581. return cubeUVRenderTarget;
  14582. }
  14583. return this._fromTexture( equirectangular, renderTarget );
  14584. }
  14585. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  14586. if ( this._hasInitialized === false ) await this._renderer.init();
  14587. return this._fromTexture( equirectangular, renderTarget );
  14588. }
  14589. /**
  14590. * Generates a PMREM from an cubemap texture, which can be either LDR
  14591. * or HDR. The ideal input cube size is 256 x 256,
  14592. * as this matches best with the 256 x 256 cubemap output.
  14593. */
  14594. fromCubemap( cubemap, renderTarget = null ) {
  14595. if ( this._hasInitialized === false ) {
  14596. console.warn( 'THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead.' );
  14597. this._setSizeFromTexture( cubemap );
  14598. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  14599. this.fromCubemapAsync( cubemap, renderTarget );
  14600. return cubeUVRenderTarget;
  14601. }
  14602. return this._fromTexture( cubemap, renderTarget );
  14603. }
  14604. async fromCubemapAsync( cubemap, renderTarget = null ) {
  14605. if ( this._hasInitialized === false ) await this._renderer.init();
  14606. return this._fromTexture( cubemap, renderTarget );
  14607. }
  14608. /**
  14609. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  14610. * your texture's network fetch for increased concurrency.
  14611. */
  14612. async compileCubemapShader() {
  14613. if ( this._cubemapMaterial === null ) {
  14614. this._cubemapMaterial = _getCubemapMaterial();
  14615. await this._compileMaterial( this._cubemapMaterial );
  14616. }
  14617. }
  14618. /**
  14619. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  14620. * your texture's network fetch for increased concurrency.
  14621. */
  14622. async compileEquirectangularShader() {
  14623. if ( this._equirectMaterial === null ) {
  14624. this._equirectMaterial = _getEquirectMaterial();
  14625. await this._compileMaterial( this._equirectMaterial );
  14626. }
  14627. }
  14628. /**
  14629. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  14630. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  14631. * one of them will cause any others to also become unusable.
  14632. */
  14633. dispose() {
  14634. this._dispose();
  14635. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  14636. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  14637. if ( this._backgroundBox !== null ) {
  14638. this._backgroundBox.geometry.dispose();
  14639. this._backgroundBox.material.dispose();
  14640. }
  14641. }
  14642. // private interface
  14643. _setSizeFromTexture( texture ) {
  14644. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  14645. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  14646. } else { // Equirectangular
  14647. this._setSize( texture.image.width / 4 );
  14648. }
  14649. }
  14650. _setSize( cubeSize ) {
  14651. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  14652. this._cubeSize = Math.pow( 2, this._lodMax );
  14653. }
  14654. _dispose() {
  14655. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  14656. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  14657. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  14658. this._lodPlanes[ i ].dispose();
  14659. }
  14660. }
  14661. _cleanup( outputTarget ) {
  14662. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  14663. outputTarget.scissorTest = false;
  14664. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  14665. }
  14666. _fromTexture( texture, renderTarget ) {
  14667. this._setSizeFromTexture( texture );
  14668. _oldTarget = this._renderer.getRenderTarget();
  14669. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  14670. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  14671. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  14672. this._textureToCubeUV( texture, cubeUVRenderTarget );
  14673. this._applyPMREM( cubeUVRenderTarget );
  14674. this._cleanup( cubeUVRenderTarget );
  14675. return cubeUVRenderTarget;
  14676. }
  14677. _allocateTargets() {
  14678. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  14679. const height = 4 * this._cubeSize;
  14680. const params = {
  14681. magFilter: LinearFilter,
  14682. minFilter: LinearFilter,
  14683. generateMipmaps: false,
  14684. type: HalfFloatType,
  14685. format: RGBAFormat,
  14686. colorSpace: LinearSRGBColorSpace,
  14687. //depthBuffer: false
  14688. };
  14689. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  14690. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  14691. if ( this._pingPongRenderTarget !== null ) {
  14692. this._dispose();
  14693. }
  14694. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  14695. const { _lodMax } = this;
  14696. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  14697. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  14698. }
  14699. return cubeUVRenderTarget;
  14700. }
  14701. async _compileMaterial( material ) {
  14702. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  14703. await this._renderer.compile( tmpMesh, _flatCamera );
  14704. }
  14705. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  14706. const cubeCamera = _cubeCamera;
  14707. cubeCamera.near = near;
  14708. cubeCamera.far = far;
  14709. // px, py, pz, nx, ny, nz
  14710. const upSign = [ - 1, 1, - 1, - 1, - 1, - 1 ];
  14711. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  14712. const renderer = this._renderer;
  14713. const originalAutoClear = renderer.autoClear;
  14714. renderer.getClearColor( _clearColor );
  14715. renderer.autoClear = false;
  14716. let backgroundBox = this._backgroundBox;
  14717. if ( backgroundBox === null ) {
  14718. const backgroundMaterial = new MeshBasicMaterial( {
  14719. name: 'PMREM.Background',
  14720. side: BackSide,
  14721. depthWrite: false,
  14722. depthTest: false
  14723. } );
  14724. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  14725. }
  14726. let useSolidColor = false;
  14727. const background = scene.background;
  14728. if ( background ) {
  14729. if ( background.isColor ) {
  14730. backgroundBox.material.color.copy( background );
  14731. scene.background = null;
  14732. useSolidColor = true;
  14733. }
  14734. } else {
  14735. backgroundBox.material.color.copy( _clearColor );
  14736. useSolidColor = true;
  14737. }
  14738. renderer.setRenderTarget( cubeUVRenderTarget );
  14739. renderer.clear();
  14740. if ( useSolidColor ) {
  14741. renderer.render( backgroundBox, cubeCamera );
  14742. }
  14743. for ( let i = 0; i < 6; i ++ ) {
  14744. const col = i % 3;
  14745. if ( col === 0 ) {
  14746. cubeCamera.up.set( 0, upSign[ i ], 0 );
  14747. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  14748. } else if ( col === 1 ) {
  14749. cubeCamera.up.set( 0, 0, upSign[ i ] );
  14750. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  14751. } else {
  14752. cubeCamera.up.set( 0, upSign[ i ], 0 );
  14753. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  14754. }
  14755. const size = this._cubeSize;
  14756. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  14757. renderer.render( scene, cubeCamera );
  14758. }
  14759. renderer.autoClear = originalAutoClear;
  14760. scene.background = background;
  14761. }
  14762. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  14763. const renderer = this._renderer;
  14764. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  14765. if ( isCubeTexture ) {
  14766. if ( this._cubemapMaterial === null ) {
  14767. this._cubemapMaterial = _getCubemapMaterial( texture );
  14768. }
  14769. } else {
  14770. if ( this._equirectMaterial === null ) {
  14771. this._equirectMaterial = _getEquirectMaterial( texture );
  14772. }
  14773. }
  14774. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  14775. material.fragmentNode.value = texture;
  14776. const mesh = this._lodMeshes[ 0 ];
  14777. mesh.material = material;
  14778. const size = this._cubeSize;
  14779. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  14780. renderer.setRenderTarget( cubeUVRenderTarget );
  14781. renderer.render( mesh, _flatCamera );
  14782. }
  14783. _applyPMREM( cubeUVRenderTarget ) {
  14784. const renderer = this._renderer;
  14785. const autoClear = renderer.autoClear;
  14786. renderer.autoClear = false;
  14787. const n = this._lodPlanes.length;
  14788. for ( let i = 1; i < n; i ++ ) {
  14789. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  14790. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  14791. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  14792. }
  14793. renderer.autoClear = autoClear;
  14794. }
  14795. /**
  14796. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  14797. * vertically and horizontally, but this breaks down on a cube. Here we apply
  14798. * the blur latitudinally (around the poles), and then longitudinally (towards
  14799. * the poles) to approximate the orthogonally-separable blur. It is least
  14800. * accurate at the poles, but still does a decent job.
  14801. */
  14802. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  14803. const pingPongRenderTarget = this._pingPongRenderTarget;
  14804. this._halfBlur(
  14805. cubeUVRenderTarget,
  14806. pingPongRenderTarget,
  14807. lodIn,
  14808. lodOut,
  14809. sigma,
  14810. 'latitudinal',
  14811. poleAxis );
  14812. this._halfBlur(
  14813. pingPongRenderTarget,
  14814. cubeUVRenderTarget,
  14815. lodOut,
  14816. lodOut,
  14817. sigma,
  14818. 'longitudinal',
  14819. poleAxis );
  14820. }
  14821. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  14822. const renderer = this._renderer;
  14823. const blurMaterial = this._blurMaterial;
  14824. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  14825. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  14826. }
  14827. // Number of standard deviations at which to cut off the discrete approximation.
  14828. const STANDARD_DEVIATIONS = 3;
  14829. const blurMesh = this._lodMeshes[ lodOut ];
  14830. blurMesh.material = blurMaterial;
  14831. const blurUniforms = blurMaterial.uniforms;
  14832. const pixels = this._sizeLods[ lodIn ] - 1;
  14833. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  14834. const sigmaPixels = sigmaRadians / radiansPerPixel;
  14835. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  14836. if ( samples > MAX_SAMPLES ) {
  14837. console.warn( `sigmaRadians, ${
  14838. sigmaRadians}, is too large and will clip, as it requested ${
  14839. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  14840. }
  14841. const weights = [];
  14842. let sum = 0;
  14843. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  14844. const x = i / sigmaPixels;
  14845. const weight = Math.exp( - x * x / 2 );
  14846. weights.push( weight );
  14847. if ( i === 0 ) {
  14848. sum += weight;
  14849. } else if ( i < samples ) {
  14850. sum += 2 * weight;
  14851. }
  14852. }
  14853. for ( let i = 0; i < weights.length; i ++ ) {
  14854. weights[ i ] = weights[ i ] / sum;
  14855. }
  14856. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  14857. blurUniforms.envMap.value = targetIn.texture;
  14858. blurUniforms.samples.value = samples;
  14859. blurUniforms.weights.array = weights;
  14860. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  14861. if ( poleAxis ) {
  14862. blurUniforms.poleAxis.value = poleAxis;
  14863. }
  14864. const { _lodMax } = this;
  14865. blurUniforms.dTheta.value = radiansPerPixel;
  14866. blurUniforms.mipInt.value = _lodMax - lodIn;
  14867. const outputSize = this._sizeLods[ lodOut ];
  14868. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  14869. const y = 4 * ( this._cubeSize - outputSize );
  14870. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  14871. renderer.setRenderTarget( targetOut );
  14872. renderer.render( blurMesh, _flatCamera );
  14873. }
  14874. }
  14875. function _createPlanes( lodMax ) {
  14876. const lodPlanes = [];
  14877. const sizeLods = [];
  14878. const sigmas = [];
  14879. const lodMeshes = [];
  14880. let lod = lodMax;
  14881. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  14882. for ( let i = 0; i < totalLods; i ++ ) {
  14883. const sizeLod = Math.pow( 2, lod );
  14884. sizeLods.push( sizeLod );
  14885. let sigma = 1.0 / sizeLod;
  14886. if ( i > lodMax - LOD_MIN ) {
  14887. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  14888. } else if ( i === 0 ) {
  14889. sigma = 0;
  14890. }
  14891. sigmas.push( sigma );
  14892. const texelSize = 1.0 / ( sizeLod - 2 );
  14893. const min = - texelSize;
  14894. const max = 1 + texelSize;
  14895. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  14896. const cubeFaces = 6;
  14897. const vertices = 6;
  14898. const positionSize = 3;
  14899. const uvSize = 2;
  14900. const faceIndexSize = 1;
  14901. const position = new Float32Array( positionSize * vertices * cubeFaces );
  14902. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  14903. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  14904. for ( let face = 0; face < cubeFaces; face ++ ) {
  14905. const x = ( face % 3 ) * 2 / 3 - 1;
  14906. const y = face > 2 ? 0 : - 1;
  14907. const coordinates = [
  14908. x, y, 0,
  14909. x + 2 / 3, y, 0,
  14910. x + 2 / 3, y + 1, 0,
  14911. x, y, 0,
  14912. x + 2 / 3, y + 1, 0,
  14913. x, y + 1, 0
  14914. ];
  14915. const faceIdx = _faceLib[ face ];
  14916. position.set( coordinates, positionSize * vertices * faceIdx );
  14917. uv.set( uv1, uvSize * vertices * faceIdx );
  14918. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  14919. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  14920. }
  14921. const planes = new BufferGeometry();
  14922. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  14923. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  14924. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  14925. lodPlanes.push( planes );
  14926. lodMeshes.push( new Mesh( planes, null ) );
  14927. if ( lod > LOD_MIN ) {
  14928. lod --;
  14929. }
  14930. }
  14931. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  14932. }
  14933. function _createRenderTarget( width, height, params ) {
  14934. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  14935. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  14936. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  14937. cubeUVRenderTarget.texture.isPMREMTexture = true;
  14938. cubeUVRenderTarget.scissorTest = true;
  14939. return cubeUVRenderTarget;
  14940. }
  14941. function _setViewport( target, x, y, width, height ) {
  14942. target.viewport.set( x, y, width, height );
  14943. target.scissor.set( x, y, width, height );
  14944. }
  14945. function _getMaterial( type ) {
  14946. const material = new NodeMaterial();
  14947. material.depthTest = false;
  14948. material.depthWrite = false;
  14949. material.blending = NoBlending;
  14950. material.name = `PMREM_${ type }`;
  14951. return material;
  14952. }
  14953. function _getBlurShader( lodMax, width, height ) {
  14954. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  14955. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  14956. const dTheta = uniform( 0 );
  14957. const n = float( MAX_SAMPLES );
  14958. const latitudinal = uniform( 0 ); // false, bool
  14959. const samples = uniform( 1 ); // int
  14960. const envMap = texture( null );
  14961. const mipInt = uniform( 0 ); // int
  14962. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  14963. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  14964. const CUBEUV_MAX_MIP = float( lodMax );
  14965. const materialUniforms = {
  14966. n,
  14967. latitudinal,
  14968. weights,
  14969. poleAxis,
  14970. outputDirection,
  14971. dTheta,
  14972. samples,
  14973. envMap,
  14974. mipInt,
  14975. CUBEUV_TEXEL_WIDTH,
  14976. CUBEUV_TEXEL_HEIGHT,
  14977. CUBEUV_MAX_MIP
  14978. };
  14979. const material = _getMaterial( 'blur' );
  14980. material.uniforms = materialUniforms; // TODO: Move to outside of the material
  14981. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  14982. return material;
  14983. }
  14984. function _getCubemapMaterial( envTexture ) {
  14985. const material = _getMaterial( 'cubemap' );
  14986. material.fragmentNode = cubeTexture( envTexture, outputDirection );
  14987. return material;
  14988. }
  14989. function _getEquirectMaterial( envTexture ) {
  14990. const material = _getMaterial( 'equirect' );
  14991. material.fragmentNode = texture( envTexture, equirectUV( outputDirection ), 0 );
  14992. return material;
  14993. }
  14994. const rendererCache = new WeakMap();
  14995. const typeFromArray = new Map( [
  14996. [ Int8Array, 'int' ],
  14997. [ Int16Array, 'int' ],
  14998. [ Int32Array, 'int' ],
  14999. [ Uint8Array, 'uint' ],
  15000. [ Uint16Array, 'uint' ],
  15001. [ Uint32Array, 'uint' ],
  15002. [ Float32Array, 'float' ]
  15003. ] );
  15004. const toFloat = ( value ) => {
  15005. if ( /e/g.test( value ) ) {
  15006. return String( value ).replace( /\+/g, '' );
  15007. } else {
  15008. value = Number( value );
  15009. return value + ( value % 1 ? '' : '.0' );
  15010. }
  15011. };
  15012. class NodeBuilder {
  15013. constructor( object, renderer, parser ) {
  15014. this.object = object;
  15015. this.material = ( object && object.material ) || null;
  15016. this.geometry = ( object && object.geometry ) || null;
  15017. this.renderer = renderer;
  15018. this.parser = parser;
  15019. this.scene = null;
  15020. this.camera = null;
  15021. this.nodes = [];
  15022. this.sequentialNodes = [];
  15023. this.updateNodes = [];
  15024. this.updateBeforeNodes = [];
  15025. this.updateAfterNodes = [];
  15026. this.hashNodes = {};
  15027. this.monitor = null;
  15028. this.lightsNode = null;
  15029. this.environmentNode = null;
  15030. this.fogNode = null;
  15031. this.clippingContext = null;
  15032. this.vertexShader = null;
  15033. this.fragmentShader = null;
  15034. this.computeShader = null;
  15035. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  15036. this.flowCode = { vertex: '', fragment: '', compute: '' };
  15037. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  15038. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  15039. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  15040. this.bindingsIndexes = {};
  15041. this.bindGroups = null;
  15042. this.attributes = [];
  15043. this.bufferAttributes = [];
  15044. this.varyings = [];
  15045. this.codes = {};
  15046. this.vars = {};
  15047. this.flow = { code: '' };
  15048. this.chaining = [];
  15049. this.stack = stack();
  15050. this.stacks = [];
  15051. this.tab = '\t';
  15052. this.currentFunctionNode = null;
  15053. this.context = {
  15054. material: this.material
  15055. };
  15056. this.cache = new NodeCache();
  15057. this.globalCache = this.cache;
  15058. this.flowsData = new WeakMap();
  15059. this.shaderStage = null;
  15060. this.buildStage = null;
  15061. this.useComparisonMethod = false;
  15062. }
  15063. getBindGroupsCache() {
  15064. let bindGroupsCache = rendererCache.get( this.renderer );
  15065. if ( bindGroupsCache === undefined ) {
  15066. bindGroupsCache = new ChainMap();
  15067. rendererCache.set( this.renderer, bindGroupsCache );
  15068. }
  15069. return bindGroupsCache;
  15070. }
  15071. createRenderTarget( width, height, options ) {
  15072. return new RenderTarget( width, height, options );
  15073. }
  15074. createCubeRenderTarget( size, options ) {
  15075. return new CubeRenderTarget( size, options );
  15076. }
  15077. createPMREMGenerator() {
  15078. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  15079. return new PMREMGenerator( this.renderer );
  15080. }
  15081. includes( node ) {
  15082. return this.nodes.includes( node );
  15083. }
  15084. _getBindGroup( groupName, bindings ) {
  15085. const bindGroupsCache = this.getBindGroupsCache();
  15086. //
  15087. const bindingsArray = [];
  15088. let sharedGroup = true;
  15089. for ( const binding of bindings ) {
  15090. bindingsArray.push( binding );
  15091. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  15092. }
  15093. //
  15094. let bindGroup;
  15095. if ( sharedGroup ) {
  15096. bindGroup = bindGroupsCache.get( bindingsArray );
  15097. if ( bindGroup === undefined ) {
  15098. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  15099. bindGroupsCache.set( bindingsArray, bindGroup );
  15100. }
  15101. } else {
  15102. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  15103. }
  15104. return bindGroup;
  15105. }
  15106. getBindGroupArray( groupName, shaderStage ) {
  15107. const bindings = this.bindings[ shaderStage ];
  15108. let bindGroup = bindings[ groupName ];
  15109. if ( bindGroup === undefined ) {
  15110. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  15111. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  15112. }
  15113. bindings[ groupName ] = bindGroup = [];
  15114. }
  15115. return bindGroup;
  15116. }
  15117. getBindings() {
  15118. let bindingsGroups = this.bindGroups;
  15119. if ( bindingsGroups === null ) {
  15120. const groups = {};
  15121. const bindings = this.bindings;
  15122. for ( const shaderStage of shaderStages ) {
  15123. for ( const groupName in bindings[ shaderStage ] ) {
  15124. const uniforms = bindings[ shaderStage ][ groupName ];
  15125. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  15126. groupUniforms.push( ...uniforms );
  15127. }
  15128. }
  15129. bindingsGroups = [];
  15130. for ( const groupName in groups ) {
  15131. const group = groups[ groupName ];
  15132. const bindingsGroup = this._getBindGroup( groupName, group );
  15133. bindingsGroups.push( bindingsGroup );
  15134. }
  15135. this.bindGroups = bindingsGroups;
  15136. }
  15137. return bindingsGroups;
  15138. }
  15139. sortBindingGroups() {
  15140. const bindingsGroups = this.getBindings();
  15141. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  15142. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  15143. const bindingGroup = bindingsGroups[ i ];
  15144. this.bindingsIndexes[ bindingGroup.name ].group = i;
  15145. bindingGroup.index = i;
  15146. }
  15147. }
  15148. setHashNode( node, hash ) {
  15149. this.hashNodes[ hash ] = node;
  15150. }
  15151. addNode( node ) {
  15152. if ( this.nodes.includes( node ) === false ) {
  15153. this.nodes.push( node );
  15154. this.setHashNode( node, node.getHash( this ) );
  15155. }
  15156. }
  15157. addSequentialNode( node ) {
  15158. if ( this.sequentialNodes.includes( node ) === false ) {
  15159. this.sequentialNodes.push( node );
  15160. }
  15161. }
  15162. buildUpdateNodes() {
  15163. for ( const node of this.nodes ) {
  15164. const updateType = node.getUpdateType();
  15165. if ( updateType !== NodeUpdateType.NONE ) {
  15166. this.updateNodes.push( node.getSelf() );
  15167. }
  15168. }
  15169. for ( const node of this.sequentialNodes ) {
  15170. const updateBeforeType = node.getUpdateBeforeType();
  15171. const updateAfterType = node.getUpdateAfterType();
  15172. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  15173. this.updateBeforeNodes.push( node.getSelf() );
  15174. }
  15175. if ( updateAfterType !== NodeUpdateType.NONE ) {
  15176. this.updateAfterNodes.push( node.getSelf() );
  15177. }
  15178. }
  15179. }
  15180. get currentNode() {
  15181. return this.chaining[ this.chaining.length - 1 ];
  15182. }
  15183. isFilteredTexture( texture ) {
  15184. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  15185. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  15186. }
  15187. addChain( node ) {
  15188. /*
  15189. if ( this.chaining.indexOf( node ) !== - 1 ) {
  15190. console.warn( 'Recursive node: ', node );
  15191. }
  15192. */
  15193. this.chaining.push( node );
  15194. }
  15195. removeChain( node ) {
  15196. const lastChain = this.chaining.pop();
  15197. if ( lastChain !== node ) {
  15198. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  15199. }
  15200. }
  15201. getMethod( method ) {
  15202. return method;
  15203. }
  15204. getNodeFromHash( hash ) {
  15205. return this.hashNodes[ hash ];
  15206. }
  15207. addFlow( shaderStage, node ) {
  15208. this.flowNodes[ shaderStage ].push( node );
  15209. return node;
  15210. }
  15211. setContext( context ) {
  15212. this.context = context;
  15213. }
  15214. getContext() {
  15215. return this.context;
  15216. }
  15217. getSharedContext() {
  15218. ({ ...this.context });
  15219. return this.context;
  15220. }
  15221. setCache( cache ) {
  15222. this.cache = cache;
  15223. }
  15224. getCache() {
  15225. return this.cache;
  15226. }
  15227. getCacheFromNode( node, parent = true ) {
  15228. const data = this.getDataFromNode( node );
  15229. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  15230. return data.cache;
  15231. }
  15232. isAvailable( /*name*/ ) {
  15233. return false;
  15234. }
  15235. getVertexIndex() {
  15236. console.warn( 'Abstract function.' );
  15237. }
  15238. getInstanceIndex() {
  15239. console.warn( 'Abstract function.' );
  15240. }
  15241. getDrawIndex() {
  15242. console.warn( 'Abstract function.' );
  15243. }
  15244. getFrontFacing() {
  15245. console.warn( 'Abstract function.' );
  15246. }
  15247. getFragCoord() {
  15248. console.warn( 'Abstract function.' );
  15249. }
  15250. isFlipY() {
  15251. return false;
  15252. }
  15253. increaseUsage( node ) {
  15254. const nodeData = this.getDataFromNode( node );
  15255. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  15256. return nodeData.usageCount;
  15257. }
  15258. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  15259. console.warn( 'Abstract function.' );
  15260. }
  15261. generateTextureLod( /* texture, textureProperty, uvSnippet, levelSnippet */ ) {
  15262. console.warn( 'Abstract function.' );
  15263. }
  15264. generateConst( type, value = null ) {
  15265. if ( value === null ) {
  15266. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  15267. else if ( type === 'bool' ) value = false;
  15268. else if ( type === 'color' ) value = new Color();
  15269. else if ( type === 'vec2' ) value = new Vector2();
  15270. else if ( type === 'vec3' ) value = new Vector3();
  15271. else if ( type === 'vec4' ) value = new Vector4();
  15272. }
  15273. if ( type === 'float' ) return toFloat( value );
  15274. if ( type === 'int' ) return `${ Math.round( value ) }`;
  15275. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  15276. if ( type === 'bool' ) return value ? 'true' : 'false';
  15277. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  15278. const typeLength = this.getTypeLength( type );
  15279. const componentType = this.getComponentType( type );
  15280. const generateConst = value => this.generateConst( componentType, value );
  15281. if ( typeLength === 2 ) {
  15282. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  15283. } else if ( typeLength === 3 ) {
  15284. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  15285. } else if ( typeLength === 4 ) {
  15286. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  15287. } else if ( typeLength > 4 && value && ( value.isMatrix3 || value.isMatrix4 ) ) {
  15288. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  15289. } else if ( typeLength > 4 ) {
  15290. return `${ this.getType( type ) }()`;
  15291. }
  15292. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  15293. }
  15294. getType( type ) {
  15295. if ( type === 'color' ) return 'vec3';
  15296. return type;
  15297. }
  15298. hasGeometryAttribute( name ) {
  15299. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  15300. }
  15301. getAttribute( name, type ) {
  15302. const attributes = this.attributes;
  15303. // find attribute
  15304. for ( const attribute of attributes ) {
  15305. if ( attribute.name === name ) {
  15306. return attribute;
  15307. }
  15308. }
  15309. // create a new if no exist
  15310. const attribute = new NodeAttribute( name, type );
  15311. attributes.push( attribute );
  15312. return attribute;
  15313. }
  15314. getPropertyName( node/*, shaderStage*/ ) {
  15315. return node.name;
  15316. }
  15317. isVector( type ) {
  15318. return /vec\d/.test( type );
  15319. }
  15320. isMatrix( type ) {
  15321. return /mat\d/.test( type );
  15322. }
  15323. isReference( type ) {
  15324. return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  15325. }
  15326. needsToWorkingColorSpace( /*texture*/ ) {
  15327. return false;
  15328. }
  15329. getComponentTypeFromTexture( texture ) {
  15330. const type = texture.type;
  15331. if ( texture.isDataTexture ) {
  15332. if ( type === IntType ) return 'int';
  15333. if ( type === UnsignedIntType ) return 'uint';
  15334. }
  15335. return 'float';
  15336. }
  15337. getElementType( type ) {
  15338. if ( type === 'mat2' ) return 'vec2';
  15339. if ( type === 'mat3' ) return 'vec3';
  15340. if ( type === 'mat4' ) return 'vec4';
  15341. return this.getComponentType( type );
  15342. }
  15343. getComponentType( type ) {
  15344. type = this.getVectorType( type );
  15345. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  15346. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  15347. if ( componentType === null ) return null;
  15348. if ( componentType[ 1 ] === 'b' ) return 'bool';
  15349. if ( componentType[ 1 ] === 'i' ) return 'int';
  15350. if ( componentType[ 1 ] === 'u' ) return 'uint';
  15351. return 'float';
  15352. }
  15353. getVectorType( type ) {
  15354. if ( type === 'color' ) return 'vec3';
  15355. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  15356. return type;
  15357. }
  15358. getTypeFromLength( length, componentType = 'float' ) {
  15359. if ( length === 1 ) return componentType;
  15360. const baseType = getTypeFromLength( length );
  15361. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  15362. return prefix + baseType;
  15363. }
  15364. getTypeFromArray( array ) {
  15365. return typeFromArray.get( array.constructor );
  15366. }
  15367. getTypeFromAttribute( attribute ) {
  15368. let dataAttribute = attribute;
  15369. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  15370. const array = dataAttribute.array;
  15371. const itemSize = attribute.itemSize;
  15372. const normalized = attribute.normalized;
  15373. let arrayType;
  15374. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  15375. arrayType = this.getTypeFromArray( array );
  15376. }
  15377. return this.getTypeFromLength( itemSize, arrayType );
  15378. }
  15379. getTypeLength( type ) {
  15380. const vecType = this.getVectorType( type );
  15381. const vecNum = /vec([2-4])/.exec( vecType );
  15382. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  15383. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  15384. if ( /mat2/.test( type ) === true ) return 4;
  15385. if ( /mat3/.test( type ) === true ) return 9;
  15386. if ( /mat4/.test( type ) === true ) return 16;
  15387. return 0;
  15388. }
  15389. getVectorFromMatrix( type ) {
  15390. return type.replace( 'mat', 'vec' );
  15391. }
  15392. changeComponentType( type, newComponentType ) {
  15393. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  15394. }
  15395. getIntegerType( type ) {
  15396. const componentType = this.getComponentType( type );
  15397. if ( componentType === 'int' || componentType === 'uint' ) return type;
  15398. return this.changeComponentType( type, 'int' );
  15399. }
  15400. addStack() {
  15401. this.stack = stack( this.stack );
  15402. this.stacks.push( getCurrentStack() || this.stack );
  15403. setCurrentStack( this.stack );
  15404. return this.stack;
  15405. }
  15406. removeStack() {
  15407. const lastStack = this.stack;
  15408. this.stack = lastStack.parent;
  15409. setCurrentStack( this.stacks.pop() );
  15410. return lastStack;
  15411. }
  15412. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  15413. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  15414. let nodeData = cache.getData( node );
  15415. if ( nodeData === undefined ) {
  15416. nodeData = {};
  15417. cache.setData( node, nodeData );
  15418. }
  15419. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  15420. return nodeData[ shaderStage ];
  15421. }
  15422. getNodeProperties( node, shaderStage = 'any' ) {
  15423. const nodeData = this.getDataFromNode( node, shaderStage );
  15424. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  15425. }
  15426. getBufferAttributeFromNode( node, type ) {
  15427. const nodeData = this.getDataFromNode( node );
  15428. let bufferAttribute = nodeData.bufferAttribute;
  15429. if ( bufferAttribute === undefined ) {
  15430. const index = this.uniforms.index ++;
  15431. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  15432. this.bufferAttributes.push( bufferAttribute );
  15433. nodeData.bufferAttribute = bufferAttribute;
  15434. }
  15435. return bufferAttribute;
  15436. }
  15437. getStructTypeFromNode( node, shaderStage = this.shaderStage ) {
  15438. const nodeData = this.getDataFromNode( node, shaderStage );
  15439. if ( nodeData.structType === undefined ) {
  15440. const index = this.structs.index ++;
  15441. node.name = `StructType${ index }`;
  15442. this.structs[ shaderStage ].push( node );
  15443. nodeData.structType = node;
  15444. }
  15445. return node;
  15446. }
  15447. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  15448. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  15449. let nodeUniform = nodeData.uniform;
  15450. if ( nodeUniform === undefined ) {
  15451. const index = this.uniforms.index ++;
  15452. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  15453. this.uniforms[ shaderStage ].push( nodeUniform );
  15454. nodeData.uniform = nodeUniform;
  15455. }
  15456. return nodeUniform;
  15457. }
  15458. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage ) {
  15459. const nodeData = this.getDataFromNode( node, shaderStage );
  15460. let nodeVar = nodeData.variable;
  15461. if ( nodeVar === undefined ) {
  15462. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  15463. if ( name === null ) name = 'nodeVar' + vars.length;
  15464. nodeVar = new NodeVar( name, type );
  15465. vars.push( nodeVar );
  15466. nodeData.variable = nodeVar;
  15467. }
  15468. return nodeVar;
  15469. }
  15470. getVaryingFromNode( node, name = null, type = node.getNodeType( this ) ) {
  15471. const nodeData = this.getDataFromNode( node, 'any' );
  15472. let nodeVarying = nodeData.varying;
  15473. if ( nodeVarying === undefined ) {
  15474. const varyings = this.varyings;
  15475. const index = varyings.length;
  15476. if ( name === null ) name = 'nodeVarying' + index;
  15477. nodeVarying = new NodeVarying( name, type );
  15478. varyings.push( nodeVarying );
  15479. nodeData.varying = nodeVarying;
  15480. }
  15481. return nodeVarying;
  15482. }
  15483. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  15484. const nodeData = this.getDataFromNode( node );
  15485. let nodeCode = nodeData.code;
  15486. if ( nodeCode === undefined ) {
  15487. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  15488. const index = codes.length;
  15489. nodeCode = new NodeCode( 'nodeCode' + index, type );
  15490. codes.push( nodeCode );
  15491. nodeData.code = nodeCode;
  15492. }
  15493. return nodeCode;
  15494. }
  15495. addFlowCodeHierarchy( node, nodeBlock ) {
  15496. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  15497. let needsFlowCode = true;
  15498. let nodeBlockHierarchy = nodeBlock;
  15499. while ( nodeBlockHierarchy ) {
  15500. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  15501. needsFlowCode = false;
  15502. break;
  15503. }
  15504. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  15505. }
  15506. if ( needsFlowCode ) {
  15507. for ( const flowCode of flowCodes ) {
  15508. this.addLineFlowCode( flowCode );
  15509. }
  15510. }
  15511. }
  15512. addLineFlowCodeBlock( node, code, nodeBlock ) {
  15513. const nodeData = this.getDataFromNode( node );
  15514. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  15515. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  15516. flowCodes.push( code );
  15517. codeBlock.set( nodeBlock, true );
  15518. }
  15519. addLineFlowCode( code, node = null ) {
  15520. if ( code === '' ) return this;
  15521. if ( node !== null && this.context.nodeBlock ) {
  15522. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  15523. }
  15524. code = this.tab + code;
  15525. if ( ! /;\s*$/.test( code ) ) {
  15526. code = code + ';\n';
  15527. }
  15528. this.flow.code += code;
  15529. return this;
  15530. }
  15531. addFlowCode( code ) {
  15532. this.flow.code += code;
  15533. return this;
  15534. }
  15535. addFlowTab() {
  15536. this.tab += '\t';
  15537. return this;
  15538. }
  15539. removeFlowTab() {
  15540. this.tab = this.tab.slice( 0, - 1 );
  15541. return this;
  15542. }
  15543. getFlowData( node/*, shaderStage*/ ) {
  15544. return this.flowsData.get( node );
  15545. }
  15546. flowNode( node ) {
  15547. const output = node.getNodeType( this );
  15548. const flowData = this.flowChildNode( node, output );
  15549. this.flowsData.set( node, flowData );
  15550. return flowData;
  15551. }
  15552. buildFunctionNode( shaderNode ) {
  15553. const fn = new FunctionNode();
  15554. const previous = this.currentFunctionNode;
  15555. this.currentFunctionNode = fn;
  15556. fn.code = this.buildFunctionCode( shaderNode );
  15557. this.currentFunctionNode = previous;
  15558. return fn;
  15559. }
  15560. flowShaderNode( shaderNode ) {
  15561. const layout = shaderNode.layout;
  15562. const inputs = {
  15563. [ Symbol.iterator ]() {
  15564. let index = 0;
  15565. const values = Object.values( this );
  15566. return {
  15567. next: () => ( {
  15568. value: values[ index ],
  15569. done: index ++ >= values.length
  15570. } )
  15571. };
  15572. }
  15573. };
  15574. for ( const input of layout.inputs ) {
  15575. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  15576. }
  15577. //
  15578. shaderNode.layout = null;
  15579. const callNode = shaderNode.call( inputs );
  15580. const flowData = this.flowStagesNode( callNode, layout.type );
  15581. shaderNode.layout = layout;
  15582. return flowData;
  15583. }
  15584. flowStagesNode( node, output = null ) {
  15585. const previousFlow = this.flow;
  15586. const previousVars = this.vars;
  15587. const previousCache = this.cache;
  15588. const previousBuildStage = this.buildStage;
  15589. const previousStack = this.stack;
  15590. const flow = {
  15591. code: ''
  15592. };
  15593. this.flow = flow;
  15594. this.vars = {};
  15595. this.cache = new NodeCache();
  15596. this.stack = stack();
  15597. for ( const buildStage of defaultBuildStages ) {
  15598. this.setBuildStage( buildStage );
  15599. flow.result = node.build( this, output );
  15600. }
  15601. flow.vars = this.getVars( this.shaderStage );
  15602. this.flow = previousFlow;
  15603. this.vars = previousVars;
  15604. this.cache = previousCache;
  15605. this.stack = previousStack;
  15606. this.setBuildStage( previousBuildStage );
  15607. return flow;
  15608. }
  15609. getFunctionOperator() {
  15610. return null;
  15611. }
  15612. flowChildNode( node, output = null ) {
  15613. const previousFlow = this.flow;
  15614. const flow = {
  15615. code: ''
  15616. };
  15617. this.flow = flow;
  15618. flow.result = node.build( this, output );
  15619. this.flow = previousFlow;
  15620. return flow;
  15621. }
  15622. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  15623. const previousShaderStage = this.shaderStage;
  15624. this.setShaderStage( shaderStage );
  15625. const flowData = this.flowChildNode( node, output );
  15626. if ( propertyName !== null ) {
  15627. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  15628. }
  15629. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  15630. this.setShaderStage( previousShaderStage );
  15631. return flowData;
  15632. }
  15633. getAttributesArray() {
  15634. return this.attributes.concat( this.bufferAttributes );
  15635. }
  15636. getAttributes( /*shaderStage*/ ) {
  15637. console.warn( 'Abstract function.' );
  15638. }
  15639. getVaryings( /*shaderStage*/ ) {
  15640. console.warn( 'Abstract function.' );
  15641. }
  15642. getVar( type, name ) {
  15643. return `${ this.getType( type ) } ${ name }`;
  15644. }
  15645. getVars( shaderStage ) {
  15646. let snippet = '';
  15647. const vars = this.vars[ shaderStage ];
  15648. if ( vars !== undefined ) {
  15649. for ( const variable of vars ) {
  15650. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  15651. }
  15652. }
  15653. return snippet;
  15654. }
  15655. getUniforms( /*shaderStage*/ ) {
  15656. console.warn( 'Abstract function.' );
  15657. }
  15658. getCodes( shaderStage ) {
  15659. const codes = this.codes[ shaderStage ];
  15660. let code = '';
  15661. if ( codes !== undefined ) {
  15662. for ( const nodeCode of codes ) {
  15663. code += nodeCode.code + '\n';
  15664. }
  15665. }
  15666. return code;
  15667. }
  15668. getHash() {
  15669. return this.vertexShader + this.fragmentShader + this.computeShader;
  15670. }
  15671. setShaderStage( shaderStage ) {
  15672. this.shaderStage = shaderStage;
  15673. }
  15674. getShaderStage() {
  15675. return this.shaderStage;
  15676. }
  15677. setBuildStage( buildStage ) {
  15678. this.buildStage = buildStage;
  15679. }
  15680. getBuildStage() {
  15681. return this.buildStage;
  15682. }
  15683. buildCode() {
  15684. console.warn( 'Abstract function.' );
  15685. }
  15686. build() {
  15687. const { object, material, renderer } = this;
  15688. if ( material !== null ) {
  15689. let nodeMaterial = renderer.library.fromMaterial( material );
  15690. if ( nodeMaterial === null ) {
  15691. console.error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  15692. nodeMaterial = new NodeMaterial();
  15693. }
  15694. nodeMaterial.build( this );
  15695. } else {
  15696. this.addFlow( 'compute', object );
  15697. }
  15698. // setup() -> stage 1: create possible new nodes and returns an output reference node
  15699. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  15700. // generate() -> stage 3: generate shader
  15701. for ( const buildStage of defaultBuildStages ) {
  15702. this.setBuildStage( buildStage );
  15703. if ( this.context.vertex && this.context.vertex.isNode ) {
  15704. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  15705. }
  15706. for ( const shaderStage of shaderStages ) {
  15707. this.setShaderStage( shaderStage );
  15708. const flowNodes = this.flowNodes[ shaderStage ];
  15709. for ( const node of flowNodes ) {
  15710. if ( buildStage === 'generate' ) {
  15711. this.flowNode( node );
  15712. } else {
  15713. node.build( this );
  15714. }
  15715. }
  15716. }
  15717. }
  15718. this.setBuildStage( null );
  15719. this.setShaderStage( null );
  15720. // stage 4: build code for a specific output
  15721. this.buildCode();
  15722. this.buildUpdateNodes();
  15723. return this;
  15724. }
  15725. getNodeUniform( uniformNode, type ) {
  15726. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  15727. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  15728. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  15729. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  15730. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  15731. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  15732. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  15733. throw new Error( `Uniform "${type}" not declared.` );
  15734. }
  15735. createNodeMaterial( type = 'NodeMaterial' ) { // @deprecated, r168
  15736. throw new Error( `THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${ type }() instead.` );
  15737. }
  15738. format( snippet, fromType, toType ) {
  15739. fromType = this.getVectorType( fromType );
  15740. toType = this.getVectorType( toType );
  15741. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  15742. return snippet;
  15743. }
  15744. const fromTypeLength = this.getTypeLength( fromType );
  15745. const toTypeLength = this.getTypeLength( toType );
  15746. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  15747. return `${ this.getType( toType ) }(${ snippet }[0].xyz, ${ snippet }[1].xyz, ${ snippet }[2].xyz)`;
  15748. }
  15749. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  15750. return `${ this.getType( toType ) }(${ snippet }[0].xy, ${ snippet }[1].xy)`;
  15751. }
  15752. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  15753. // @TODO: ignore for now
  15754. return snippet;
  15755. }
  15756. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  15757. // @TODO: ignore for now
  15758. return snippet;
  15759. }
  15760. if ( fromTypeLength === toTypeLength ) {
  15761. return `${ this.getType( toType ) }( ${ snippet } )`;
  15762. }
  15763. if ( fromTypeLength > toTypeLength ) {
  15764. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  15765. }
  15766. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  15767. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  15768. }
  15769. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  15770. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  15771. }
  15772. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  15773. // convert a number value to vector type, e.g:
  15774. // vec3( 1u ) -> vec3( float( 1u ) )
  15775. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  15776. }
  15777. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  15778. }
  15779. getSignature() {
  15780. return `// Three.js r${ REVISION } - Node System\n`;
  15781. }
  15782. }
  15783. class NodeFrame {
  15784. constructor() {
  15785. this.time = 0;
  15786. this.deltaTime = 0;
  15787. this.frameId = 0;
  15788. this.renderId = 0;
  15789. this.startTime = null;
  15790. this.updateMap = new WeakMap();
  15791. this.updateBeforeMap = new WeakMap();
  15792. this.updateAfterMap = new WeakMap();
  15793. this.renderer = null;
  15794. this.material = null;
  15795. this.camera = null;
  15796. this.object = null;
  15797. this.scene = null;
  15798. }
  15799. _getMaps( referenceMap, nodeRef ) {
  15800. let maps = referenceMap.get( nodeRef );
  15801. if ( maps === undefined ) {
  15802. maps = {
  15803. renderMap: new WeakMap(),
  15804. frameMap: new WeakMap()
  15805. };
  15806. referenceMap.set( nodeRef, maps );
  15807. }
  15808. return maps;
  15809. }
  15810. updateBeforeNode( node ) {
  15811. const updateType = node.getUpdateBeforeType();
  15812. const reference = node.updateReference( this );
  15813. if ( updateType === NodeUpdateType.FRAME ) {
  15814. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  15815. if ( frameMap.get( reference ) !== this.frameId ) {
  15816. if ( node.updateBefore( this ) !== false ) {
  15817. frameMap.set( reference, this.frameId );
  15818. }
  15819. }
  15820. } else if ( updateType === NodeUpdateType.RENDER ) {
  15821. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  15822. if ( renderMap.get( reference ) !== this.renderId ) {
  15823. if ( node.updateBefore( this ) !== false ) {
  15824. renderMap.set( reference, this.renderId );
  15825. }
  15826. }
  15827. } else if ( updateType === NodeUpdateType.OBJECT ) {
  15828. node.updateBefore( this );
  15829. }
  15830. }
  15831. updateAfterNode( node ) {
  15832. const updateType = node.getUpdateAfterType();
  15833. const reference = node.updateReference( this );
  15834. if ( updateType === NodeUpdateType.FRAME ) {
  15835. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  15836. if ( frameMap.get( reference ) !== this.frameId ) {
  15837. if ( node.updateAfter( this ) !== false ) {
  15838. frameMap.set( reference, this.frameId );
  15839. }
  15840. }
  15841. } else if ( updateType === NodeUpdateType.RENDER ) {
  15842. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  15843. if ( renderMap.get( reference ) !== this.renderId ) {
  15844. if ( node.updateAfter( this ) !== false ) {
  15845. renderMap.set( reference, this.renderId );
  15846. }
  15847. }
  15848. } else if ( updateType === NodeUpdateType.OBJECT ) {
  15849. node.updateAfter( this );
  15850. }
  15851. }
  15852. updateNode( node ) {
  15853. const updateType = node.getUpdateType();
  15854. const reference = node.updateReference( this );
  15855. if ( updateType === NodeUpdateType.FRAME ) {
  15856. const { frameMap } = this._getMaps( this.updateMap, reference );
  15857. if ( frameMap.get( reference ) !== this.frameId ) {
  15858. if ( node.update( this ) !== false ) {
  15859. frameMap.set( reference, this.frameId );
  15860. }
  15861. }
  15862. } else if ( updateType === NodeUpdateType.RENDER ) {
  15863. const { renderMap } = this._getMaps( this.updateMap, reference );
  15864. if ( renderMap.get( reference ) !== this.renderId ) {
  15865. if ( node.update( this ) !== false ) {
  15866. renderMap.set( reference, this.renderId );
  15867. }
  15868. }
  15869. } else if ( updateType === NodeUpdateType.OBJECT ) {
  15870. node.update( this );
  15871. }
  15872. }
  15873. update() {
  15874. this.frameId ++;
  15875. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  15876. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  15877. this.lastTime = performance.now();
  15878. this.time += this.deltaTime;
  15879. }
  15880. }
  15881. class NodeFunctionInput {
  15882. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  15883. this.type = type;
  15884. this.name = name;
  15885. this.count = count;
  15886. this.qualifier = qualifier;
  15887. this.isConst = isConst;
  15888. }
  15889. }
  15890. NodeFunctionInput.isNodeFunctionInput = true;
  15891. class DirectionalLightNode extends AnalyticLightNode {
  15892. static get type() {
  15893. return 'DirectionalLightNode';
  15894. }
  15895. constructor( light = null ) {
  15896. super( light );
  15897. }
  15898. setup( builder ) {
  15899. super.setup( builder );
  15900. const lightingModel = builder.context.lightingModel;
  15901. const lightColor = this.colorNode;
  15902. const lightDirection = lightTargetDirection( this.light );
  15903. const reflectedLight = builder.context.reflectedLight;
  15904. lightingModel.direct( {
  15905. lightDirection,
  15906. lightColor,
  15907. reflectedLight
  15908. }, builder.stack, builder );
  15909. }
  15910. }
  15911. const _matrix41 = /*@__PURE__*/ new Matrix4();
  15912. const _matrix42 = /*@__PURE__*/ new Matrix4();
  15913. let ltcLib = null;
  15914. class RectAreaLightNode extends AnalyticLightNode {
  15915. static get type() {
  15916. return 'RectAreaLightNode';
  15917. }
  15918. constructor( light = null ) {
  15919. super( light );
  15920. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  15921. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  15922. this.updateType = NodeUpdateType.RENDER;
  15923. }
  15924. update( frame ) {
  15925. super.update( frame );
  15926. const { light } = this;
  15927. const viewMatrix = frame.camera.matrixWorldInverse;
  15928. _matrix42.identity();
  15929. _matrix41.copy( light.matrixWorld );
  15930. _matrix41.premultiply( viewMatrix );
  15931. _matrix42.extractRotation( _matrix41 );
  15932. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  15933. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  15934. this.halfWidth.value.applyMatrix4( _matrix42 );
  15935. this.halfHeight.value.applyMatrix4( _matrix42 );
  15936. }
  15937. setup( builder ) {
  15938. super.setup( builder );
  15939. let ltc_1, ltc_2;
  15940. if ( builder.isAvailable( 'float32Filterable' ) ) {
  15941. ltc_1 = texture( ltcLib.LTC_FLOAT_1 );
  15942. ltc_2 = texture( ltcLib.LTC_FLOAT_2 );
  15943. } else {
  15944. ltc_1 = texture( ltcLib.LTC_HALF_1 );
  15945. ltc_2 = texture( ltcLib.LTC_HALF_2 );
  15946. }
  15947. const { colorNode, light } = this;
  15948. const lightingModel = builder.context.lightingModel;
  15949. const lightPosition = lightViewPosition( light );
  15950. const reflectedLight = builder.context.reflectedLight;
  15951. lightingModel.directRectArea( {
  15952. lightColor: colorNode,
  15953. lightPosition,
  15954. halfWidth: this.halfWidth,
  15955. halfHeight: this.halfHeight,
  15956. reflectedLight,
  15957. ltc_1,
  15958. ltc_2
  15959. }, builder.stack, builder );
  15960. }
  15961. static setLTC( ltc ) {
  15962. ltcLib = ltc;
  15963. }
  15964. }
  15965. class SpotLightNode extends AnalyticLightNode {
  15966. static get type() {
  15967. return 'SpotLightNode';
  15968. }
  15969. constructor( light = null ) {
  15970. super( light );
  15971. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  15972. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  15973. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  15974. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  15975. }
  15976. update( frame ) {
  15977. super.update( frame );
  15978. const { light } = this;
  15979. this.coneCosNode.value = Math.cos( light.angle );
  15980. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  15981. this.cutoffDistanceNode.value = light.distance;
  15982. this.decayExponentNode.value = light.decay;
  15983. }
  15984. getSpotAttenuation( angleCosine ) {
  15985. const { coneCosNode, penumbraCosNode } = this;
  15986. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  15987. }
  15988. setup( builder ) {
  15989. super.setup( builder );
  15990. const lightingModel = builder.context.lightingModel;
  15991. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  15992. const lVector = lightViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  15993. const lightDirection = lVector.normalize();
  15994. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  15995. const spotAttenuation = this.getSpotAttenuation( angleCos );
  15996. const lightDistance = lVector.length();
  15997. const lightAttenuation = getDistanceAttenuation( {
  15998. lightDistance,
  15999. cutoffDistance: cutoffDistanceNode,
  16000. decayExponent: decayExponentNode
  16001. } );
  16002. let lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  16003. if ( light.map ) {
  16004. const spotLightCoord = lightProjectionUV( light );
  16005. const projectedTexture = texture( light.map, spotLightCoord.xy ).onRenderUpdate( () => light.map );
  16006. const inSpotLightMap = spotLightCoord.mul( 2. ).sub( 1. ).abs().lessThan( 1. ).all();
  16007. lightColor = inSpotLightMap.select( lightColor.mul( projectedTexture ), lightColor );
  16008. }
  16009. const reflectedLight = builder.context.reflectedLight;
  16010. lightingModel.direct( {
  16011. lightDirection,
  16012. lightColor,
  16013. reflectedLight
  16014. }, builder.stack, builder );
  16015. }
  16016. }
  16017. class IESSpotLightNode extends SpotLightNode {
  16018. static get type() {
  16019. return 'IESSpotLightNode';
  16020. }
  16021. getSpotAttenuation( angleCosine ) {
  16022. const iesMap = this.light.iesMap;
  16023. let spotAttenuation = null;
  16024. if ( iesMap && iesMap.isTexture === true ) {
  16025. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  16026. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  16027. } else {
  16028. spotAttenuation = super.getSpotAttenuation( angleCosine );
  16029. }
  16030. return spotAttenuation;
  16031. }
  16032. }
  16033. class AmbientLightNode extends AnalyticLightNode {
  16034. static get type() {
  16035. return 'AmbientLightNode';
  16036. }
  16037. constructor( light = null ) {
  16038. super( light );
  16039. }
  16040. setup( { context } ) {
  16041. context.irradiance.addAssign( this.colorNode );
  16042. }
  16043. }
  16044. class HemisphereLightNode extends AnalyticLightNode {
  16045. static get type() {
  16046. return 'HemisphereLightNode';
  16047. }
  16048. constructor( light = null ) {
  16049. super( light );
  16050. this.lightPositionNode = lightPosition( light );
  16051. this.lightDirectionNode = this.lightPositionNode.normalize();
  16052. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  16053. }
  16054. update( frame ) {
  16055. const { light } = this;
  16056. super.update( frame );
  16057. this.lightPositionNode.object3d = light;
  16058. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  16059. }
  16060. setup( builder ) {
  16061. const { colorNode, groundColorNode, lightDirectionNode } = this;
  16062. const dotNL = normalView.dot( lightDirectionNode );
  16063. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  16064. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  16065. builder.context.irradiance.addAssign( irradiance );
  16066. }
  16067. }
  16068. class LightProbeNode extends AnalyticLightNode {
  16069. static get type() {
  16070. return 'LightProbeNode';
  16071. }
  16072. constructor( light = null ) {
  16073. super( light );
  16074. const array = [];
  16075. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  16076. this.lightProbe = uniformArray( array );
  16077. }
  16078. update( frame ) {
  16079. const { light } = this;
  16080. super.update( frame );
  16081. //
  16082. for ( let i = 0; i < 9; i ++ ) {
  16083. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  16084. }
  16085. }
  16086. setup( builder ) {
  16087. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  16088. builder.context.irradiance.addAssign( irradiance );
  16089. }
  16090. }
  16091. class NodeParser {
  16092. parseFunction( /*source*/ ) {
  16093. console.warn( 'Abstract function.' );
  16094. }
  16095. }
  16096. class NodeFunction {
  16097. constructor( type, inputs, name = '', precision = '' ) {
  16098. this.type = type;
  16099. this.inputs = inputs;
  16100. this.name = name;
  16101. this.precision = precision;
  16102. }
  16103. getCode( /*name = this.name*/ ) {
  16104. console.warn( 'Abstract function.' );
  16105. }
  16106. }
  16107. NodeFunction.isNodeFunction = true;
  16108. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  16109. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  16110. const pragmaMain = '#pragma main';
  16111. const parse$1 = ( source ) => {
  16112. source = source.trim();
  16113. const pragmaMainIndex = source.indexOf( pragmaMain );
  16114. const mainCode = pragmaMainIndex !== - 1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  16115. const declaration = mainCode.match( declarationRegexp$1 );
  16116. if ( declaration !== null && declaration.length === 5 ) {
  16117. // tokenizer
  16118. const inputsCode = declaration[ 4 ];
  16119. const propsMatches = [];
  16120. let nameMatch = null;
  16121. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  16122. propsMatches.push( nameMatch );
  16123. }
  16124. // parser
  16125. const inputs = [];
  16126. let i = 0;
  16127. while ( i < propsMatches.length ) {
  16128. const isConst = propsMatches[ i ][ 0 ] === 'const';
  16129. if ( isConst === true ) {
  16130. i ++;
  16131. }
  16132. let qualifier = propsMatches[ i ][ 0 ];
  16133. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  16134. i ++;
  16135. } else {
  16136. qualifier = '';
  16137. }
  16138. const type = propsMatches[ i ++ ][ 0 ];
  16139. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  16140. if ( Number.isNaN( count ) === false ) i ++;
  16141. else count = null;
  16142. const name = propsMatches[ i ++ ][ 0 ];
  16143. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  16144. }
  16145. //
  16146. const blockCode = mainCode.substring( declaration[ 0 ].length );
  16147. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  16148. const type = declaration[ 2 ];
  16149. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  16150. const headerCode = pragmaMainIndex !== - 1 ? source.slice( 0, pragmaMainIndex ) : '';
  16151. return {
  16152. type,
  16153. inputs,
  16154. name,
  16155. precision,
  16156. inputsCode,
  16157. blockCode,
  16158. headerCode
  16159. };
  16160. } else {
  16161. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  16162. }
  16163. };
  16164. class GLSLNodeFunction extends NodeFunction {
  16165. constructor( source ) {
  16166. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  16167. super( type, inputs, name, precision );
  16168. this.inputsCode = inputsCode;
  16169. this.blockCode = blockCode;
  16170. this.headerCode = headerCode;
  16171. }
  16172. getCode( name = this.name ) {
  16173. let code;
  16174. const blockCode = this.blockCode;
  16175. if ( blockCode !== '' ) {
  16176. const { type, inputsCode, headerCode, precision } = this;
  16177. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  16178. if ( precision !== '' ) {
  16179. declarationCode = `${ precision } ${ declarationCode }`;
  16180. }
  16181. code = headerCode + declarationCode + blockCode;
  16182. } else {
  16183. // interface function
  16184. code = '';
  16185. }
  16186. return code;
  16187. }
  16188. }
  16189. class GLSLNodeParser extends NodeParser {
  16190. parseFunction( source ) {
  16191. return new GLSLNodeFunction( source );
  16192. }
  16193. }
  16194. const outputNodeMap = new WeakMap();
  16195. class Nodes extends DataMap {
  16196. constructor( renderer, backend ) {
  16197. super();
  16198. this.renderer = renderer;
  16199. this.backend = backend;
  16200. this.nodeFrame = new NodeFrame();
  16201. this.nodeBuilderCache = new Map();
  16202. this.callHashCache = new ChainMap();
  16203. this.groupsData = new ChainMap();
  16204. }
  16205. updateGroup( nodeUniformsGroup ) {
  16206. const groupNode = nodeUniformsGroup.groupNode;
  16207. const name = groupNode.name;
  16208. // objectGroup is every updated
  16209. if ( name === objectGroup.name ) return true;
  16210. // renderGroup is updated once per render/compute call
  16211. if ( name === renderGroup.name ) {
  16212. const uniformsGroupData = this.get( nodeUniformsGroup );
  16213. const renderId = this.nodeFrame.renderId;
  16214. if ( uniformsGroupData.renderId !== renderId ) {
  16215. uniformsGroupData.renderId = renderId;
  16216. return true;
  16217. }
  16218. return false;
  16219. }
  16220. // frameGroup is updated once per frame
  16221. if ( name === frameGroup.name ) {
  16222. const uniformsGroupData = this.get( nodeUniformsGroup );
  16223. const frameId = this.nodeFrame.frameId;
  16224. if ( uniformsGroupData.frameId !== frameId ) {
  16225. uniformsGroupData.frameId = frameId;
  16226. return true;
  16227. }
  16228. return false;
  16229. }
  16230. // other groups are updated just when groupNode.needsUpdate is true
  16231. const groupChain = [ groupNode, nodeUniformsGroup ];
  16232. let groupData = this.groupsData.get( groupChain );
  16233. if ( groupData === undefined ) this.groupsData.set( groupChain, groupData = {} );
  16234. if ( groupData.version !== groupNode.version ) {
  16235. groupData.version = groupNode.version;
  16236. return true;
  16237. }
  16238. return false;
  16239. }
  16240. getForRenderCacheKey( renderObject ) {
  16241. return renderObject.initialCacheKey;
  16242. }
  16243. getForRender( renderObject ) {
  16244. const renderObjectData = this.get( renderObject );
  16245. let nodeBuilderState = renderObjectData.nodeBuilderState;
  16246. if ( nodeBuilderState === undefined ) {
  16247. const { nodeBuilderCache } = this;
  16248. const cacheKey = this.getForRenderCacheKey( renderObject );
  16249. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  16250. if ( nodeBuilderState === undefined ) {
  16251. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  16252. nodeBuilder.scene = renderObject.scene;
  16253. nodeBuilder.material = renderObject.material;
  16254. nodeBuilder.camera = renderObject.camera;
  16255. nodeBuilder.context.material = renderObject.material;
  16256. nodeBuilder.lightsNode = renderObject.lightsNode;
  16257. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  16258. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  16259. nodeBuilder.clippingContext = renderObject.clippingContext;
  16260. nodeBuilder.build();
  16261. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  16262. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  16263. }
  16264. nodeBuilderState.usedTimes ++;
  16265. renderObjectData.nodeBuilderState = nodeBuilderState;
  16266. }
  16267. return nodeBuilderState;
  16268. }
  16269. delete( object ) {
  16270. if ( object.isRenderObject ) {
  16271. const nodeBuilderState = this.get( object ).nodeBuilderState;
  16272. nodeBuilderState.usedTimes --;
  16273. if ( nodeBuilderState.usedTimes === 0 ) {
  16274. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  16275. }
  16276. }
  16277. return super.delete( object );
  16278. }
  16279. getForCompute( computeNode ) {
  16280. const computeData = this.get( computeNode );
  16281. let nodeBuilderState = computeData.nodeBuilderState;
  16282. if ( nodeBuilderState === undefined ) {
  16283. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  16284. nodeBuilder.build();
  16285. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  16286. computeData.nodeBuilderState = nodeBuilderState;
  16287. }
  16288. return nodeBuilderState;
  16289. }
  16290. _createNodeBuilderState( nodeBuilder ) {
  16291. return new NodeBuilderState(
  16292. nodeBuilder.vertexShader,
  16293. nodeBuilder.fragmentShader,
  16294. nodeBuilder.computeShader,
  16295. nodeBuilder.getAttributesArray(),
  16296. nodeBuilder.getBindings(),
  16297. nodeBuilder.updateNodes,
  16298. nodeBuilder.updateBeforeNodes,
  16299. nodeBuilder.updateAfterNodes,
  16300. nodeBuilder.monitor,
  16301. nodeBuilder.transforms
  16302. );
  16303. }
  16304. getEnvironmentNode( scene ) {
  16305. return scene.environmentNode || this.get( scene ).environmentNode || null;
  16306. }
  16307. getBackgroundNode( scene ) {
  16308. return scene.backgroundNode || this.get( scene ).backgroundNode || null;
  16309. }
  16310. getFogNode( scene ) {
  16311. return scene.fogNode || this.get( scene ).fogNode || null;
  16312. }
  16313. getCacheKey( scene, lightsNode ) {
  16314. const chain = [ scene, lightsNode ];
  16315. const callId = this.renderer.info.calls;
  16316. let cacheKeyData = this.callHashCache.get( chain );
  16317. if ( cacheKeyData === undefined || cacheKeyData.callId !== callId ) {
  16318. const environmentNode = this.getEnvironmentNode( scene );
  16319. const fogNode = this.getFogNode( scene );
  16320. const values = [];
  16321. if ( lightsNode ) values.push( lightsNode.getCacheKey( true ) );
  16322. if ( environmentNode ) values.push( environmentNode.getCacheKey() );
  16323. if ( fogNode ) values.push( fogNode.getCacheKey() );
  16324. values.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  16325. cacheKeyData = {
  16326. callId,
  16327. cacheKey: hashArray( values )
  16328. };
  16329. this.callHashCache.set( chain, cacheKeyData );
  16330. }
  16331. return cacheKeyData.cacheKey;
  16332. }
  16333. updateScene( scene ) {
  16334. this.updateEnvironment( scene );
  16335. this.updateFog( scene );
  16336. this.updateBackground( scene );
  16337. }
  16338. get isToneMappingState() {
  16339. return this.renderer.getRenderTarget() ? false : true;
  16340. }
  16341. updateBackground( scene ) {
  16342. const sceneData = this.get( scene );
  16343. const background = scene.background;
  16344. if ( background ) {
  16345. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  16346. if ( sceneData.background !== background || forceUpdate ) {
  16347. let backgroundNode = null;
  16348. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  16349. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  16350. backgroundNode = pmremTexture( background );
  16351. } else {
  16352. let envMap;
  16353. if ( background.isCubeTexture === true ) {
  16354. envMap = cubeTexture( background );
  16355. } else {
  16356. envMap = texture( background );
  16357. }
  16358. backgroundNode = cubeMapNode( envMap );
  16359. }
  16360. } else if ( background.isTexture === true ) {
  16361. backgroundNode = texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  16362. } else if ( background.isColor !== true ) {
  16363. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  16364. }
  16365. sceneData.backgroundNode = backgroundNode;
  16366. sceneData.background = background;
  16367. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  16368. }
  16369. } else if ( sceneData.backgroundNode ) {
  16370. delete sceneData.backgroundNode;
  16371. delete sceneData.background;
  16372. }
  16373. }
  16374. updateFog( scene ) {
  16375. const sceneData = this.get( scene );
  16376. const fog = scene.fog;
  16377. if ( fog ) {
  16378. if ( sceneData.fog !== fog ) {
  16379. let fogNode = null;
  16380. if ( fog.isFogExp2 ) {
  16381. const color = reference( 'color', 'color', fog ).setGroup( renderGroup );
  16382. const density = reference( 'density', 'float', fog ).setGroup( renderGroup );
  16383. fogNode = densityFog( color, density );
  16384. } else if ( fog.isFog ) {
  16385. const color = reference( 'color', 'color', fog ).setGroup( renderGroup );
  16386. const near = reference( 'near', 'float', fog ).setGroup( renderGroup );
  16387. const far = reference( 'far', 'float', fog ).setGroup( renderGroup );
  16388. fogNode = rangeFog( color, near, far );
  16389. } else {
  16390. console.error( 'WebGPUNodes: Unsupported fog configuration.', fog );
  16391. }
  16392. sceneData.fogNode = fogNode;
  16393. sceneData.fog = fog;
  16394. }
  16395. } else {
  16396. delete sceneData.fogNode;
  16397. delete sceneData.fog;
  16398. }
  16399. }
  16400. updateEnvironment( scene ) {
  16401. const sceneData = this.get( scene );
  16402. const environment = scene.environment;
  16403. if ( environment ) {
  16404. if ( sceneData.environment !== environment ) {
  16405. let environmentNode = null;
  16406. if ( environment.isCubeTexture === true ) {
  16407. environmentNode = cubeTexture( environment );
  16408. } else if ( environment.isTexture === true ) {
  16409. environmentNode = texture( environment );
  16410. } else {
  16411. console.error( 'Nodes: Unsupported environment configuration.', environment );
  16412. }
  16413. sceneData.environmentNode = environmentNode;
  16414. sceneData.environment = environment;
  16415. }
  16416. } else if ( sceneData.environmentNode ) {
  16417. delete sceneData.environmentNode;
  16418. delete sceneData.environment;
  16419. }
  16420. }
  16421. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  16422. const nodeFrame = this.nodeFrame;
  16423. nodeFrame.renderer = renderer;
  16424. nodeFrame.scene = scene;
  16425. nodeFrame.object = object;
  16426. nodeFrame.camera = camera;
  16427. nodeFrame.material = material;
  16428. return nodeFrame;
  16429. }
  16430. getNodeFrameForRender( renderObject ) {
  16431. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  16432. }
  16433. getOutputCacheKey() {
  16434. const renderer = this.renderer;
  16435. return renderer.toneMapping + ',' + renderer.currentColorSpace;
  16436. }
  16437. hasOutputChange( outputTarget ) {
  16438. const cacheKey = outputNodeMap.get( outputTarget );
  16439. return cacheKey !== this.getOutputCacheKey();
  16440. }
  16441. getOutputNode( outputTexture ) {
  16442. const renderer = this.renderer;
  16443. const cacheKey = this.getOutputCacheKey();
  16444. const output = texture( outputTexture, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  16445. outputNodeMap.set( outputTexture, cacheKey );
  16446. return output;
  16447. }
  16448. updateBefore( renderObject ) {
  16449. const nodeBuilder = renderObject.getNodeBuilderState();
  16450. for ( const node of nodeBuilder.updateBeforeNodes ) {
  16451. // update frame state for each node
  16452. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  16453. }
  16454. }
  16455. updateAfter( renderObject ) {
  16456. const nodeBuilder = renderObject.getNodeBuilderState();
  16457. for ( const node of nodeBuilder.updateAfterNodes ) {
  16458. // update frame state for each node
  16459. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  16460. }
  16461. }
  16462. updateForCompute( computeNode ) {
  16463. const nodeFrame = this.getNodeFrame();
  16464. const nodeBuilder = this.getForCompute( computeNode );
  16465. for ( const node of nodeBuilder.updateNodes ) {
  16466. nodeFrame.updateNode( node );
  16467. }
  16468. }
  16469. updateForRender( renderObject ) {
  16470. const nodeFrame = this.getNodeFrameForRender( renderObject );
  16471. const nodeBuilder = renderObject.getNodeBuilderState();
  16472. for ( const node of nodeBuilder.updateNodes ) {
  16473. nodeFrame.updateNode( node );
  16474. }
  16475. }
  16476. needsRefresh( renderObject ) {
  16477. const nodeFrame = this.getNodeFrameForRender( renderObject );
  16478. const monitor = renderObject.getMonitor();
  16479. return monitor.needsRefresh( renderObject, nodeFrame );
  16480. }
  16481. dispose() {
  16482. super.dispose();
  16483. this.nodeFrame = new NodeFrame();
  16484. this.nodeBuilderCache = new Map();
  16485. }
  16486. }
  16487. const _plane = /*@__PURE__*/ new Plane();
  16488. class ClippingContext {
  16489. constructor( parentContext = null ) {
  16490. this.version = 0;
  16491. this.clipIntersection = null;
  16492. this.cacheKey = '';
  16493. if ( parentContext === null ) {
  16494. this.intersectionPlanes = [];
  16495. this.unionPlanes = [];
  16496. this.viewNormalMatrix = new Matrix3();
  16497. this.clippingGroupContexts = new WeakMap();
  16498. this.shadowPass = false;
  16499. } else {
  16500. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  16501. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  16502. this.shadowPass = parentContext.shadowPass;
  16503. this.viewMatrix = parentContext.viewMatrix;
  16504. }
  16505. this.parentVersion = null;
  16506. }
  16507. projectPlanes( source, destination, offset ) {
  16508. const l = source.length;
  16509. for ( let i = 0; i < l; i ++ ) {
  16510. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  16511. const v = destination[ offset + i ];
  16512. const normal = _plane.normal;
  16513. v.x = - normal.x;
  16514. v.y = - normal.y;
  16515. v.z = - normal.z;
  16516. v.w = _plane.constant;
  16517. }
  16518. }
  16519. updateGlobal( scene, camera ) {
  16520. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowNodeMaterial );
  16521. this.viewMatrix = camera.matrixWorldInverse;
  16522. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  16523. }
  16524. update( parentContext, clippingGroup ) {
  16525. let update = false;
  16526. if ( parentContext.version !== this.parentVersion ) {
  16527. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  16528. this.unionPlanes = Array.from( parentContext.unionPlanes );
  16529. this.parentVersion = parentContext.version;
  16530. }
  16531. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  16532. this.clipIntersection = clippingGroup.clipIntersection;
  16533. if ( this.clipIntersection ) {
  16534. this.unionPlanes.length = parentContext.unionPlanes.length;
  16535. } else {
  16536. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  16537. }
  16538. }
  16539. const srcClippingPlanes = clippingGroup.clippingPlanes;
  16540. const l = srcClippingPlanes.length;
  16541. let dstClippingPlanes;
  16542. let offset;
  16543. if ( this.clipIntersection ) {
  16544. dstClippingPlanes = this.intersectionPlanes;
  16545. offset = parentContext.intersectionPlanes.length;
  16546. } else {
  16547. dstClippingPlanes = this.unionPlanes;
  16548. offset = parentContext.unionPlanes.length;
  16549. }
  16550. if ( dstClippingPlanes.length !== offset + l ) {
  16551. dstClippingPlanes.length = offset + l;
  16552. for ( let i = 0; i < l; i ++ ) {
  16553. dstClippingPlanes[ offset + i ] = new Vector4();
  16554. }
  16555. update = true;
  16556. }
  16557. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  16558. if ( update ) {
  16559. this.version ++;
  16560. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  16561. }
  16562. }
  16563. getGroupContext( clippingGroup ) {
  16564. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  16565. let context = this.clippingGroupContexts.get( clippingGroup );
  16566. if ( context === undefined ) {
  16567. context = new ClippingContext( this );
  16568. this.clippingGroupContexts.set( clippingGroup, context );
  16569. }
  16570. context.update( this, clippingGroup );
  16571. return context;
  16572. }
  16573. get unionClippingCount() {
  16574. return this.unionPlanes.length;
  16575. }
  16576. }
  16577. class RenderBundle {
  16578. constructor( scene, camera ) {
  16579. this.scene = scene;
  16580. this.camera = camera;
  16581. }
  16582. clone() {
  16583. return Object.assign( new this.constructor(), this );
  16584. }
  16585. }
  16586. class RenderBundles {
  16587. constructor() {
  16588. this.lists = new ChainMap();
  16589. }
  16590. get( scene, camera ) {
  16591. const lists = this.lists;
  16592. const keys = [ scene, camera ];
  16593. let list = lists.get( keys );
  16594. if ( list === undefined ) {
  16595. list = new RenderBundle( scene, camera );
  16596. lists.set( keys, list );
  16597. }
  16598. return list;
  16599. }
  16600. dispose() {
  16601. this.lists = new ChainMap();
  16602. }
  16603. }
  16604. class NodeLibrary {
  16605. constructor() {
  16606. this.lightNodes = new WeakMap();
  16607. this.materialNodes = new Map();
  16608. this.toneMappingNodes = new Map();
  16609. }
  16610. fromMaterial( material ) {
  16611. if ( material.isNodeMaterial ) return material;
  16612. let nodeMaterial = null;
  16613. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  16614. if ( nodeMaterialClass !== null ) {
  16615. nodeMaterial = new nodeMaterialClass();
  16616. for ( const key in material ) {
  16617. nodeMaterial[ key ] = material[ key ];
  16618. }
  16619. }
  16620. return nodeMaterial;
  16621. }
  16622. addToneMapping( toneMappingNode, toneMapping ) {
  16623. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  16624. }
  16625. getToneMappingFunction( toneMapping ) {
  16626. return this.toneMappingNodes.get( toneMapping ) || null;
  16627. }
  16628. getMaterialNodeClass( materialType ) {
  16629. return this.materialNodes.get( materialType ) || null;
  16630. }
  16631. addMaterial( materialNodeClass, materialClassType ) {
  16632. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  16633. }
  16634. getLightNodeClass( light ) {
  16635. return this.lightNodes.get( light ) || null;
  16636. }
  16637. addLight( lightNodeClass, lightClass ) {
  16638. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  16639. }
  16640. addType( nodeClass, type, library ) {
  16641. if ( library.has( type ) ) {
  16642. console.warn( `Redefinition of node ${ type }` );
  16643. return;
  16644. }
  16645. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  16646. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  16647. library.set( type, nodeClass );
  16648. }
  16649. addClass( nodeClass, baseClass, library ) {
  16650. if ( library.has( baseClass ) ) {
  16651. console.warn( `Redefinition of node ${ baseClass.name }` );
  16652. return;
  16653. }
  16654. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  16655. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  16656. library.set( baseClass, nodeClass );
  16657. }
  16658. }
  16659. const _defaultLights = /*@__PURE__*/ new LightsNode();
  16660. class Lighting extends ChainMap {
  16661. constructor() {
  16662. super();
  16663. }
  16664. createNode( lights = [] ) {
  16665. return new LightsNode().setLights( lights );
  16666. }
  16667. getNode( scene, camera ) {
  16668. // ignore post-processing
  16669. if ( scene.isQuadMesh ) return _defaultLights;
  16670. // tiled lighting
  16671. const keys = [ scene, camera ];
  16672. let node = this.get( keys );
  16673. if ( node === undefined ) {
  16674. node = this.createNode();
  16675. this.set( keys, node );
  16676. }
  16677. return node;
  16678. }
  16679. }
  16680. const _scene = /*@__PURE__*/ new Scene();
  16681. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  16682. const _screen = /*@__PURE__*/ new Vector4();
  16683. const _frustum = /*@__PURE__*/ new Frustum();
  16684. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  16685. const _vector4 = /*@__PURE__*/ new Vector4();
  16686. class Renderer {
  16687. constructor( backend, parameters = {} ) {
  16688. this.isRenderer = true;
  16689. //
  16690. const {
  16691. logarithmicDepthBuffer = false,
  16692. alpha = true,
  16693. depth = true,
  16694. stencil = false,
  16695. antialias = false,
  16696. samples = 0,
  16697. getFallback = null
  16698. } = parameters;
  16699. // public
  16700. this.domElement = backend.getDomElement();
  16701. this.backend = backend;
  16702. this.samples = samples || ( antialias === true ) ? 4 : 0;
  16703. this.autoClear = true;
  16704. this.autoClearColor = true;
  16705. this.autoClearDepth = true;
  16706. this.autoClearStencil = true;
  16707. this.alpha = alpha;
  16708. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  16709. this.outputColorSpace = SRGBColorSpace;
  16710. this.toneMapping = NoToneMapping;
  16711. this.toneMappingExposure = 1.0;
  16712. this.sortObjects = true;
  16713. this.depth = depth;
  16714. this.stencil = stencil;
  16715. this.info = new Info();
  16716. this.nodes = {
  16717. modelViewMatrix: null,
  16718. modelNormalViewMatrix: null
  16719. };
  16720. this.library = new NodeLibrary();
  16721. this.lighting = new Lighting();
  16722. // internals
  16723. this._getFallback = getFallback;
  16724. this._pixelRatio = 1;
  16725. this._width = this.domElement.width;
  16726. this._height = this.domElement.height;
  16727. this._viewport = new Vector4( 0, 0, this._width, this._height );
  16728. this._scissor = new Vector4( 0, 0, this._width, this._height );
  16729. this._scissorTest = false;
  16730. this._attributes = null;
  16731. this._geometries = null;
  16732. this._nodes = null;
  16733. this._animation = null;
  16734. this._bindings = null;
  16735. this._objects = null;
  16736. this._pipelines = null;
  16737. this._bundles = null;
  16738. this._renderLists = null;
  16739. this._renderContexts = null;
  16740. this._textures = null;
  16741. this._background = null;
  16742. this._quad = new QuadMesh( new NodeMaterial() );
  16743. this._quad.material.type = 'Renderer_output';
  16744. this._currentRenderContext = null;
  16745. this._opaqueSort = null;
  16746. this._transparentSort = null;
  16747. this._frameBufferTarget = null;
  16748. const alphaClear = this.alpha === true ? 0 : 1;
  16749. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  16750. this._clearDepth = 1;
  16751. this._clearStencil = 0;
  16752. this._renderTarget = null;
  16753. this._activeCubeFace = 0;
  16754. this._activeMipmapLevel = 0;
  16755. this._mrt = null;
  16756. this._renderObjectFunction = null;
  16757. this._currentRenderObjectFunction = null;
  16758. this._currentRenderBundle = null;
  16759. this._handleObjectFunction = this._renderObjectDirect;
  16760. this._isDeviceLost = false;
  16761. this.onDeviceLost = this._onDeviceLost;
  16762. this._initialized = false;
  16763. this._initPromise = null;
  16764. this._compilationPromises = null;
  16765. this.transparent = true;
  16766. this.opaque = true;
  16767. this.shadowMap = {
  16768. enabled: false,
  16769. type: PCFShadowMap
  16770. };
  16771. this.xr = {
  16772. enabled: false
  16773. };
  16774. this.debug = {
  16775. checkShaderErrors: true,
  16776. onShaderError: null,
  16777. getShaderAsync: async ( scene, camera, object ) => {
  16778. await this.compileAsync( scene, camera );
  16779. const renderList = this._renderLists.get( scene, camera );
  16780. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  16781. const material = scene.overrideMaterial || object.material;
  16782. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  16783. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  16784. return { fragmentShader, vertexShader };
  16785. }
  16786. };
  16787. }
  16788. async init() {
  16789. if ( this._initialized ) {
  16790. throw new Error( 'Renderer: Backend has already been initialized.' );
  16791. }
  16792. if ( this._initPromise !== null ) {
  16793. return this._initPromise;
  16794. }
  16795. this._initPromise = new Promise( async ( resolve, reject ) => {
  16796. let backend = this.backend;
  16797. try {
  16798. await backend.init( this );
  16799. } catch ( error ) {
  16800. if ( this._getFallback !== null ) {
  16801. // try the fallback
  16802. try {
  16803. this.backend = backend = this._getFallback( error );
  16804. await backend.init( this );
  16805. } catch ( error ) {
  16806. reject( error );
  16807. return;
  16808. }
  16809. } else {
  16810. reject( error );
  16811. return;
  16812. }
  16813. }
  16814. this._nodes = new Nodes( this, backend );
  16815. this._animation = new Animation( this._nodes, this.info );
  16816. this._attributes = new Attributes( backend );
  16817. this._background = new Background( this, this._nodes );
  16818. this._geometries = new Geometries( this._attributes, this.info );
  16819. this._textures = new Textures( this, backend, this.info );
  16820. this._pipelines = new Pipelines( backend, this._nodes );
  16821. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  16822. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  16823. this._renderLists = new RenderLists( this.lighting );
  16824. this._bundles = new RenderBundles();
  16825. this._renderContexts = new RenderContexts();
  16826. //
  16827. this._animation.start();
  16828. this._initialized = true;
  16829. resolve();
  16830. } );
  16831. return this._initPromise;
  16832. }
  16833. get coordinateSystem() {
  16834. return this.backend.coordinateSystem;
  16835. }
  16836. async compileAsync( scene, camera, targetScene = null ) {
  16837. if ( this._isDeviceLost === true ) return;
  16838. if ( this._initialized === false ) await this.init();
  16839. // preserve render tree
  16840. const nodeFrame = this._nodes.nodeFrame;
  16841. const previousRenderId = nodeFrame.renderId;
  16842. const previousRenderContext = this._currentRenderContext;
  16843. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  16844. const previousCompilationPromises = this._compilationPromises;
  16845. //
  16846. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  16847. if ( targetScene === null ) targetScene = scene;
  16848. const renderTarget = this._renderTarget;
  16849. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  16850. const activeMipmapLevel = this._activeMipmapLevel;
  16851. const compilationPromises = [];
  16852. this._currentRenderContext = renderContext;
  16853. this._currentRenderObjectFunction = this.renderObject;
  16854. this._handleObjectFunction = this._createObjectPipeline;
  16855. this._compilationPromises = compilationPromises;
  16856. nodeFrame.renderId ++;
  16857. //
  16858. nodeFrame.update();
  16859. //
  16860. renderContext.depth = this.depth;
  16861. renderContext.stencil = this.stencil;
  16862. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  16863. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  16864. //
  16865. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  16866. //
  16867. const renderList = this._renderLists.get( scene, camera );
  16868. renderList.begin();
  16869. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  16870. // include lights from target scene
  16871. if ( targetScene !== scene ) {
  16872. targetScene.traverseVisible( function ( object ) {
  16873. if ( object.isLight && object.layers.test( camera.layers ) ) {
  16874. renderList.pushLight( object );
  16875. }
  16876. } );
  16877. }
  16878. renderList.finish();
  16879. //
  16880. if ( renderTarget !== null ) {
  16881. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  16882. const renderTargetData = this._textures.get( renderTarget );
  16883. renderContext.textures = renderTargetData.textures;
  16884. renderContext.depthTexture = renderTargetData.depthTexture;
  16885. } else {
  16886. renderContext.textures = null;
  16887. renderContext.depthTexture = null;
  16888. }
  16889. //
  16890. this._nodes.updateScene( sceneRef );
  16891. //
  16892. this._background.update( sceneRef, renderList, renderContext );
  16893. // process render lists
  16894. const opaqueObjects = renderList.opaque;
  16895. const transparentObjects = renderList.transparent;
  16896. const transparentDoublePassObjects = renderList.transparentDoublePass;
  16897. const lightsNode = renderList.lightsNode;
  16898. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  16899. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  16900. // restore render tree
  16901. nodeFrame.renderId = previousRenderId;
  16902. this._currentRenderContext = previousRenderContext;
  16903. this._currentRenderObjectFunction = previousRenderObjectFunction;
  16904. this._compilationPromises = previousCompilationPromises;
  16905. this._handleObjectFunction = this._renderObjectDirect;
  16906. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  16907. await Promise.all( compilationPromises );
  16908. }
  16909. async renderAsync( scene, camera ) {
  16910. if ( this._initialized === false ) await this.init();
  16911. const renderContext = this._renderScene( scene, camera );
  16912. await this.backend.resolveTimestampAsync( renderContext, 'render' );
  16913. }
  16914. async waitForGPU() {
  16915. await this.backend.waitForGPU();
  16916. }
  16917. setMRT( mrt ) {
  16918. this._mrt = mrt;
  16919. return this;
  16920. }
  16921. getMRT() {
  16922. return this._mrt;
  16923. }
  16924. _onDeviceLost( info ) {
  16925. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  16926. if ( info.reason ) {
  16927. errorMessage += `\nReason: ${info.reason}`;
  16928. }
  16929. console.error( errorMessage );
  16930. this._isDeviceLost = true;
  16931. }
  16932. _renderBundle( bundle, sceneRef, lightsNode ) {
  16933. const { bundleGroup, camera, renderList } = bundle;
  16934. const renderContext = this._currentRenderContext;
  16935. //
  16936. const renderBundle = this._bundles.get( bundleGroup, camera );
  16937. const renderBundleData = this.backend.get( renderBundle );
  16938. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  16939. //
  16940. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  16941. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  16942. renderBundleData.renderContexts.add( renderContext );
  16943. if ( renderBundleNeedsUpdate ) {
  16944. this.backend.beginBundle( renderContext );
  16945. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  16946. renderBundleData.renderObjects = [];
  16947. }
  16948. this._currentRenderBundle = renderBundle;
  16949. const opaqueObjects = renderList.opaque;
  16950. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  16951. this._currentRenderBundle = null;
  16952. //
  16953. this.backend.finishBundle( renderContext, renderBundle );
  16954. renderBundleData.version = bundleGroup.version;
  16955. } else {
  16956. const { renderObjects } = renderBundleData;
  16957. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  16958. const renderObject = renderObjects[ i ];
  16959. if ( this._nodes.needsRefresh( renderObject ) ) {
  16960. this._nodes.updateBefore( renderObject );
  16961. this._nodes.updateForRender( renderObject );
  16962. this._bindings.updateForRender( renderObject );
  16963. this._nodes.updateAfter( renderObject );
  16964. }
  16965. }
  16966. }
  16967. this.backend.addBundle( renderContext, renderBundle );
  16968. }
  16969. render( scene, camera ) {
  16970. if ( this._initialized === false ) {
  16971. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  16972. return this.renderAsync( scene, camera );
  16973. }
  16974. this._renderScene( scene, camera );
  16975. }
  16976. _getFrameBufferTarget() {
  16977. const { currentToneMapping, currentColorSpace } = this;
  16978. const useToneMapping = currentToneMapping !== NoToneMapping;
  16979. const useColorSpace = currentColorSpace !== LinearSRGBColorSpace;
  16980. if ( useToneMapping === false && useColorSpace === false ) return null;
  16981. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  16982. const { depth, stencil } = this;
  16983. let frameBufferTarget = this._frameBufferTarget;
  16984. if ( frameBufferTarget === null ) {
  16985. frameBufferTarget = new RenderTarget( width, height, {
  16986. depthBuffer: depth,
  16987. stencilBuffer: stencil,
  16988. type: HalfFloatType, // FloatType
  16989. format: RGBAFormat,
  16990. colorSpace: LinearSRGBColorSpace,
  16991. generateMipmaps: false,
  16992. minFilter: LinearFilter,
  16993. magFilter: LinearFilter,
  16994. samples: this.samples
  16995. } );
  16996. frameBufferTarget.isPostProcessingRenderTarget = true;
  16997. this._frameBufferTarget = frameBufferTarget;
  16998. }
  16999. frameBufferTarget.depthBuffer = depth;
  17000. frameBufferTarget.stencilBuffer = stencil;
  17001. frameBufferTarget.setSize( width, height );
  17002. frameBufferTarget.viewport.copy( this._viewport );
  17003. frameBufferTarget.scissor.copy( this._scissor );
  17004. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  17005. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  17006. frameBufferTarget.scissorTest = this._scissorTest;
  17007. return frameBufferTarget;
  17008. }
  17009. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  17010. if ( this._isDeviceLost === true ) return;
  17011. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  17012. // preserve render tree
  17013. const nodeFrame = this._nodes.nodeFrame;
  17014. const previousRenderId = nodeFrame.renderId;
  17015. const previousRenderContext = this._currentRenderContext;
  17016. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  17017. //
  17018. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  17019. const outputRenderTarget = this._renderTarget;
  17020. const activeCubeFace = this._activeCubeFace;
  17021. const activeMipmapLevel = this._activeMipmapLevel;
  17022. //
  17023. let renderTarget;
  17024. if ( frameBufferTarget !== null ) {
  17025. renderTarget = frameBufferTarget;
  17026. this.setRenderTarget( renderTarget );
  17027. } else {
  17028. renderTarget = outputRenderTarget;
  17029. }
  17030. //
  17031. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  17032. this._currentRenderContext = renderContext;
  17033. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  17034. //
  17035. this.info.calls ++;
  17036. this.info.render.calls ++;
  17037. this.info.render.frameCalls ++;
  17038. nodeFrame.renderId = this.info.calls;
  17039. //
  17040. const coordinateSystem = this.coordinateSystem;
  17041. if ( camera.coordinateSystem !== coordinateSystem ) {
  17042. camera.coordinateSystem = coordinateSystem;
  17043. camera.updateProjectionMatrix();
  17044. }
  17045. //
  17046. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  17047. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  17048. //
  17049. let viewport = this._viewport;
  17050. let scissor = this._scissor;
  17051. let pixelRatio = this._pixelRatio;
  17052. if ( renderTarget !== null ) {
  17053. viewport = renderTarget.viewport;
  17054. scissor = renderTarget.scissor;
  17055. pixelRatio = 1;
  17056. }
  17057. this.getDrawingBufferSize( _drawingBufferSize );
  17058. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  17059. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  17060. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  17061. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  17062. renderContext.viewportValue.width >>= activeMipmapLevel;
  17063. renderContext.viewportValue.height >>= activeMipmapLevel;
  17064. renderContext.viewportValue.minDepth = minDepth;
  17065. renderContext.viewportValue.maxDepth = maxDepth;
  17066. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  17067. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  17068. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  17069. renderContext.scissorValue.width >>= activeMipmapLevel;
  17070. renderContext.scissorValue.height >>= activeMipmapLevel;
  17071. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  17072. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  17073. //
  17074. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  17075. //
  17076. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  17077. _frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  17078. const renderList = this._renderLists.get( scene, camera );
  17079. renderList.begin();
  17080. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  17081. renderList.finish();
  17082. if ( this.sortObjects === true ) {
  17083. renderList.sort( this._opaqueSort, this._transparentSort );
  17084. }
  17085. //
  17086. if ( renderTarget !== null ) {
  17087. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  17088. const renderTargetData = this._textures.get( renderTarget );
  17089. renderContext.textures = renderTargetData.textures;
  17090. renderContext.depthTexture = renderTargetData.depthTexture;
  17091. renderContext.width = renderTargetData.width;
  17092. renderContext.height = renderTargetData.height;
  17093. renderContext.renderTarget = renderTarget;
  17094. renderContext.depth = renderTarget.depthBuffer;
  17095. renderContext.stencil = renderTarget.stencilBuffer;
  17096. } else {
  17097. renderContext.textures = null;
  17098. renderContext.depthTexture = null;
  17099. renderContext.width = this.domElement.width;
  17100. renderContext.height = this.domElement.height;
  17101. renderContext.depth = this.depth;
  17102. renderContext.stencil = this.stencil;
  17103. }
  17104. renderContext.width >>= activeMipmapLevel;
  17105. renderContext.height >>= activeMipmapLevel;
  17106. renderContext.activeCubeFace = activeCubeFace;
  17107. renderContext.activeMipmapLevel = activeMipmapLevel;
  17108. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  17109. //
  17110. this._nodes.updateScene( sceneRef );
  17111. //
  17112. this._background.update( sceneRef, renderList, renderContext );
  17113. //
  17114. this.backend.beginRender( renderContext );
  17115. // process render lists
  17116. const {
  17117. bundles,
  17118. lightsNode,
  17119. transparentDoublePass: transparentDoublePassObjects,
  17120. transparent: transparentObjects,
  17121. opaque: opaqueObjects
  17122. } = renderList;
  17123. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  17124. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  17125. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  17126. // finish render pass
  17127. this.backend.finishRender( renderContext );
  17128. // restore render tree
  17129. nodeFrame.renderId = previousRenderId;
  17130. this._currentRenderContext = previousRenderContext;
  17131. this._currentRenderObjectFunction = previousRenderObjectFunction;
  17132. //
  17133. if ( frameBufferTarget !== null ) {
  17134. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  17135. const quad = this._quad;
  17136. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  17137. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  17138. quad.material.needsUpdate = true;
  17139. }
  17140. this._renderScene( quad, quad.camera, false );
  17141. }
  17142. //
  17143. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  17144. //
  17145. return renderContext;
  17146. }
  17147. getMaxAnisotropy() {
  17148. return this.backend.getMaxAnisotropy();
  17149. }
  17150. getActiveCubeFace() {
  17151. return this._activeCubeFace;
  17152. }
  17153. getActiveMipmapLevel() {
  17154. return this._activeMipmapLevel;
  17155. }
  17156. async setAnimationLoop( callback ) {
  17157. if ( this._initialized === false ) await this.init();
  17158. this._animation.setAnimationLoop( callback );
  17159. }
  17160. async getArrayBufferAsync( attribute ) {
  17161. return await this.backend.getArrayBufferAsync( attribute );
  17162. }
  17163. getContext() {
  17164. return this.backend.getContext();
  17165. }
  17166. getPixelRatio() {
  17167. return this._pixelRatio;
  17168. }
  17169. getDrawingBufferSize( target ) {
  17170. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  17171. }
  17172. getSize( target ) {
  17173. return target.set( this._width, this._height );
  17174. }
  17175. setPixelRatio( value = 1 ) {
  17176. if ( this._pixelRatio === value ) return;
  17177. this._pixelRatio = value;
  17178. this.setSize( this._width, this._height, false );
  17179. }
  17180. setDrawingBufferSize( width, height, pixelRatio ) {
  17181. this._width = width;
  17182. this._height = height;
  17183. this._pixelRatio = pixelRatio;
  17184. this.domElement.width = Math.floor( width * pixelRatio );
  17185. this.domElement.height = Math.floor( height * pixelRatio );
  17186. this.setViewport( 0, 0, width, height );
  17187. if ( this._initialized ) this.backend.updateSize();
  17188. }
  17189. setSize( width, height, updateStyle = true ) {
  17190. this._width = width;
  17191. this._height = height;
  17192. this.domElement.width = Math.floor( width * this._pixelRatio );
  17193. this.domElement.height = Math.floor( height * this._pixelRatio );
  17194. if ( updateStyle === true ) {
  17195. this.domElement.style.width = width + 'px';
  17196. this.domElement.style.height = height + 'px';
  17197. }
  17198. this.setViewport( 0, 0, width, height );
  17199. if ( this._initialized ) this.backend.updateSize();
  17200. }
  17201. setOpaqueSort( method ) {
  17202. this._opaqueSort = method;
  17203. }
  17204. setTransparentSort( method ) {
  17205. this._transparentSort = method;
  17206. }
  17207. getScissor( target ) {
  17208. const scissor = this._scissor;
  17209. target.x = scissor.x;
  17210. target.y = scissor.y;
  17211. target.width = scissor.width;
  17212. target.height = scissor.height;
  17213. return target;
  17214. }
  17215. setScissor( x, y, width, height ) {
  17216. const scissor = this._scissor;
  17217. if ( x.isVector4 ) {
  17218. scissor.copy( x );
  17219. } else {
  17220. scissor.set( x, y, width, height );
  17221. }
  17222. }
  17223. getScissorTest() {
  17224. return this._scissorTest;
  17225. }
  17226. setScissorTest( boolean ) {
  17227. this._scissorTest = boolean;
  17228. this.backend.setScissorTest( boolean );
  17229. }
  17230. getViewport( target ) {
  17231. return target.copy( this._viewport );
  17232. }
  17233. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  17234. const viewport = this._viewport;
  17235. if ( x.isVector4 ) {
  17236. viewport.copy( x );
  17237. } else {
  17238. viewport.set( x, y, width, height );
  17239. }
  17240. viewport.minDepth = minDepth;
  17241. viewport.maxDepth = maxDepth;
  17242. }
  17243. getClearColor( target ) {
  17244. return target.copy( this._clearColor );
  17245. }
  17246. setClearColor( color, alpha = 1 ) {
  17247. this._clearColor.set( color );
  17248. this._clearColor.a = alpha;
  17249. }
  17250. getClearAlpha() {
  17251. return this._clearColor.a;
  17252. }
  17253. setClearAlpha( alpha ) {
  17254. this._clearColor.a = alpha;
  17255. }
  17256. getClearDepth() {
  17257. return this._clearDepth;
  17258. }
  17259. setClearDepth( depth ) {
  17260. this._clearDepth = depth;
  17261. }
  17262. getClearStencil() {
  17263. return this._clearStencil;
  17264. }
  17265. setClearStencil( stencil ) {
  17266. this._clearStencil = stencil;
  17267. }
  17268. isOccluded( object ) {
  17269. const renderContext = this._currentRenderContext;
  17270. return renderContext && this.backend.isOccluded( renderContext, object );
  17271. }
  17272. clear( color = true, depth = true, stencil = true ) {
  17273. if ( this._initialized === false ) {
  17274. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  17275. return this.clearAsync( color, depth, stencil );
  17276. }
  17277. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  17278. let renderTargetData = null;
  17279. if ( renderTarget !== null ) {
  17280. this._textures.updateRenderTarget( renderTarget );
  17281. renderTargetData = this._textures.get( renderTarget );
  17282. }
  17283. this.backend.clear( color, depth, stencil, renderTargetData );
  17284. if ( renderTarget !== null && this._renderTarget === null ) {
  17285. // If a color space transform or tone mapping is required,
  17286. // the clear operation clears the intermediate renderTarget texture, but does not update the screen canvas.
  17287. const quad = this._quad;
  17288. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  17289. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  17290. quad.material.needsUpdate = true;
  17291. }
  17292. this._renderScene( quad, quad.camera, false );
  17293. }
  17294. }
  17295. clearColor() {
  17296. return this.clear( true, false, false );
  17297. }
  17298. clearDepth() {
  17299. return this.clear( false, true, false );
  17300. }
  17301. clearStencil() {
  17302. return this.clear( false, false, true );
  17303. }
  17304. async clearAsync( color = true, depth = true, stencil = true ) {
  17305. if ( this._initialized === false ) await this.init();
  17306. this.clear( color, depth, stencil );
  17307. }
  17308. clearColorAsync() {
  17309. return this.clearAsync( true, false, false );
  17310. }
  17311. clearDepthAsync() {
  17312. return this.clearAsync( false, true, false );
  17313. }
  17314. clearStencilAsync() {
  17315. return this.clearAsync( false, false, true );
  17316. }
  17317. get currentToneMapping() {
  17318. return this._renderTarget !== null ? NoToneMapping : this.toneMapping;
  17319. }
  17320. get currentColorSpace() {
  17321. return this._renderTarget !== null ? LinearSRGBColorSpace : this.outputColorSpace;
  17322. }
  17323. dispose() {
  17324. this.info.dispose();
  17325. this.backend.dispose();
  17326. this._animation.dispose();
  17327. this._objects.dispose();
  17328. this._pipelines.dispose();
  17329. this._nodes.dispose();
  17330. this._bindings.dispose();
  17331. this._renderLists.dispose();
  17332. this._renderContexts.dispose();
  17333. this._textures.dispose();
  17334. this.setRenderTarget( null );
  17335. this.setAnimationLoop( null );
  17336. }
  17337. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  17338. this._renderTarget = renderTarget;
  17339. this._activeCubeFace = activeCubeFace;
  17340. this._activeMipmapLevel = activeMipmapLevel;
  17341. }
  17342. getRenderTarget() {
  17343. return this._renderTarget;
  17344. }
  17345. setRenderObjectFunction( renderObjectFunction ) {
  17346. this._renderObjectFunction = renderObjectFunction;
  17347. }
  17348. getRenderObjectFunction() {
  17349. return this._renderObjectFunction;
  17350. }
  17351. compute( computeNodes ) {
  17352. if ( this.isDeviceLost === true ) return;
  17353. if ( this._initialized === false ) {
  17354. console.warn( 'THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  17355. return this.computeAsync( computeNodes );
  17356. }
  17357. //
  17358. const nodeFrame = this._nodes.nodeFrame;
  17359. const previousRenderId = nodeFrame.renderId;
  17360. //
  17361. this.info.calls ++;
  17362. this.info.compute.calls ++;
  17363. this.info.compute.frameCalls ++;
  17364. nodeFrame.renderId = this.info.calls;
  17365. //
  17366. const backend = this.backend;
  17367. const pipelines = this._pipelines;
  17368. const bindings = this._bindings;
  17369. const nodes = this._nodes;
  17370. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  17371. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  17372. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  17373. }
  17374. backend.beginCompute( computeNodes );
  17375. for ( const computeNode of computeList ) {
  17376. // onInit
  17377. if ( pipelines.has( computeNode ) === false ) {
  17378. const dispose = () => {
  17379. computeNode.removeEventListener( 'dispose', dispose );
  17380. pipelines.delete( computeNode );
  17381. bindings.delete( computeNode );
  17382. nodes.delete( computeNode );
  17383. };
  17384. computeNode.addEventListener( 'dispose', dispose );
  17385. //
  17386. const onInitFn = computeNode.onInitFunction;
  17387. if ( onInitFn !== null ) {
  17388. onInitFn.call( computeNode, { renderer: this } );
  17389. }
  17390. }
  17391. nodes.updateForCompute( computeNode );
  17392. bindings.updateForCompute( computeNode );
  17393. const computeBindings = bindings.getForCompute( computeNode );
  17394. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  17395. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  17396. }
  17397. backend.finishCompute( computeNodes );
  17398. //
  17399. nodeFrame.renderId = previousRenderId;
  17400. }
  17401. async computeAsync( computeNodes ) {
  17402. if ( this._initialized === false ) await this.init();
  17403. this.compute( computeNodes );
  17404. await this.backend.resolveTimestampAsync( computeNodes, 'compute' );
  17405. }
  17406. async hasFeatureAsync( name ) {
  17407. if ( this._initialized === false ) await this.init();
  17408. return this.backend.hasFeature( name );
  17409. }
  17410. hasFeature( name ) {
  17411. if ( this._initialized === false ) {
  17412. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  17413. return false;
  17414. }
  17415. return this.backend.hasFeature( name );
  17416. }
  17417. hasInitialized() {
  17418. return this._initialized;
  17419. }
  17420. async initTextureAsync( texture ) {
  17421. if ( this._initialized === false ) await this.init();
  17422. this._textures.updateTexture( texture );
  17423. }
  17424. initTexture( texture ) {
  17425. if ( this._initialized === false ) {
  17426. console.warn( 'THREE.Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead.' );
  17427. return false;
  17428. }
  17429. this._textures.updateTexture( texture );
  17430. }
  17431. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  17432. if ( rectangle !== null ) {
  17433. if ( rectangle.isVector2 ) {
  17434. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  17435. } else if ( rectangle.isVector4 ) {
  17436. rectangle = _vector4.copy( rectangle ).floor();
  17437. } else {
  17438. console.error( 'THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  17439. return;
  17440. }
  17441. } else {
  17442. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  17443. }
  17444. //
  17445. let renderContext = this._currentRenderContext;
  17446. let renderTarget;
  17447. if ( renderContext !== null ) {
  17448. renderTarget = renderContext.renderTarget;
  17449. } else {
  17450. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  17451. if ( renderTarget !== null ) {
  17452. this._textures.updateRenderTarget( renderTarget );
  17453. renderContext = this._textures.get( renderTarget );
  17454. }
  17455. }
  17456. //
  17457. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  17458. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  17459. }
  17460. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  17461. this._textures.updateTexture( srcTexture );
  17462. this._textures.updateTexture( dstTexture );
  17463. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  17464. }
  17465. readRenderTargetPixelsAsync( renderTarget, x, y, width, height, index = 0, faceIndex = 0 ) {
  17466. return this.backend.copyTextureToBuffer( renderTarget.textures[ index ], x, y, width, height, faceIndex );
  17467. }
  17468. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  17469. if ( object.visible === false ) return;
  17470. const visible = object.layers.test( camera.layers );
  17471. if ( visible ) {
  17472. if ( object.isGroup ) {
  17473. groupOrder = object.renderOrder;
  17474. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  17475. } else if ( object.isLOD ) {
  17476. if ( object.autoUpdate === true ) object.update( camera );
  17477. } else if ( object.isLight ) {
  17478. renderList.pushLight( object );
  17479. } else if ( object.isSprite ) {
  17480. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  17481. if ( this.sortObjects === true ) {
  17482. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  17483. }
  17484. const { geometry, material } = object;
  17485. if ( material.visible ) {
  17486. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  17487. }
  17488. }
  17489. } else if ( object.isLineLoop ) {
  17490. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  17491. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  17492. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  17493. const { geometry, material } = object;
  17494. if ( this.sortObjects === true ) {
  17495. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  17496. _vector4
  17497. .copy( geometry.boundingSphere.center )
  17498. .applyMatrix4( object.matrixWorld )
  17499. .applyMatrix4( _projScreenMatrix );
  17500. }
  17501. if ( Array.isArray( material ) ) {
  17502. const groups = geometry.groups;
  17503. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  17504. const group = groups[ i ];
  17505. const groupMaterial = material[ group.materialIndex ];
  17506. if ( groupMaterial && groupMaterial.visible ) {
  17507. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  17508. }
  17509. }
  17510. } else if ( material.visible ) {
  17511. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  17512. }
  17513. }
  17514. }
  17515. }
  17516. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  17517. const baseRenderList = renderList;
  17518. // replace render list
  17519. renderList = this._renderLists.get( object, camera );
  17520. renderList.begin();
  17521. baseRenderList.pushBundle( {
  17522. bundleGroup: object,
  17523. camera,
  17524. renderList,
  17525. } );
  17526. renderList.finish();
  17527. }
  17528. const children = object.children;
  17529. for ( let i = 0, l = children.length; i < l; i ++ ) {
  17530. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  17531. }
  17532. }
  17533. _renderBundles( bundles, sceneRef, lightsNode ) {
  17534. for ( const bundle of bundles ) {
  17535. this._renderBundle( bundle, sceneRef, lightsNode );
  17536. }
  17537. }
  17538. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  17539. if ( doublePassList.length > 0 ) {
  17540. // render back side
  17541. for ( const { material } of doublePassList ) {
  17542. material.side = BackSide;
  17543. }
  17544. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  17545. // render front side
  17546. for ( const { material } of doublePassList ) {
  17547. material.side = FrontSide;
  17548. }
  17549. this._renderObjects( renderList, camera, scene, lightsNode );
  17550. // restore
  17551. for ( const { material } of doublePassList ) {
  17552. material.side = DoubleSide;
  17553. }
  17554. } else {
  17555. this._renderObjects( renderList, camera, scene, lightsNode );
  17556. }
  17557. }
  17558. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  17559. // process renderable objects
  17560. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  17561. const renderItem = renderList[ i ];
  17562. // @TODO: Add support for multiple materials per object. This will require to extract
  17563. // the material from the renderItem object and pass it with its group data to renderObject().
  17564. const { object, geometry, material, group, clippingContext } = renderItem;
  17565. if ( camera.isArrayCamera ) {
  17566. const cameras = camera.cameras;
  17567. for ( let j = 0, jl = cameras.length; j < jl; j ++ ) {
  17568. const camera2 = cameras[ j ];
  17569. if ( object.layers.test( camera2.layers ) ) {
  17570. const vp = camera2.viewport;
  17571. const minDepth = ( vp.minDepth === undefined ) ? 0 : vp.minDepth;
  17572. const maxDepth = ( vp.maxDepth === undefined ) ? 1 : vp.maxDepth;
  17573. const viewportValue = this._currentRenderContext.viewportValue;
  17574. viewportValue.copy( vp ).multiplyScalar( this._pixelRatio ).floor();
  17575. viewportValue.minDepth = minDepth;
  17576. viewportValue.maxDepth = maxDepth;
  17577. this.backend.updateViewport( this._currentRenderContext );
  17578. this._currentRenderObjectFunction( object, scene, camera2, geometry, material, group, lightsNode, clippingContext, passId );
  17579. }
  17580. }
  17581. } else {
  17582. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  17583. }
  17584. }
  17585. }
  17586. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  17587. let overridePositionNode;
  17588. let overrideColorNode;
  17589. let overrideDepthNode;
  17590. //
  17591. object.onBeforeRender( this, scene, camera, geometry, material, group );
  17592. //
  17593. if ( scene.overrideMaterial !== null ) {
  17594. const overrideMaterial = scene.overrideMaterial;
  17595. if ( material.positionNode && material.positionNode.isNode ) {
  17596. overridePositionNode = overrideMaterial.positionNode;
  17597. overrideMaterial.positionNode = material.positionNode;
  17598. }
  17599. overrideMaterial.alphaTest = material.alphaTest;
  17600. overrideMaterial.alphaMap = material.alphaMap;
  17601. if ( overrideMaterial.isShadowNodeMaterial ) {
  17602. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  17603. if ( material.depthNode && material.depthNode.isNode ) {
  17604. overrideDepthNode = overrideMaterial.depthNode;
  17605. overrideMaterial.depthNode = material.depthNode;
  17606. }
  17607. if ( material.castShadowNode && material.castShadowNode.isNode ) {
  17608. overrideColorNode = overrideMaterial.colorNode;
  17609. overrideMaterial.colorNode = material.castShadowNode;
  17610. }
  17611. }
  17612. material = overrideMaterial;
  17613. }
  17614. //
  17615. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  17616. material.side = BackSide;
  17617. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  17618. material.side = FrontSide;
  17619. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  17620. material.side = DoubleSide;
  17621. } else {
  17622. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  17623. }
  17624. //
  17625. if ( overridePositionNode !== undefined ) {
  17626. scene.overrideMaterial.positionNode = overridePositionNode;
  17627. }
  17628. if ( overrideDepthNode !== undefined ) {
  17629. scene.overrideMaterial.depthNode = overrideDepthNode;
  17630. }
  17631. if ( overrideColorNode !== undefined ) {
  17632. scene.overrideMaterial.colorNode = overrideColorNode;
  17633. }
  17634. //
  17635. object.onAfterRender( this, scene, camera, geometry, material, group );
  17636. }
  17637. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  17638. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  17639. renderObject.drawRange = object.geometry.drawRange;
  17640. renderObject.group = group;
  17641. //
  17642. const needsRefresh = this._nodes.needsRefresh( renderObject );
  17643. if ( needsRefresh ) {
  17644. this._nodes.updateBefore( renderObject );
  17645. this._geometries.updateForRender( renderObject );
  17646. this._nodes.updateForRender( renderObject );
  17647. this._bindings.updateForRender( renderObject );
  17648. }
  17649. this._pipelines.updateForRender( renderObject );
  17650. //
  17651. if ( this._currentRenderBundle !== null ) {
  17652. const renderBundleData = this.backend.get( this._currentRenderBundle );
  17653. renderBundleData.renderObjects.push( renderObject );
  17654. renderObject.bundle = this._currentRenderBundle.scene;
  17655. }
  17656. this.backend.draw( renderObject, this.info );
  17657. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  17658. }
  17659. _createObjectPipeline( object, material, scene, camera, lightsNode, clippingContext, passId ) {
  17660. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  17661. //
  17662. this._nodes.updateBefore( renderObject );
  17663. this._geometries.updateForRender( renderObject );
  17664. this._nodes.updateForRender( renderObject );
  17665. this._bindings.updateForRender( renderObject );
  17666. this._pipelines.getForRender( renderObject, this._compilationPromises );
  17667. this._nodes.updateAfter( renderObject );
  17668. }
  17669. get compile() {
  17670. return this.compileAsync;
  17671. }
  17672. }
  17673. class Binding {
  17674. constructor( name = '' ) {
  17675. this.name = name;
  17676. this.visibility = 0;
  17677. }
  17678. setVisibility( visibility ) {
  17679. this.visibility |= visibility;
  17680. }
  17681. clone() {
  17682. return Object.assign( new this.constructor(), this );
  17683. }
  17684. }
  17685. function getFloatLength( floatLength ) {
  17686. // ensure chunk size alignment (STD140 layout)
  17687. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  17688. }
  17689. class Buffer extends Binding {
  17690. constructor( name, buffer = null ) {
  17691. super( name );
  17692. this.isBuffer = true;
  17693. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  17694. this._buffer = buffer;
  17695. }
  17696. get byteLength() {
  17697. return getFloatLength( this._buffer.byteLength );
  17698. }
  17699. get buffer() {
  17700. return this._buffer;
  17701. }
  17702. update() {
  17703. return true;
  17704. }
  17705. }
  17706. class UniformBuffer extends Buffer {
  17707. constructor( name, buffer = null ) {
  17708. super( name, buffer );
  17709. this.isUniformBuffer = true;
  17710. }
  17711. }
  17712. let _id$4 = 0;
  17713. class NodeUniformBuffer extends UniformBuffer {
  17714. constructor( nodeUniform, groupNode ) {
  17715. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  17716. this.nodeUniform = nodeUniform;
  17717. this.groupNode = groupNode;
  17718. }
  17719. get buffer() {
  17720. return this.nodeUniform.value;
  17721. }
  17722. }
  17723. class UniformsGroup extends UniformBuffer {
  17724. constructor( name ) {
  17725. super( name );
  17726. this.isUniformsGroup = true;
  17727. this._values = null;
  17728. // the order of uniforms in this array must match the order of uniforms in the shader
  17729. this.uniforms = [];
  17730. }
  17731. addUniform( uniform ) {
  17732. this.uniforms.push( uniform );
  17733. return this;
  17734. }
  17735. removeUniform( uniform ) {
  17736. const index = this.uniforms.indexOf( uniform );
  17737. if ( index !== - 1 ) {
  17738. this.uniforms.splice( index, 1 );
  17739. }
  17740. return this;
  17741. }
  17742. get values() {
  17743. if ( this._values === null ) {
  17744. this._values = Array.from( this.buffer );
  17745. }
  17746. return this._values;
  17747. }
  17748. get buffer() {
  17749. let buffer = this._buffer;
  17750. if ( buffer === null ) {
  17751. const byteLength = this.byteLength;
  17752. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  17753. this._buffer = buffer;
  17754. }
  17755. return buffer;
  17756. }
  17757. get byteLength() {
  17758. let offset = 0; // global buffer offset in bytes
  17759. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  17760. const uniform = this.uniforms[ i ];
  17761. const { boundary, itemSize } = uniform;
  17762. // offset within a single chunk in bytes
  17763. const chunkOffset = offset % GPU_CHUNK_BYTES;
  17764. const remainingSizeInChunk = GPU_CHUNK_BYTES - chunkOffset;
  17765. // conformance tests
  17766. if ( chunkOffset !== 0 && ( remainingSizeInChunk - boundary ) < 0 ) {
  17767. // check for chunk overflow
  17768. offset += ( GPU_CHUNK_BYTES - chunkOffset );
  17769. } else if ( chunkOffset % boundary !== 0 ) {
  17770. // check for correct alignment
  17771. offset += ( chunkOffset % boundary );
  17772. }
  17773. uniform.offset = ( offset / this.bytesPerElement );
  17774. offset += ( itemSize * this.bytesPerElement );
  17775. }
  17776. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  17777. }
  17778. update() {
  17779. let updated = false;
  17780. for ( const uniform of this.uniforms ) {
  17781. if ( this.updateByType( uniform ) === true ) {
  17782. updated = true;
  17783. }
  17784. }
  17785. return updated;
  17786. }
  17787. updateByType( uniform ) {
  17788. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  17789. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  17790. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  17791. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  17792. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  17793. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  17794. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  17795. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  17796. }
  17797. updateNumber( uniform ) {
  17798. let updated = false;
  17799. const a = this.values;
  17800. const v = uniform.getValue();
  17801. const offset = uniform.offset;
  17802. const type = uniform.getType();
  17803. if ( a[ offset ] !== v ) {
  17804. const b = this._getBufferForType( type );
  17805. b[ offset ] = a[ offset ] = v;
  17806. updated = true;
  17807. }
  17808. return updated;
  17809. }
  17810. updateVector2( uniform ) {
  17811. let updated = false;
  17812. const a = this.values;
  17813. const v = uniform.getValue();
  17814. const offset = uniform.offset;
  17815. const type = uniform.getType();
  17816. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  17817. const b = this._getBufferForType( type );
  17818. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  17819. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  17820. updated = true;
  17821. }
  17822. return updated;
  17823. }
  17824. updateVector3( uniform ) {
  17825. let updated = false;
  17826. const a = this.values;
  17827. const v = uniform.getValue();
  17828. const offset = uniform.offset;
  17829. const type = uniform.getType();
  17830. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  17831. const b = this._getBufferForType( type );
  17832. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  17833. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  17834. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  17835. updated = true;
  17836. }
  17837. return updated;
  17838. }
  17839. updateVector4( uniform ) {
  17840. let updated = false;
  17841. const a = this.values;
  17842. const v = uniform.getValue();
  17843. const offset = uniform.offset;
  17844. const type = uniform.getType();
  17845. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  17846. const b = this._getBufferForType( type );
  17847. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  17848. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  17849. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  17850. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  17851. updated = true;
  17852. }
  17853. return updated;
  17854. }
  17855. updateColor( uniform ) {
  17856. let updated = false;
  17857. const a = this.values;
  17858. const c = uniform.getValue();
  17859. const offset = uniform.offset;
  17860. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  17861. const b = this.buffer;
  17862. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  17863. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  17864. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  17865. updated = true;
  17866. }
  17867. return updated;
  17868. }
  17869. updateMatrix3( uniform ) {
  17870. let updated = false;
  17871. const a = this.values;
  17872. const e = uniform.getValue().elements;
  17873. const offset = uniform.offset;
  17874. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  17875. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  17876. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  17877. const b = this.buffer;
  17878. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  17879. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  17880. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  17881. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  17882. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  17883. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  17884. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  17885. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  17886. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  17887. updated = true;
  17888. }
  17889. return updated;
  17890. }
  17891. updateMatrix4( uniform ) {
  17892. let updated = false;
  17893. const a = this.values;
  17894. const e = uniform.getValue().elements;
  17895. const offset = uniform.offset;
  17896. if ( arraysEqual( a, e, offset ) === false ) {
  17897. const b = this.buffer;
  17898. b.set( e, offset );
  17899. setArray( a, e, offset );
  17900. updated = true;
  17901. }
  17902. return updated;
  17903. }
  17904. _getBufferForType( type ) {
  17905. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  17906. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  17907. return this.buffer;
  17908. }
  17909. }
  17910. function setArray( a, b, offset ) {
  17911. for ( let i = 0, l = b.length; i < l; i ++ ) {
  17912. a[ offset + i ] = b[ i ];
  17913. }
  17914. }
  17915. function arraysEqual( a, b, offset ) {
  17916. for ( let i = 0, l = b.length; i < l; i ++ ) {
  17917. if ( a[ offset + i ] !== b[ i ] ) return false;
  17918. }
  17919. return true;
  17920. }
  17921. let _id$3 = 0;
  17922. class NodeUniformsGroup extends UniformsGroup {
  17923. constructor( name, groupNode ) {
  17924. super( name );
  17925. this.id = _id$3 ++;
  17926. this.groupNode = groupNode;
  17927. this.isNodeUniformsGroup = true;
  17928. }
  17929. getNodes() {
  17930. const nodes = [];
  17931. for ( const uniform of this.uniforms ) {
  17932. const node = uniform.nodeUniform.node;
  17933. if ( ! node ) throw new Error( 'NodeUniformsGroup: Uniform has no node.' );
  17934. nodes.push( node );
  17935. }
  17936. return nodes;
  17937. }
  17938. }
  17939. let _id$2 = 0;
  17940. class SampledTexture extends Binding {
  17941. constructor( name, texture ) {
  17942. super( name );
  17943. this.id = _id$2 ++;
  17944. this.texture = texture;
  17945. this.version = texture ? texture.version : 0;
  17946. this.store = false;
  17947. this.generation = null;
  17948. this.isSampledTexture = true;
  17949. }
  17950. needsBindingsUpdate( generation ) {
  17951. const { texture } = this;
  17952. if ( generation !== this.generation ) {
  17953. this.generation = generation;
  17954. return true;
  17955. }
  17956. return texture.isVideoTexture;
  17957. }
  17958. update() {
  17959. const { texture, version } = this;
  17960. if ( version !== texture.version ) {
  17961. this.version = texture.version;
  17962. return true;
  17963. }
  17964. return false;
  17965. }
  17966. }
  17967. class NodeSampledTexture extends SampledTexture {
  17968. constructor( name, textureNode, groupNode, access = null ) {
  17969. super( name, textureNode ? textureNode.value : null );
  17970. this.textureNode = textureNode;
  17971. this.groupNode = groupNode;
  17972. this.access = access;
  17973. }
  17974. needsBindingsUpdate( generation ) {
  17975. return this.textureNode.value !== this.texture || super.needsBindingsUpdate( generation );
  17976. }
  17977. update() {
  17978. const { textureNode } = this;
  17979. if ( this.texture !== textureNode.value ) {
  17980. this.texture = textureNode.value;
  17981. return true;
  17982. }
  17983. return super.update();
  17984. }
  17985. }
  17986. class NodeSampledCubeTexture extends NodeSampledTexture {
  17987. constructor( name, textureNode, groupNode, access ) {
  17988. super( name, textureNode, groupNode, access );
  17989. this.isSampledCubeTexture = true;
  17990. }
  17991. }
  17992. class NodeSampledTexture3D extends NodeSampledTexture {
  17993. constructor( name, textureNode, groupNode, access ) {
  17994. super( name, textureNode, groupNode, access );
  17995. this.isSampledTexture3D = true;
  17996. }
  17997. }
  17998. const glslMethods = {
  17999. atan2: 'atan',
  18000. textureDimensions: 'textureSize',
  18001. equals: 'equal'
  18002. };
  18003. const precisionLib = {
  18004. low: 'lowp',
  18005. medium: 'mediump',
  18006. high: 'highp'
  18007. };
  18008. const supports$1 = {
  18009. swizzleAssign: true,
  18010. storageBuffer: false
  18011. };
  18012. const defaultPrecisions = `
  18013. precision highp float;
  18014. precision highp int;
  18015. precision highp sampler2D;
  18016. precision highp sampler3D;
  18017. precision highp samplerCube;
  18018. precision highp sampler2DArray;
  18019. precision highp usampler2D;
  18020. precision highp usampler3D;
  18021. precision highp usamplerCube;
  18022. precision highp usampler2DArray;
  18023. precision highp isampler2D;
  18024. precision highp isampler3D;
  18025. precision highp isamplerCube;
  18026. precision highp isampler2DArray;
  18027. precision lowp sampler2DShadow;
  18028. `;
  18029. class GLSLNodeBuilder extends NodeBuilder {
  18030. constructor( object, renderer ) {
  18031. super( object, renderer, new GLSLNodeParser() );
  18032. this.uniformGroups = {};
  18033. this.transforms = [];
  18034. this.extensions = {};
  18035. this.builtins = { vertex: [], fragment: [], compute: [] };
  18036. this.useComparisonMethod = true;
  18037. }
  18038. needsToWorkingColorSpace( texture ) {
  18039. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  18040. }
  18041. getMethod( method ) {
  18042. return glslMethods[ method ] || method;
  18043. }
  18044. getOutputStructName() {
  18045. return '';
  18046. }
  18047. buildFunctionCode( shaderNode ) {
  18048. const layout = shaderNode.layout;
  18049. const flowData = this.flowShaderNode( shaderNode );
  18050. const parameters = [];
  18051. for ( const input of layout.inputs ) {
  18052. parameters.push( this.getType( input.type ) + ' ' + input.name );
  18053. }
  18054. //
  18055. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  18056. ${ flowData.vars }
  18057. ${ flowData.code }
  18058. return ${ flowData.result };
  18059. }`;
  18060. //
  18061. return code;
  18062. }
  18063. setupPBO( storageBufferNode ) {
  18064. const attribute = storageBufferNode.value;
  18065. if ( attribute.pbo === undefined ) {
  18066. const originalArray = attribute.array;
  18067. const numElements = attribute.count * attribute.itemSize;
  18068. const { itemSize } = attribute;
  18069. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  18070. let format = isInteger ? RedIntegerFormat : RedFormat;
  18071. if ( itemSize === 2 ) {
  18072. format = isInteger ? RGIntegerFormat : RGFormat;
  18073. } else if ( itemSize === 3 ) {
  18074. format = isInteger ? RGBIntegerFormat : RGBFormat;
  18075. } else if ( itemSize === 4 ) {
  18076. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  18077. }
  18078. const typeMap = {
  18079. Float32Array: FloatType,
  18080. Uint8Array: UnsignedByteType,
  18081. Uint16Array: UnsignedShortType,
  18082. Uint32Array: UnsignedIntType,
  18083. Int8Array: ByteType,
  18084. Int16Array: ShortType,
  18085. Int32Array: IntType,
  18086. Uint8ClampedArray: UnsignedByteType,
  18087. };
  18088. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  18089. let height = Math.ceil( ( numElements / itemSize ) / width );
  18090. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  18091. const newSize = width * height * itemSize;
  18092. const newArray = new originalArray.constructor( newSize );
  18093. newArray.set( originalArray, 0 );
  18094. attribute.array = newArray;
  18095. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  18096. pboTexture.needsUpdate = true;
  18097. pboTexture.isPBOTexture = true;
  18098. const pbo = new TextureNode( pboTexture, null, null );
  18099. pbo.setPrecision( 'high' );
  18100. attribute.pboNode = pbo;
  18101. attribute.pbo = pbo.value;
  18102. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  18103. }
  18104. }
  18105. getPropertyName( node, shaderStage = this.shaderStage ) {
  18106. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  18107. return shaderStage.charAt( 0 ) + '_' + node.name;
  18108. }
  18109. return super.getPropertyName( node, shaderStage );
  18110. }
  18111. generatePBO( storageArrayElementNode ) {
  18112. const { node, indexNode } = storageArrayElementNode;
  18113. const attribute = node.value;
  18114. if ( this.renderer.backend.has( attribute ) ) {
  18115. const attributeData = this.renderer.backend.get( attribute );
  18116. attributeData.pbo = attribute.pbo;
  18117. }
  18118. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  18119. const textureName = this.getPropertyName( nodeUniform );
  18120. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  18121. const indexSnippet = indexNode.build( this, 'uint' );
  18122. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  18123. let propertyName = elementNodeData.propertyName;
  18124. if ( propertyName === undefined ) {
  18125. // property element
  18126. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  18127. propertyName = this.getPropertyName( nodeVar );
  18128. // property size
  18129. const bufferNodeData = this.getDataFromNode( node );
  18130. let propertySizeName = bufferNodeData.propertySizeName;
  18131. if ( propertySizeName === undefined ) {
  18132. propertySizeName = propertyName + 'Size';
  18133. this.getVarFromNode( node, propertySizeName, 'uint' );
  18134. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  18135. bufferNodeData.propertySizeName = propertySizeName;
  18136. }
  18137. //
  18138. const { itemSize } = attribute;
  18139. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  18140. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  18141. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  18142. //
  18143. let prefix = 'vec4';
  18144. if ( attribute.pbo.type === UnsignedIntType ) {
  18145. prefix = 'uvec4';
  18146. } else if ( attribute.pbo.type === IntType ) {
  18147. prefix = 'ivec4';
  18148. }
  18149. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  18150. elementNodeData.propertyName = propertyName;
  18151. }
  18152. return propertyName;
  18153. }
  18154. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  18155. if ( depthSnippet ) {
  18156. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  18157. } else {
  18158. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  18159. }
  18160. }
  18161. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  18162. if ( texture.isDepthTexture ) {
  18163. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  18164. } else {
  18165. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  18166. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  18167. }
  18168. }
  18169. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  18170. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  18171. }
  18172. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
  18173. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  18174. }
  18175. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  18176. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  18177. }
  18178. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  18179. if ( shaderStage === 'fragment' ) {
  18180. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  18181. } else {
  18182. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  18183. }
  18184. }
  18185. getVars( shaderStage ) {
  18186. const snippets = [];
  18187. const vars = this.vars[ shaderStage ];
  18188. if ( vars !== undefined ) {
  18189. for ( const variable of vars ) {
  18190. snippets.push( `${ this.getVar( variable.type, variable.name ) };` );
  18191. }
  18192. }
  18193. return snippets.join( '\n\t' );
  18194. }
  18195. getUniforms( shaderStage ) {
  18196. const uniforms = this.uniforms[ shaderStage ];
  18197. const bindingSnippets = [];
  18198. const uniformGroups = {};
  18199. for ( const uniform of uniforms ) {
  18200. let snippet = null;
  18201. let group = false;
  18202. if ( uniform.type === 'texture' ) {
  18203. const texture = uniform.node.value;
  18204. let typePrefix = '';
  18205. if ( texture.isDataTexture === true ) {
  18206. if ( texture.type === UnsignedIntType ) {
  18207. typePrefix = 'u';
  18208. } else if ( texture.type === IntType ) {
  18209. typePrefix = 'i';
  18210. }
  18211. }
  18212. if ( texture.compareFunction ) {
  18213. snippet = `sampler2DShadow ${ uniform.name };`;
  18214. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  18215. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  18216. } else {
  18217. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  18218. }
  18219. } else if ( uniform.type === 'cubeTexture' ) {
  18220. snippet = `samplerCube ${ uniform.name };`;
  18221. } else if ( uniform.type === 'texture3D' ) {
  18222. snippet = `sampler3D ${ uniform.name };`;
  18223. } else if ( uniform.type === 'buffer' ) {
  18224. const bufferNode = uniform.node;
  18225. const bufferType = this.getType( bufferNode.bufferType );
  18226. const bufferCount = bufferNode.bufferCount;
  18227. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  18228. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  18229. } else {
  18230. const vectorType = this.getVectorType( uniform.type );
  18231. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  18232. group = true;
  18233. }
  18234. const precision = uniform.node.precision;
  18235. if ( precision !== null ) {
  18236. snippet = precisionLib[ precision ] + ' ' + snippet;
  18237. }
  18238. if ( group ) {
  18239. snippet = '\t' + snippet;
  18240. const groupName = uniform.groupNode.name;
  18241. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  18242. groupSnippets.push( snippet );
  18243. } else {
  18244. snippet = 'uniform ' + snippet;
  18245. bindingSnippets.push( snippet );
  18246. }
  18247. }
  18248. let output = '';
  18249. for ( const name in uniformGroups ) {
  18250. const groupSnippets = uniformGroups[ name ];
  18251. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  18252. }
  18253. output += bindingSnippets.join( '\n' );
  18254. return output;
  18255. }
  18256. getTypeFromAttribute( attribute ) {
  18257. let nodeType = super.getTypeFromAttribute( attribute );
  18258. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  18259. let dataAttribute = attribute;
  18260. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  18261. const array = dataAttribute.array;
  18262. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  18263. nodeType = nodeType.slice( 1 );
  18264. }
  18265. }
  18266. return nodeType;
  18267. }
  18268. getAttributes( shaderStage ) {
  18269. let snippet = '';
  18270. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  18271. const attributes = this.getAttributesArray();
  18272. let location = 0;
  18273. for ( const attribute of attributes ) {
  18274. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  18275. }
  18276. }
  18277. return snippet;
  18278. }
  18279. getStructMembers( struct ) {
  18280. const snippets = [];
  18281. const members = struct.getMemberTypes();
  18282. for ( let i = 0; i < members.length; i ++ ) {
  18283. const member = members[ i ];
  18284. snippets.push( `layout( location = ${i} ) out ${ member} m${i};` );
  18285. }
  18286. return snippets.join( '\n' );
  18287. }
  18288. getStructs( shaderStage ) {
  18289. const snippets = [];
  18290. const structs = this.structs[ shaderStage ];
  18291. if ( structs.length === 0 ) {
  18292. return 'layout( location = 0 ) out vec4 fragColor;\n';
  18293. }
  18294. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  18295. const struct = structs[ index ];
  18296. let snippet = '\n';
  18297. snippet += this.getStructMembers( struct );
  18298. snippet += '\n';
  18299. snippets.push( snippet );
  18300. }
  18301. return snippets.join( '\n\n' );
  18302. }
  18303. getVaryings( shaderStage ) {
  18304. let snippet = '';
  18305. const varyings = this.varyings;
  18306. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  18307. for ( const varying of varyings ) {
  18308. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  18309. const type = this.getType( varying.type );
  18310. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  18311. snippet += `${flat}${varying.needsInterpolation ? 'out' : '/*out*/'} ${type} ${varying.name};\n`;
  18312. }
  18313. } else if ( shaderStage === 'fragment' ) {
  18314. for ( const varying of varyings ) {
  18315. if ( varying.needsInterpolation ) {
  18316. const type = this.getType( varying.type );
  18317. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  18318. snippet += `${flat}in ${type} ${varying.name};\n`;
  18319. }
  18320. }
  18321. }
  18322. for ( const builtin of this.builtins[ shaderStage ] ) {
  18323. snippet += `${builtin};\n`;
  18324. }
  18325. return snippet;
  18326. }
  18327. getVertexIndex() {
  18328. return 'uint( gl_VertexID )';
  18329. }
  18330. getInstanceIndex() {
  18331. return 'uint( gl_InstanceID )';
  18332. }
  18333. getInvocationLocalIndex() {
  18334. const workgroupSize = this.object.workgroupSize;
  18335. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  18336. return `uint( gl_InstanceID ) % ${size}u`;
  18337. }
  18338. getDrawIndex() {
  18339. const extensions = this.renderer.backend.extensions;
  18340. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  18341. return 'uint( gl_DrawID )';
  18342. }
  18343. return null;
  18344. }
  18345. getFrontFacing() {
  18346. return 'gl_FrontFacing';
  18347. }
  18348. getFragCoord() {
  18349. return 'gl_FragCoord.xy';
  18350. }
  18351. getFragDepth() {
  18352. return 'gl_FragDepth';
  18353. }
  18354. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  18355. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  18356. if ( map.has( name ) === false ) {
  18357. map.set( name, {
  18358. name,
  18359. behavior
  18360. } );
  18361. }
  18362. }
  18363. getExtensions( shaderStage ) {
  18364. const snippets = [];
  18365. if ( shaderStage === 'vertex' ) {
  18366. const ext = this.renderer.backend.extensions;
  18367. const isBatchedMesh = this.object.isBatchedMesh;
  18368. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  18369. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  18370. }
  18371. }
  18372. const extensions = this.extensions[ shaderStage ];
  18373. if ( extensions !== undefined ) {
  18374. for ( const { name, behavior } of extensions.values() ) {
  18375. snippets.push( `#extension ${name} : ${behavior}` );
  18376. }
  18377. }
  18378. return snippets.join( '\n' );
  18379. }
  18380. getClipDistance() {
  18381. return 'gl_ClipDistance';
  18382. }
  18383. isAvailable( name ) {
  18384. let result = supports$1[ name ];
  18385. if ( result === undefined ) {
  18386. let extensionName;
  18387. result = false;
  18388. switch ( name ) {
  18389. case 'float32Filterable':
  18390. extensionName = 'OES_texture_float_linear';
  18391. break;
  18392. case 'clipDistance':
  18393. extensionName = 'WEBGL_clip_cull_distance';
  18394. break;
  18395. }
  18396. if ( extensionName !== undefined ) {
  18397. const extensions = this.renderer.backend.extensions;
  18398. if ( extensions.has( extensionName ) ) {
  18399. extensions.get( extensionName );
  18400. result = true;
  18401. }
  18402. }
  18403. supports$1[ name ] = result;
  18404. }
  18405. return result;
  18406. }
  18407. isFlipY() {
  18408. return true;
  18409. }
  18410. enableHardwareClipping( planeCount ) {
  18411. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  18412. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  18413. }
  18414. registerTransform( varyingName, attributeNode ) {
  18415. this.transforms.push( { varyingName, attributeNode } );
  18416. }
  18417. getTransforms( /* shaderStage */ ) {
  18418. const transforms = this.transforms;
  18419. let snippet = '';
  18420. for ( let i = 0; i < transforms.length; i ++ ) {
  18421. const transform = transforms[ i ];
  18422. const attributeName = this.getPropertyName( transform.attributeNode );
  18423. snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  18424. }
  18425. return snippet;
  18426. }
  18427. _getGLSLUniformStruct( name, vars ) {
  18428. return `
  18429. layout( std140 ) uniform ${name} {
  18430. ${vars}
  18431. };`;
  18432. }
  18433. _getGLSLVertexCode( shaderData ) {
  18434. return `#version 300 es
  18435. ${ this.getSignature() }
  18436. // extensions
  18437. ${shaderData.extensions}
  18438. // precision
  18439. ${ defaultPrecisions }
  18440. // uniforms
  18441. ${shaderData.uniforms}
  18442. // varyings
  18443. ${shaderData.varyings}
  18444. // attributes
  18445. ${shaderData.attributes}
  18446. // codes
  18447. ${shaderData.codes}
  18448. void main() {
  18449. // vars
  18450. ${shaderData.vars}
  18451. // transforms
  18452. ${shaderData.transforms}
  18453. // flow
  18454. ${shaderData.flow}
  18455. gl_PointSize = 1.0;
  18456. }
  18457. `;
  18458. }
  18459. _getGLSLFragmentCode( shaderData ) {
  18460. return `#version 300 es
  18461. ${ this.getSignature() }
  18462. // precision
  18463. ${ defaultPrecisions }
  18464. // uniforms
  18465. ${shaderData.uniforms}
  18466. // varyings
  18467. ${shaderData.varyings}
  18468. // codes
  18469. ${shaderData.codes}
  18470. ${shaderData.structs}
  18471. void main() {
  18472. // vars
  18473. ${shaderData.vars}
  18474. // flow
  18475. ${shaderData.flow}
  18476. }
  18477. `;
  18478. }
  18479. buildCode() {
  18480. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  18481. this.sortBindingGroups();
  18482. for ( const shaderStage in shadersData ) {
  18483. let flow = '// code\n\n';
  18484. flow += this.flowCode[ shaderStage ];
  18485. const flowNodes = this.flowNodes[ shaderStage ];
  18486. const mainNode = flowNodes[ flowNodes.length - 1 ];
  18487. for ( const node of flowNodes ) {
  18488. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  18489. const slotName = node.name;
  18490. if ( slotName ) {
  18491. if ( flow.length > 0 ) flow += '\n';
  18492. flow += `\t// flow -> ${ slotName }\n\t`;
  18493. }
  18494. flow += `${ flowSlotData.code }\n\t`;
  18495. if ( node === mainNode && shaderStage !== 'compute' ) {
  18496. flow += '// result\n\t';
  18497. if ( shaderStage === 'vertex' ) {
  18498. flow += 'gl_Position = ';
  18499. flow += `${ flowSlotData.result };`;
  18500. } else if ( shaderStage === 'fragment' ) {
  18501. if ( ! node.outputNode.isOutputStructNode ) {
  18502. flow += 'fragColor = ';
  18503. flow += `${ flowSlotData.result };`;
  18504. }
  18505. }
  18506. }
  18507. }
  18508. const stageData = shadersData[ shaderStage ];
  18509. stageData.extensions = this.getExtensions( shaderStage );
  18510. stageData.uniforms = this.getUniforms( shaderStage );
  18511. stageData.attributes = this.getAttributes( shaderStage );
  18512. stageData.varyings = this.getVaryings( shaderStage );
  18513. stageData.vars = this.getVars( shaderStage );
  18514. stageData.structs = this.getStructs( shaderStage );
  18515. stageData.codes = this.getCodes( shaderStage );
  18516. stageData.transforms = this.getTransforms( shaderStage );
  18517. stageData.flow = flow;
  18518. }
  18519. if ( this.material !== null ) {
  18520. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  18521. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  18522. } else {
  18523. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  18524. }
  18525. }
  18526. getUniformFromNode( node, type, shaderStage, name = null ) {
  18527. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  18528. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  18529. let uniformGPU = nodeData.uniformGPU;
  18530. if ( uniformGPU === undefined ) {
  18531. const group = node.groupNode;
  18532. const groupName = group.name;
  18533. const bindings = this.getBindGroupArray( groupName, shaderStage );
  18534. if ( type === 'texture' ) {
  18535. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  18536. bindings.push( uniformGPU );
  18537. } else if ( type === 'cubeTexture' ) {
  18538. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  18539. bindings.push( uniformGPU );
  18540. } else if ( type === 'texture3D' ) {
  18541. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  18542. bindings.push( uniformGPU );
  18543. } else if ( type === 'buffer' ) {
  18544. node.name = `NodeBuffer_${ node.id }`;
  18545. uniformNode.name = `buffer${ node.id }`;
  18546. const buffer = new NodeUniformBuffer( node, group );
  18547. buffer.name = node.name;
  18548. bindings.push( buffer );
  18549. uniformGPU = buffer;
  18550. } else {
  18551. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  18552. let uniformsGroup = uniformsStage[ groupName ];
  18553. if ( uniformsGroup === undefined ) {
  18554. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  18555. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  18556. uniformsStage[ groupName ] = uniformsGroup;
  18557. bindings.push( uniformsGroup );
  18558. }
  18559. uniformGPU = this.getNodeUniform( uniformNode, type );
  18560. uniformsGroup.addUniform( uniformGPU );
  18561. }
  18562. nodeData.uniformGPU = uniformGPU;
  18563. }
  18564. return uniformNode;
  18565. }
  18566. }
  18567. let vector2 = null;
  18568. let vector4 = null;
  18569. let color4 = null;
  18570. class Backend {
  18571. constructor( parameters = {} ) {
  18572. this.parameters = Object.assign( {}, parameters );
  18573. this.data = new WeakMap();
  18574. this.renderer = null;
  18575. this.domElement = null;
  18576. }
  18577. async init( renderer ) {
  18578. this.renderer = renderer;
  18579. }
  18580. // render context
  18581. begin( /*renderContext*/ ) { }
  18582. finish( /*renderContext*/ ) { }
  18583. // render object
  18584. draw( /*renderObject, info*/ ) { }
  18585. // program
  18586. createProgram( /*program*/ ) { }
  18587. destroyProgram( /*program*/ ) { }
  18588. // bindings
  18589. createBindings( /*bingGroup, bindings*/ ) { }
  18590. updateBindings( /*bingGroup, bindings*/ ) { }
  18591. // pipeline
  18592. createRenderPipeline( /*renderObject*/ ) { }
  18593. createComputePipeline( /*computeNode, pipeline*/ ) { }
  18594. destroyPipeline( /*pipeline*/ ) { }
  18595. // cache key
  18596. needsRenderUpdate( /*renderObject*/ ) { } // return Boolean ( fast test )
  18597. getRenderCacheKey( /*renderObject*/ ) { } // return String
  18598. // node builder
  18599. createNodeBuilder( /*renderObject*/ ) { } // return NodeBuilder (ADD IT)
  18600. // textures
  18601. createSampler( /*texture*/ ) { }
  18602. createDefaultTexture( /*texture*/ ) { }
  18603. createTexture( /*texture*/ ) { }
  18604. copyTextureToBuffer( /*texture, x, y, width, height*/ ) {}
  18605. // attributes
  18606. createAttribute( /*attribute*/ ) { }
  18607. createIndexAttribute( /*attribute*/ ) { }
  18608. updateAttribute( /*attribute*/ ) { }
  18609. destroyAttribute( /*attribute*/ ) { }
  18610. // canvas
  18611. getContext() { }
  18612. updateSize() { }
  18613. // utils
  18614. resolveTimestampAsync( /*renderContext, type*/ ) { }
  18615. hasFeatureAsync( /*name*/ ) { } // return Boolean
  18616. hasFeature( /*name*/ ) { } // return Boolean
  18617. getInstanceCount( renderObject ) {
  18618. const { object, geometry } = renderObject;
  18619. return geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  18620. }
  18621. getDrawingBufferSize() {
  18622. vector2 = vector2 || new Vector2();
  18623. return this.renderer.getDrawingBufferSize( vector2 );
  18624. }
  18625. getScissor() {
  18626. vector4 = vector4 || new Vector4();
  18627. return this.renderer.getScissor( vector4 );
  18628. }
  18629. setScissorTest( /*boolean*/ ) { }
  18630. getClearColor() {
  18631. const renderer = this.renderer;
  18632. color4 = color4 || new Color4();
  18633. renderer.getClearColor( color4 );
  18634. color4.getRGB( color4, this.renderer.currentColorSpace );
  18635. return color4;
  18636. }
  18637. getDomElement() {
  18638. let domElement = this.domElement;
  18639. if ( domElement === null ) {
  18640. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  18641. // OffscreenCanvas does not have setAttribute, see #22811
  18642. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  18643. this.domElement = domElement;
  18644. }
  18645. return domElement;
  18646. }
  18647. // resource properties
  18648. set( object, value ) {
  18649. this.data.set( object, value );
  18650. }
  18651. get( object ) {
  18652. let map = this.data.get( object );
  18653. if ( map === undefined ) {
  18654. map = {};
  18655. this.data.set( object, map );
  18656. }
  18657. return map;
  18658. }
  18659. has( object ) {
  18660. return this.data.has( object );
  18661. }
  18662. delete( object ) {
  18663. this.data.delete( object );
  18664. }
  18665. dispose() { }
  18666. }
  18667. let _id$1 = 0;
  18668. class DualAttributeData {
  18669. constructor( attributeData, dualBuffer ) {
  18670. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  18671. this.type = attributeData.type;
  18672. this.bufferType = attributeData.bufferType;
  18673. this.pbo = attributeData.pbo;
  18674. this.byteLength = attributeData.byteLength;
  18675. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  18676. this.version = attributeData.version;
  18677. this.isInteger = attributeData.isInteger;
  18678. this.activeBufferIndex = 0;
  18679. this.baseId = attributeData.id;
  18680. }
  18681. get id() {
  18682. return `${ this.baseId }|${ this.activeBufferIndex }`;
  18683. }
  18684. get bufferGPU() {
  18685. return this.buffers[ this.activeBufferIndex ];
  18686. }
  18687. get transformBuffer() {
  18688. return this.buffers[ this.activeBufferIndex ^ 1 ];
  18689. }
  18690. switchBuffers() {
  18691. this.activeBufferIndex ^= 1;
  18692. }
  18693. }
  18694. class WebGLAttributeUtils {
  18695. constructor( backend ) {
  18696. this.backend = backend;
  18697. }
  18698. createAttribute( attribute, bufferType ) {
  18699. const backend = this.backend;
  18700. const { gl } = backend;
  18701. const array = attribute.array;
  18702. const usage = attribute.usage || gl.STATIC_DRAW;
  18703. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  18704. const bufferData = backend.get( bufferAttribute );
  18705. let bufferGPU = bufferData.bufferGPU;
  18706. if ( bufferGPU === undefined ) {
  18707. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  18708. bufferData.bufferGPU = bufferGPU;
  18709. bufferData.bufferType = bufferType;
  18710. bufferData.version = bufferAttribute.version;
  18711. }
  18712. //attribute.onUploadCallback();
  18713. let type;
  18714. if ( array instanceof Float32Array ) {
  18715. type = gl.FLOAT;
  18716. } else if ( array instanceof Uint16Array ) {
  18717. if ( attribute.isFloat16BufferAttribute ) {
  18718. type = gl.HALF_FLOAT;
  18719. } else {
  18720. type = gl.UNSIGNED_SHORT;
  18721. }
  18722. } else if ( array instanceof Int16Array ) {
  18723. type = gl.SHORT;
  18724. } else if ( array instanceof Uint32Array ) {
  18725. type = gl.UNSIGNED_INT;
  18726. } else if ( array instanceof Int32Array ) {
  18727. type = gl.INT;
  18728. } else if ( array instanceof Int8Array ) {
  18729. type = gl.BYTE;
  18730. } else if ( array instanceof Uint8Array ) {
  18731. type = gl.UNSIGNED_BYTE;
  18732. } else if ( array instanceof Uint8ClampedArray ) {
  18733. type = gl.UNSIGNED_BYTE;
  18734. } else {
  18735. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  18736. }
  18737. let attributeData = {
  18738. bufferGPU,
  18739. bufferType,
  18740. type,
  18741. byteLength: array.byteLength,
  18742. bytesPerElement: array.BYTES_PER_ELEMENT,
  18743. version: attribute.version,
  18744. pbo: attribute.pbo,
  18745. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  18746. id: _id$1 ++
  18747. };
  18748. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  18749. // create buffer for tranform feedback use
  18750. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  18751. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  18752. }
  18753. backend.set( attribute, attributeData );
  18754. }
  18755. updateAttribute( attribute ) {
  18756. const backend = this.backend;
  18757. const { gl } = backend;
  18758. const array = attribute.array;
  18759. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  18760. const bufferData = backend.get( bufferAttribute );
  18761. const bufferType = bufferData.bufferType;
  18762. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  18763. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  18764. if ( updateRanges.length === 0 ) {
  18765. // Not using update ranges
  18766. gl.bufferSubData( bufferType, 0, array );
  18767. } else {
  18768. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  18769. const range = updateRanges[ i ];
  18770. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  18771. array, range.start, range.count );
  18772. }
  18773. bufferAttribute.clearUpdateRanges();
  18774. }
  18775. gl.bindBuffer( bufferType, null );
  18776. bufferData.version = bufferAttribute.version;
  18777. }
  18778. destroyAttribute( attribute ) {
  18779. const backend = this.backend;
  18780. const { gl } = backend;
  18781. if ( attribute.isInterleavedBufferAttribute ) {
  18782. backend.delete( attribute.data );
  18783. }
  18784. const attributeData = backend.get( attribute );
  18785. gl.deleteBuffer( attributeData.bufferGPU );
  18786. backend.delete( attribute );
  18787. }
  18788. async getArrayBufferAsync( attribute ) {
  18789. const backend = this.backend;
  18790. const { gl } = backend;
  18791. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  18792. const { bufferGPU } = backend.get( bufferAttribute );
  18793. const array = attribute.array;
  18794. const byteLength = array.byteLength;
  18795. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  18796. const writeBuffer = gl.createBuffer();
  18797. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  18798. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  18799. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  18800. await backend.utils._clientWaitAsync();
  18801. const dstBuffer = new attribute.array.constructor( array.length );
  18802. // Ensure the buffer is bound before reading
  18803. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  18804. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  18805. gl.deleteBuffer( writeBuffer );
  18806. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  18807. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  18808. return dstBuffer.buffer;
  18809. }
  18810. _createBuffer( gl, bufferType, array, usage ) {
  18811. const bufferGPU = gl.createBuffer();
  18812. gl.bindBuffer( bufferType, bufferGPU );
  18813. gl.bufferData( bufferType, array, usage );
  18814. gl.bindBuffer( bufferType, null );
  18815. return bufferGPU;
  18816. }
  18817. }
  18818. let initialized$1 = false, equationToGL, factorToGL;
  18819. class WebGLState {
  18820. constructor( backend ) {
  18821. this.backend = backend;
  18822. this.gl = this.backend.gl;
  18823. this.enabled = {};
  18824. this.currentFlipSided = null;
  18825. this.currentCullFace = null;
  18826. this.currentProgram = null;
  18827. this.currentBlendingEnabled = false;
  18828. this.currentBlending = null;
  18829. this.currentBlendSrc = null;
  18830. this.currentBlendDst = null;
  18831. this.currentBlendSrcAlpha = null;
  18832. this.currentBlendDstAlpha = null;
  18833. this.currentPremultipledAlpha = null;
  18834. this.currentPolygonOffsetFactor = null;
  18835. this.currentPolygonOffsetUnits = null;
  18836. this.currentColorMask = null;
  18837. this.currentDepthFunc = null;
  18838. this.currentDepthMask = null;
  18839. this.currentStencilFunc = null;
  18840. this.currentStencilRef = null;
  18841. this.currentStencilFuncMask = null;
  18842. this.currentStencilFail = null;
  18843. this.currentStencilZFail = null;
  18844. this.currentStencilZPass = null;
  18845. this.currentStencilMask = null;
  18846. this.currentLineWidth = null;
  18847. this.currentClippingPlanes = 0;
  18848. this.currentBoundFramebuffers = {};
  18849. this.currentDrawbuffers = new WeakMap();
  18850. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  18851. this.currentTextureSlot = null;
  18852. this.currentBoundTextures = {};
  18853. this.currentBoundBufferBases = {};
  18854. if ( initialized$1 === false ) {
  18855. this._init( this.gl );
  18856. initialized$1 = true;
  18857. }
  18858. }
  18859. _init( gl ) {
  18860. // Store only WebGL constants here.
  18861. equationToGL = {
  18862. [ AddEquation ]: gl.FUNC_ADD,
  18863. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  18864. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  18865. };
  18866. factorToGL = {
  18867. [ ZeroFactor ]: gl.ZERO,
  18868. [ OneFactor ]: gl.ONE,
  18869. [ SrcColorFactor ]: gl.SRC_COLOR,
  18870. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  18871. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  18872. [ DstColorFactor ]: gl.DST_COLOR,
  18873. [ DstAlphaFactor ]: gl.DST_ALPHA,
  18874. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  18875. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  18876. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  18877. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  18878. };
  18879. }
  18880. enable( id ) {
  18881. const { enabled } = this;
  18882. if ( enabled[ id ] !== true ) {
  18883. this.gl.enable( id );
  18884. enabled[ id ] = true;
  18885. }
  18886. }
  18887. disable( id ) {
  18888. const { enabled } = this;
  18889. if ( enabled[ id ] !== false ) {
  18890. this.gl.disable( id );
  18891. enabled[ id ] = false;
  18892. }
  18893. }
  18894. setFlipSided( flipSided ) {
  18895. if ( this.currentFlipSided !== flipSided ) {
  18896. const { gl } = this;
  18897. if ( flipSided ) {
  18898. gl.frontFace( gl.CW );
  18899. } else {
  18900. gl.frontFace( gl.CCW );
  18901. }
  18902. this.currentFlipSided = flipSided;
  18903. }
  18904. }
  18905. setCullFace( cullFace ) {
  18906. const { gl } = this;
  18907. if ( cullFace !== CullFaceNone ) {
  18908. this.enable( gl.CULL_FACE );
  18909. if ( cullFace !== this.currentCullFace ) {
  18910. if ( cullFace === CullFaceBack ) {
  18911. gl.cullFace( gl.BACK );
  18912. } else if ( cullFace === CullFaceFront ) {
  18913. gl.cullFace( gl.FRONT );
  18914. } else {
  18915. gl.cullFace( gl.FRONT_AND_BACK );
  18916. }
  18917. }
  18918. } else {
  18919. this.disable( gl.CULL_FACE );
  18920. }
  18921. this.currentCullFace = cullFace;
  18922. }
  18923. setLineWidth( width ) {
  18924. const { currentLineWidth, gl } = this;
  18925. if ( width !== currentLineWidth ) {
  18926. gl.lineWidth( width );
  18927. this.currentLineWidth = width;
  18928. }
  18929. }
  18930. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  18931. const { gl } = this;
  18932. if ( blending === NoBlending ) {
  18933. if ( this.currentBlendingEnabled === true ) {
  18934. this.disable( gl.BLEND );
  18935. this.currentBlendingEnabled = false;
  18936. }
  18937. return;
  18938. }
  18939. if ( this.currentBlendingEnabled === false ) {
  18940. this.enable( gl.BLEND );
  18941. this.currentBlendingEnabled = true;
  18942. }
  18943. if ( blending !== CustomBlending ) {
  18944. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  18945. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  18946. gl.blendEquation( gl.FUNC_ADD );
  18947. this.currentBlendEquation = AddEquation;
  18948. this.currentBlendEquationAlpha = AddEquation;
  18949. }
  18950. if ( premultipliedAlpha ) {
  18951. switch ( blending ) {
  18952. case NormalBlending:
  18953. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  18954. break;
  18955. case AdditiveBlending:
  18956. gl.blendFunc( gl.ONE, gl.ONE );
  18957. break;
  18958. case SubtractiveBlending:
  18959. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  18960. break;
  18961. case MultiplyBlending:
  18962. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  18963. break;
  18964. default:
  18965. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  18966. break;
  18967. }
  18968. } else {
  18969. switch ( blending ) {
  18970. case NormalBlending:
  18971. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  18972. break;
  18973. case AdditiveBlending:
  18974. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  18975. break;
  18976. case SubtractiveBlending:
  18977. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  18978. break;
  18979. case MultiplyBlending:
  18980. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  18981. break;
  18982. default:
  18983. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  18984. break;
  18985. }
  18986. }
  18987. this.currentBlendSrc = null;
  18988. this.currentBlendDst = null;
  18989. this.currentBlendSrcAlpha = null;
  18990. this.currentBlendDstAlpha = null;
  18991. this.currentBlending = blending;
  18992. this.currentPremultipledAlpha = premultipliedAlpha;
  18993. }
  18994. return;
  18995. }
  18996. // custom blending
  18997. blendEquationAlpha = blendEquationAlpha || blendEquation;
  18998. blendSrcAlpha = blendSrcAlpha || blendSrc;
  18999. blendDstAlpha = blendDstAlpha || blendDst;
  19000. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  19001. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  19002. this.currentBlendEquation = blendEquation;
  19003. this.currentBlendEquationAlpha = blendEquationAlpha;
  19004. }
  19005. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  19006. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  19007. this.currentBlendSrc = blendSrc;
  19008. this.currentBlendDst = blendDst;
  19009. this.currentBlendSrcAlpha = blendSrcAlpha;
  19010. this.currentBlendDstAlpha = blendDstAlpha;
  19011. }
  19012. this.currentBlending = blending;
  19013. this.currentPremultipledAlpha = false;
  19014. }
  19015. setColorMask( colorMask ) {
  19016. if ( this.currentColorMask !== colorMask ) {
  19017. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  19018. this.currentColorMask = colorMask;
  19019. }
  19020. }
  19021. setDepthTest( depthTest ) {
  19022. const { gl } = this;
  19023. if ( depthTest ) {
  19024. this.enable( gl.DEPTH_TEST );
  19025. } else {
  19026. this.disable( gl.DEPTH_TEST );
  19027. }
  19028. }
  19029. setDepthMask( depthMask ) {
  19030. if ( this.currentDepthMask !== depthMask ) {
  19031. this.gl.depthMask( depthMask );
  19032. this.currentDepthMask = depthMask;
  19033. }
  19034. }
  19035. setDepthFunc( depthFunc ) {
  19036. if ( this.currentDepthFunc !== depthFunc ) {
  19037. const { gl } = this;
  19038. switch ( depthFunc ) {
  19039. case NeverDepth:
  19040. gl.depthFunc( gl.NEVER );
  19041. break;
  19042. case AlwaysDepth:
  19043. gl.depthFunc( gl.ALWAYS );
  19044. break;
  19045. case LessDepth:
  19046. gl.depthFunc( gl.LESS );
  19047. break;
  19048. case LessEqualDepth:
  19049. gl.depthFunc( gl.LEQUAL );
  19050. break;
  19051. case EqualDepth:
  19052. gl.depthFunc( gl.EQUAL );
  19053. break;
  19054. case GreaterEqualDepth:
  19055. gl.depthFunc( gl.GEQUAL );
  19056. break;
  19057. case GreaterDepth:
  19058. gl.depthFunc( gl.GREATER );
  19059. break;
  19060. case NotEqualDepth:
  19061. gl.depthFunc( gl.NOTEQUAL );
  19062. break;
  19063. default:
  19064. gl.depthFunc( gl.LEQUAL );
  19065. }
  19066. this.currentDepthFunc = depthFunc;
  19067. }
  19068. }
  19069. setStencilTest( stencilTest ) {
  19070. const { gl } = this;
  19071. if ( stencilTest ) {
  19072. this.enable( gl.STENCIL_TEST );
  19073. } else {
  19074. this.disable( gl.STENCIL_TEST );
  19075. }
  19076. }
  19077. setStencilMask( stencilMask ) {
  19078. if ( this.currentStencilMask !== stencilMask ) {
  19079. this.gl.stencilMask( stencilMask );
  19080. this.currentStencilMask = stencilMask;
  19081. }
  19082. }
  19083. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  19084. if ( this.currentStencilFunc !== stencilFunc ||
  19085. this.currentStencilRef !== stencilRef ||
  19086. this.currentStencilFuncMask !== stencilMask ) {
  19087. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  19088. this.currentStencilFunc = stencilFunc;
  19089. this.currentStencilRef = stencilRef;
  19090. this.currentStencilFuncMask = stencilMask;
  19091. }
  19092. }
  19093. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  19094. if ( this.currentStencilFail !== stencilFail ||
  19095. this.currentStencilZFail !== stencilZFail ||
  19096. this.currentStencilZPass !== stencilZPass ) {
  19097. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  19098. this.currentStencilFail = stencilFail;
  19099. this.currentStencilZFail = stencilZFail;
  19100. this.currentStencilZPass = stencilZPass;
  19101. }
  19102. }
  19103. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  19104. const { gl } = this;
  19105. material.side === DoubleSide
  19106. ? this.disable( gl.CULL_FACE )
  19107. : this.enable( gl.CULL_FACE );
  19108. let flipSided = ( material.side === BackSide );
  19109. if ( frontFaceCW ) flipSided = ! flipSided;
  19110. this.setFlipSided( flipSided );
  19111. ( material.blending === NormalBlending && material.transparent === false )
  19112. ? this.setBlending( NoBlending )
  19113. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  19114. this.setDepthFunc( material.depthFunc );
  19115. this.setDepthTest( material.depthTest );
  19116. this.setDepthMask( material.depthWrite );
  19117. this.setColorMask( material.colorWrite );
  19118. const stencilWrite = material.stencilWrite;
  19119. this.setStencilTest( stencilWrite );
  19120. if ( stencilWrite ) {
  19121. this.setStencilMask( material.stencilWriteMask );
  19122. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  19123. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  19124. }
  19125. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  19126. material.alphaToCoverage === true && this.backend.renderer.samples > 1
  19127. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  19128. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  19129. if ( hardwareClippingPlanes > 0 ) {
  19130. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  19131. const CLIP_DISTANCE0_WEBGL = 0x3000;
  19132. for ( let i = 0; i < 8; i ++ ) {
  19133. if ( i < hardwareClippingPlanes ) {
  19134. this.enable( CLIP_DISTANCE0_WEBGL + i );
  19135. } else {
  19136. this.disable( CLIP_DISTANCE0_WEBGL + i );
  19137. }
  19138. }
  19139. }
  19140. }
  19141. }
  19142. setPolygonOffset( polygonOffset, factor, units ) {
  19143. const { gl } = this;
  19144. if ( polygonOffset ) {
  19145. this.enable( gl.POLYGON_OFFSET_FILL );
  19146. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  19147. gl.polygonOffset( factor, units );
  19148. this.currentPolygonOffsetFactor = factor;
  19149. this.currentPolygonOffsetUnits = units;
  19150. }
  19151. } else {
  19152. this.disable( gl.POLYGON_OFFSET_FILL );
  19153. }
  19154. }
  19155. useProgram( program ) {
  19156. if ( this.currentProgram !== program ) {
  19157. this.gl.useProgram( program );
  19158. this.currentProgram = program;
  19159. return true;
  19160. }
  19161. return false;
  19162. }
  19163. // framebuffer
  19164. bindFramebuffer( target, framebuffer ) {
  19165. const { gl, currentBoundFramebuffers } = this;
  19166. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  19167. gl.bindFramebuffer( target, framebuffer );
  19168. currentBoundFramebuffers[ target ] = framebuffer;
  19169. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  19170. if ( target === gl.DRAW_FRAMEBUFFER ) {
  19171. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  19172. }
  19173. if ( target === gl.FRAMEBUFFER ) {
  19174. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  19175. }
  19176. return true;
  19177. }
  19178. return false;
  19179. }
  19180. drawBuffers( renderContext, framebuffer ) {
  19181. const { gl } = this;
  19182. let drawBuffers = [];
  19183. let needsUpdate = false;
  19184. if ( renderContext.textures !== null ) {
  19185. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  19186. if ( drawBuffers === undefined ) {
  19187. drawBuffers = [];
  19188. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  19189. }
  19190. const textures = renderContext.textures;
  19191. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  19192. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  19193. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  19194. }
  19195. drawBuffers.length = textures.length;
  19196. needsUpdate = true;
  19197. }
  19198. } else {
  19199. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  19200. drawBuffers[ 0 ] = gl.BACK;
  19201. needsUpdate = true;
  19202. }
  19203. }
  19204. if ( needsUpdate ) {
  19205. gl.drawBuffers( drawBuffers );
  19206. }
  19207. }
  19208. // texture
  19209. activeTexture( webglSlot ) {
  19210. const { gl, currentTextureSlot, maxTextures } = this;
  19211. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  19212. if ( currentTextureSlot !== webglSlot ) {
  19213. gl.activeTexture( webglSlot );
  19214. this.currentTextureSlot = webglSlot;
  19215. }
  19216. }
  19217. bindTexture( webglType, webglTexture, webglSlot ) {
  19218. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  19219. if ( webglSlot === undefined ) {
  19220. if ( currentTextureSlot === null ) {
  19221. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  19222. } else {
  19223. webglSlot = currentTextureSlot;
  19224. }
  19225. }
  19226. let boundTexture = currentBoundTextures[ webglSlot ];
  19227. if ( boundTexture === undefined ) {
  19228. boundTexture = { type: undefined, texture: undefined };
  19229. currentBoundTextures[ webglSlot ] = boundTexture;
  19230. }
  19231. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  19232. if ( currentTextureSlot !== webglSlot ) {
  19233. gl.activeTexture( webglSlot );
  19234. this.currentTextureSlot = webglSlot;
  19235. }
  19236. gl.bindTexture( webglType, webglTexture );
  19237. boundTexture.type = webglType;
  19238. boundTexture.texture = webglTexture;
  19239. }
  19240. }
  19241. bindBufferBase( target, index, buffer ) {
  19242. const { gl } = this;
  19243. const key = `${target}-${index}`;
  19244. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  19245. gl.bindBufferBase( target, index, buffer );
  19246. this.currentBoundBufferBases[ key ] = buffer;
  19247. return true;
  19248. }
  19249. return false;
  19250. }
  19251. unbindTexture() {
  19252. const { gl, currentTextureSlot, currentBoundTextures } = this;
  19253. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  19254. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  19255. gl.bindTexture( boundTexture.type, null );
  19256. boundTexture.type = undefined;
  19257. boundTexture.texture = undefined;
  19258. }
  19259. }
  19260. }
  19261. class WebGLUtils {
  19262. constructor( backend ) {
  19263. this.backend = backend;
  19264. this.gl = this.backend.gl;
  19265. this.extensions = backend.extensions;
  19266. }
  19267. convert( p, colorSpace = NoColorSpace ) {
  19268. const { gl, extensions } = this;
  19269. let extension;
  19270. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  19271. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  19272. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  19273. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  19274. if ( p === ByteType ) return gl.BYTE;
  19275. if ( p === ShortType ) return gl.SHORT;
  19276. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  19277. if ( p === IntType ) return gl.INT;
  19278. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  19279. if ( p === FloatType ) return gl.FLOAT;
  19280. if ( p === HalfFloatType ) {
  19281. return gl.HALF_FLOAT;
  19282. }
  19283. if ( p === AlphaFormat ) return gl.ALPHA;
  19284. if ( p === RGBFormat ) return gl.RGB;
  19285. if ( p === RGBAFormat ) return gl.RGBA;
  19286. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  19287. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  19288. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  19289. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  19290. // WebGL2 formats.
  19291. if ( p === RedFormat ) return gl.RED;
  19292. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  19293. if ( p === RGFormat ) return gl.RG;
  19294. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  19295. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  19296. // S3TC
  19297. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  19298. if ( colorSpace === SRGBColorSpace ) {
  19299. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  19300. if ( extension !== null ) {
  19301. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  19302. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  19303. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  19304. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  19305. } else {
  19306. return null;
  19307. }
  19308. } else {
  19309. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  19310. if ( extension !== null ) {
  19311. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  19312. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  19313. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  19314. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  19315. } else {
  19316. return null;
  19317. }
  19318. }
  19319. }
  19320. // PVRTC
  19321. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  19322. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  19323. if ( extension !== null ) {
  19324. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  19325. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  19326. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  19327. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  19328. } else {
  19329. return null;
  19330. }
  19331. }
  19332. // ETC
  19333. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  19334. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  19335. if ( extension !== null ) {
  19336. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  19337. if ( p === RGBA_ETC2_EAC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  19338. } else {
  19339. return null;
  19340. }
  19341. }
  19342. // ASTC
  19343. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  19344. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  19345. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  19346. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  19347. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  19348. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  19349. if ( extension !== null ) {
  19350. if ( p === RGBA_ASTC_4x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  19351. if ( p === RGBA_ASTC_5x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  19352. if ( p === RGBA_ASTC_5x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  19353. if ( p === RGBA_ASTC_6x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  19354. if ( p === RGBA_ASTC_6x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  19355. if ( p === RGBA_ASTC_8x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  19356. if ( p === RGBA_ASTC_8x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  19357. if ( p === RGBA_ASTC_8x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  19358. if ( p === RGBA_ASTC_10x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  19359. if ( p === RGBA_ASTC_10x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  19360. if ( p === RGBA_ASTC_10x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  19361. if ( p === RGBA_ASTC_10x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  19362. if ( p === RGBA_ASTC_12x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  19363. if ( p === RGBA_ASTC_12x12_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  19364. } else {
  19365. return null;
  19366. }
  19367. }
  19368. // BPTC
  19369. if ( p === RGBA_BPTC_Format ) {
  19370. extension = extensions.get( 'EXT_texture_compression_bptc' );
  19371. if ( extension !== null ) {
  19372. if ( p === RGBA_BPTC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  19373. } else {
  19374. return null;
  19375. }
  19376. }
  19377. // RGTC
  19378. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  19379. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  19380. if ( extension !== null ) {
  19381. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  19382. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  19383. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  19384. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  19385. } else {
  19386. return null;
  19387. }
  19388. }
  19389. //
  19390. if ( p === UnsignedInt248Type ) {
  19391. return gl.UNSIGNED_INT_24_8;
  19392. }
  19393. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  19394. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  19395. }
  19396. _clientWaitAsync() {
  19397. const { gl } = this;
  19398. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  19399. gl.flush();
  19400. return new Promise( ( resolve, reject ) => {
  19401. function test() {
  19402. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  19403. if ( res === gl.WAIT_FAILED ) {
  19404. gl.deleteSync( sync );
  19405. reject();
  19406. return;
  19407. }
  19408. if ( res === gl.TIMEOUT_EXPIRED ) {
  19409. requestAnimationFrame( test );
  19410. return;
  19411. }
  19412. gl.deleteSync( sync );
  19413. resolve();
  19414. }
  19415. test();
  19416. } );
  19417. }
  19418. }
  19419. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  19420. class WebGLTextureUtils {
  19421. constructor( backend ) {
  19422. this.backend = backend;
  19423. this.gl = backend.gl;
  19424. this.extensions = backend.extensions;
  19425. this.defaultTextures = {};
  19426. if ( initialized === false ) {
  19427. this._init( this.gl );
  19428. initialized = true;
  19429. }
  19430. }
  19431. _init( gl ) {
  19432. // Store only WebGL constants here.
  19433. wrappingToGL = {
  19434. [ RepeatWrapping ]: gl.REPEAT,
  19435. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  19436. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  19437. };
  19438. filterToGL = {
  19439. [ NearestFilter ]: gl.NEAREST,
  19440. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  19441. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  19442. [ LinearFilter ]: gl.LINEAR,
  19443. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  19444. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  19445. };
  19446. compareToGL = {
  19447. [ NeverCompare ]: gl.NEVER,
  19448. [ AlwaysCompare ]: gl.ALWAYS,
  19449. [ LessCompare ]: gl.LESS,
  19450. [ LessEqualCompare ]: gl.LEQUAL,
  19451. [ EqualCompare ]: gl.EQUAL,
  19452. [ GreaterEqualCompare ]: gl.GEQUAL,
  19453. [ GreaterCompare ]: gl.GREATER,
  19454. [ NotEqualCompare ]: gl.NOTEQUAL
  19455. };
  19456. }
  19457. filterFallback( f ) {
  19458. const { gl } = this;
  19459. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  19460. return gl.NEAREST;
  19461. }
  19462. return gl.LINEAR;
  19463. }
  19464. getGLTextureType( texture ) {
  19465. const { gl } = this;
  19466. let glTextureType;
  19467. if ( texture.isCubeTexture === true ) {
  19468. glTextureType = gl.TEXTURE_CUBE_MAP;
  19469. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  19470. glTextureType = gl.TEXTURE_2D_ARRAY;
  19471. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  19472. glTextureType = gl.TEXTURE_3D;
  19473. } else {
  19474. glTextureType = gl.TEXTURE_2D;
  19475. }
  19476. return glTextureType;
  19477. }
  19478. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  19479. const { gl, extensions } = this;
  19480. if ( internalFormatName !== null ) {
  19481. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  19482. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  19483. }
  19484. let internalFormat = glFormat;
  19485. if ( glFormat === gl.RED ) {
  19486. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  19487. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  19488. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  19489. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  19490. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  19491. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  19492. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  19493. if ( glType === gl.INT ) internalFormat = gl.R32I;
  19494. }
  19495. if ( glFormat === gl.RED_INTEGER ) {
  19496. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  19497. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  19498. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  19499. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  19500. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  19501. if ( glType === gl.INT ) internalFormat = gl.R32I;
  19502. }
  19503. if ( glFormat === gl.RG ) {
  19504. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  19505. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  19506. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  19507. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  19508. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  19509. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  19510. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  19511. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  19512. }
  19513. if ( glFormat === gl.RG_INTEGER ) {
  19514. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  19515. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  19516. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  19517. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  19518. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  19519. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  19520. }
  19521. if ( glFormat === gl.RGB ) {
  19522. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  19523. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  19524. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  19525. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  19526. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  19527. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  19528. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  19529. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  19530. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8 : gl.RGB8;
  19531. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  19532. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  19533. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  19534. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  19535. }
  19536. if ( glFormat === gl.RGB_INTEGER ) {
  19537. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  19538. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  19539. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  19540. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  19541. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  19542. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  19543. }
  19544. if ( glFormat === gl.RGBA ) {
  19545. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  19546. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  19547. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  19548. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  19549. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  19550. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  19551. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  19552. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  19553. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  19554. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  19555. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  19556. }
  19557. if ( glFormat === gl.RGBA_INTEGER ) {
  19558. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  19559. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  19560. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  19561. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  19562. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  19563. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  19564. }
  19565. if ( glFormat === gl.DEPTH_COMPONENT ) {
  19566. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH24_STENCIL8;
  19567. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  19568. }
  19569. if ( glFormat === gl.DEPTH_STENCIL ) {
  19570. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  19571. }
  19572. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  19573. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  19574. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  19575. extensions.get( 'EXT_color_buffer_float' );
  19576. }
  19577. return internalFormat;
  19578. }
  19579. setTextureParameters( textureType, texture ) {
  19580. const { gl, extensions, backend } = this;
  19581. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  19582. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  19583. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  19584. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE );
  19585. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  19586. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  19587. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  19588. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  19589. }
  19590. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  19591. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  19592. // follow WebGPU backend mapping for texture filtering
  19593. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  19594. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  19595. if ( texture.compareFunction ) {
  19596. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  19597. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  19598. }
  19599. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  19600. if ( texture.magFilter === NearestFilter ) return;
  19601. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  19602. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  19603. if ( texture.anisotropy > 1 ) {
  19604. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  19605. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  19606. }
  19607. }
  19608. }
  19609. createDefaultTexture( texture ) {
  19610. const { gl, backend, defaultTextures } = this;
  19611. const glTextureType = this.getGLTextureType( texture );
  19612. let textureGPU = defaultTextures[ glTextureType ];
  19613. if ( textureGPU === undefined ) {
  19614. textureGPU = gl.createTexture();
  19615. backend.state.bindTexture( glTextureType, textureGPU );
  19616. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  19617. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  19618. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  19619. defaultTextures[ glTextureType ] = textureGPU;
  19620. }
  19621. backend.set( texture, {
  19622. textureGPU,
  19623. glTextureType,
  19624. isDefault: true
  19625. } );
  19626. }
  19627. createTexture( texture, options ) {
  19628. const { gl, backend } = this;
  19629. const { levels, width, height, depth } = options;
  19630. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  19631. const glType = backend.utils.convert( texture.type );
  19632. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  19633. const textureGPU = gl.createTexture();
  19634. const glTextureType = this.getGLTextureType( texture );
  19635. backend.state.bindTexture( glTextureType, textureGPU );
  19636. this.setTextureParameters( glTextureType, texture );
  19637. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  19638. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  19639. } else if ( texture.isData3DTexture ) {
  19640. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  19641. } else if ( ! texture.isVideoTexture ) {
  19642. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  19643. }
  19644. backend.set( texture, {
  19645. textureGPU,
  19646. glTextureType,
  19647. glFormat,
  19648. glType,
  19649. glInternalFormat
  19650. } );
  19651. }
  19652. copyBufferToTexture( buffer, texture ) {
  19653. const { gl, backend } = this;
  19654. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  19655. const { width, height } = texture.source.data;
  19656. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  19657. backend.state.bindTexture( glTextureType, textureGPU );
  19658. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  19659. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  19660. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  19661. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  19662. backend.state.unbindTexture();
  19663. // debug
  19664. // const framebuffer = gl.createFramebuffer();
  19665. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  19666. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  19667. // const readout = new Float32Array( width * height * 4 );
  19668. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  19669. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  19670. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  19671. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  19672. // console.log( readout );
  19673. }
  19674. updateTexture( texture, options ) {
  19675. const { gl } = this;
  19676. const { width, height } = options;
  19677. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  19678. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  19679. return;
  19680. const getImage = ( source ) => {
  19681. if ( source.isDataTexture ) {
  19682. return source.image.data;
  19683. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  19684. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  19685. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  19686. source instanceof OffscreenCanvas ) {
  19687. return source;
  19688. }
  19689. return source.data;
  19690. };
  19691. this.backend.state.bindTexture( glTextureType, textureGPU );
  19692. this.setTextureParameters( glTextureType, texture );
  19693. if ( texture.isCompressedTexture ) {
  19694. const mipmaps = texture.mipmaps;
  19695. const image = options.image;
  19696. for ( let i = 0; i < mipmaps.length; i ++ ) {
  19697. const mipmap = mipmaps[ i ];
  19698. if ( texture.isCompressedArrayTexture ) {
  19699. if ( texture.format !== gl.RGBA ) {
  19700. if ( glFormat !== null ) {
  19701. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  19702. } else {
  19703. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  19704. }
  19705. } else {
  19706. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  19707. }
  19708. } else {
  19709. if ( glFormat !== null ) {
  19710. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  19711. } else {
  19712. console.warn( 'Unsupported compressed texture format' );
  19713. }
  19714. }
  19715. }
  19716. } else if ( texture.isCubeTexture ) {
  19717. const images = options.images;
  19718. for ( let i = 0; i < 6; i ++ ) {
  19719. const image = getImage( images[ i ] );
  19720. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  19721. }
  19722. } else if ( texture.isDataArrayTexture ) {
  19723. const image = options.image;
  19724. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  19725. } else if ( texture.isData3DTexture ) {
  19726. const image = options.image;
  19727. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  19728. } else if ( texture.isVideoTexture ) {
  19729. texture.update();
  19730. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  19731. } else {
  19732. const image = getImage( options.image );
  19733. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  19734. }
  19735. }
  19736. generateMipmaps( texture ) {
  19737. const { gl, backend } = this;
  19738. const { textureGPU, glTextureType } = backend.get( texture );
  19739. backend.state.bindTexture( glTextureType, textureGPU );
  19740. gl.generateMipmap( glTextureType );
  19741. }
  19742. deallocateRenderBuffers( renderTarget ) {
  19743. const { gl, backend } = this;
  19744. // remove framebuffer reference
  19745. if ( renderTarget ) {
  19746. const renderContextData = backend.get( renderTarget );
  19747. renderContextData.renderBufferStorageSetup = undefined;
  19748. if ( renderContextData.framebuffers ) {
  19749. for ( const cacheKey in renderContextData.framebuffers ) {
  19750. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  19751. }
  19752. delete renderContextData.framebuffers;
  19753. }
  19754. if ( renderContextData.depthRenderbuffer ) {
  19755. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  19756. delete renderContextData.depthRenderbuffer;
  19757. }
  19758. if ( renderContextData.stencilRenderbuffer ) {
  19759. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  19760. delete renderContextData.stencilRenderbuffer;
  19761. }
  19762. if ( renderContextData.msaaFrameBuffer ) {
  19763. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  19764. delete renderContextData.msaaFrameBuffer;
  19765. }
  19766. if ( renderContextData.msaaRenderbuffers ) {
  19767. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  19768. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  19769. }
  19770. delete renderContextData.msaaRenderbuffers;
  19771. }
  19772. }
  19773. }
  19774. destroyTexture( texture ) {
  19775. const { gl, backend } = this;
  19776. const { textureGPU, renderTarget } = backend.get( texture );
  19777. this.deallocateRenderBuffers( renderTarget );
  19778. gl.deleteTexture( textureGPU );
  19779. backend.delete( texture );
  19780. }
  19781. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  19782. const { gl, backend } = this;
  19783. const { state } = this.backend;
  19784. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  19785. let width, height, minX, minY;
  19786. let dstX, dstY;
  19787. if ( srcRegion !== null ) {
  19788. width = srcRegion.max.x - srcRegion.min.x;
  19789. height = srcRegion.max.y - srcRegion.min.y;
  19790. minX = srcRegion.min.x;
  19791. minY = srcRegion.min.y;
  19792. } else {
  19793. width = srcTexture.image.width;
  19794. height = srcTexture.image.height;
  19795. minX = 0;
  19796. minY = 0;
  19797. }
  19798. if ( dstPosition !== null ) {
  19799. dstX = dstPosition.x;
  19800. dstY = dstPosition.y;
  19801. } else {
  19802. dstX = 0;
  19803. dstY = 0;
  19804. }
  19805. state.bindTexture( glTextureType, dstTextureGPU );
  19806. // As another texture upload may have changed pixelStorei
  19807. // parameters, make sure they are correct for the dstTexture
  19808. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  19809. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  19810. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  19811. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  19812. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  19813. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  19814. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  19815. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  19816. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  19817. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  19818. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  19819. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  19820. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  19821. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  19822. if ( srcTexture.isRenderTargetTexture || srcTexture.isDepthTexture ) {
  19823. const srcTextureData = backend.get( srcTexture );
  19824. const dstTextureData = backend.get( dstTexture );
  19825. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  19826. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  19827. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  19828. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  19829. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  19830. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  19831. let mask = gl.COLOR_BUFFER_BIT;
  19832. if ( srcTexture.isDepthTexture ) mask = gl.DEPTH_BUFFER_BIT;
  19833. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, mask, gl.NEAREST );
  19834. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  19835. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  19836. } else {
  19837. if ( srcTexture.isDataTexture ) {
  19838. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image.data );
  19839. } else {
  19840. if ( srcTexture.isCompressedTexture ) {
  19841. gl.compressedTexSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, image.width, image.height, glFormat, image.data );
  19842. } else {
  19843. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image );
  19844. }
  19845. }
  19846. }
  19847. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  19848. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  19849. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  19850. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  19851. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  19852. // Generate mipmaps only when copying level 0
  19853. if ( level === 0 && dstTexture.generateMipmaps ) gl.generateMipmap( gl.TEXTURE_2D );
  19854. state.unbindTexture();
  19855. }
  19856. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  19857. const { gl } = this;
  19858. const { state } = this.backend;
  19859. const { textureGPU } = this.backend.get( texture );
  19860. const { x, y, z: width, w: height } = rectangle;
  19861. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  19862. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.gerDrawingBufferSize().y;
  19863. if ( requireDrawFrameBuffer ) {
  19864. const partial = ( x !== 0 || y !== 0 );
  19865. let mask;
  19866. let attachment;
  19867. if ( texture.isDepthTexture === true ) {
  19868. mask = gl.DEPTH_BUFFER_BIT;
  19869. attachment = gl.DEPTH_ATTACHMENT;
  19870. if ( renderContext.stencil ) {
  19871. mask |= gl.STENCIL_BUFFER_BIT;
  19872. }
  19873. } else {
  19874. mask = gl.COLOR_BUFFER_BIT;
  19875. attachment = gl.COLOR_ATTACHMENT0;
  19876. }
  19877. if ( partial ) {
  19878. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  19879. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  19880. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  19881. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  19882. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  19883. const flippedY = srcHeight - y - height;
  19884. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  19885. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  19886. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  19887. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  19888. state.unbindTexture();
  19889. } else {
  19890. const fb = gl.createFramebuffer();
  19891. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  19892. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  19893. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  19894. gl.deleteFramebuffer( fb );
  19895. }
  19896. } else {
  19897. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  19898. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  19899. state.unbindTexture();
  19900. }
  19901. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  19902. this.backend._setFramebuffer( renderContext );
  19903. }
  19904. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  19905. setupRenderBufferStorage( renderbuffer, renderContext ) {
  19906. const { gl } = this;
  19907. const renderTarget = renderContext.renderTarget;
  19908. const { samples, depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  19909. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  19910. if ( depthBuffer && ! stencilBuffer ) {
  19911. let glInternalFormat = gl.DEPTH_COMPONENT24;
  19912. if ( samples > 0 ) {
  19913. if ( depthTexture && depthTexture.isDepthTexture ) {
  19914. if ( depthTexture.type === gl.FLOAT ) {
  19915. glInternalFormat = gl.DEPTH_COMPONENT32F;
  19916. }
  19917. }
  19918. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  19919. } else {
  19920. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  19921. }
  19922. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  19923. } else if ( depthBuffer && stencilBuffer ) {
  19924. if ( samples > 0 ) {
  19925. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  19926. } else {
  19927. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  19928. }
  19929. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  19930. }
  19931. }
  19932. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  19933. const { backend, gl } = this;
  19934. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  19935. const fb = gl.createFramebuffer();
  19936. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  19937. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  19938. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  19939. const typedArrayType = this._getTypedArrayType( glType );
  19940. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  19941. const elementCount = width * height;
  19942. const byteLength = elementCount * bytesPerTexel;
  19943. const buffer = gl.createBuffer();
  19944. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  19945. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  19946. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  19947. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  19948. await backend.utils._clientWaitAsync();
  19949. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  19950. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  19951. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  19952. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  19953. gl.deleteFramebuffer( fb );
  19954. return dstBuffer;
  19955. }
  19956. _getTypedArrayType( glType ) {
  19957. const { gl } = this;
  19958. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  19959. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  19960. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  19961. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  19962. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  19963. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  19964. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  19965. if ( glType === gl.FLOAT ) return Float32Array;
  19966. throw new Error( `Unsupported WebGL type: ${glType}` );
  19967. }
  19968. _getBytesPerTexel( glType, glFormat ) {
  19969. const { gl } = this;
  19970. let bytesPerComponent = 0;
  19971. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  19972. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  19973. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  19974. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  19975. glType === gl.UNSIGNED_SHORT ||
  19976. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  19977. if ( glType === gl.UNSIGNED_INT ||
  19978. glType === gl.FLOAT ) bytesPerComponent = 4;
  19979. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  19980. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  19981. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  19982. }
  19983. }
  19984. class WebGLExtensions {
  19985. constructor( backend ) {
  19986. this.backend = backend;
  19987. this.gl = this.backend.gl;
  19988. this.availableExtensions = this.gl.getSupportedExtensions();
  19989. this.extensions = {};
  19990. }
  19991. get( name ) {
  19992. let extension = this.extensions[ name ];
  19993. if ( extension === undefined ) {
  19994. extension = this.gl.getExtension( name );
  19995. this.extensions[ name ] = extension;
  19996. }
  19997. return extension;
  19998. }
  19999. has( name ) {
  20000. return this.availableExtensions.includes( name );
  20001. }
  20002. }
  20003. class WebGLCapabilities {
  20004. constructor( backend ) {
  20005. this.backend = backend;
  20006. this.maxAnisotropy = null;
  20007. }
  20008. getMaxAnisotropy() {
  20009. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  20010. const gl = this.backend.gl;
  20011. const extensions = this.backend.extensions;
  20012. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  20013. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  20014. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  20015. } else {
  20016. this.maxAnisotropy = 0;
  20017. }
  20018. return this.maxAnisotropy;
  20019. }
  20020. }
  20021. const GLFeatureName = {
  20022. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  20023. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  20024. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  20025. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  20026. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  20027. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  20028. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  20029. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  20030. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  20031. };
  20032. class WebGLBufferRenderer {
  20033. constructor( backend ) {
  20034. this.gl = backend.gl;
  20035. this.extensions = backend.extensions;
  20036. this.info = backend.renderer.info;
  20037. this.mode = null;
  20038. this.index = 0;
  20039. this.type = null;
  20040. this.object = null;
  20041. }
  20042. render( start, count ) {
  20043. const { gl, mode, object, type, info, index } = this;
  20044. if ( index !== 0 ) {
  20045. gl.drawElements( mode, count, type, start );
  20046. } else {
  20047. gl.drawArrays( mode, start, count );
  20048. }
  20049. info.update( object, count, mode, 1 );
  20050. }
  20051. renderInstances( start, count, primcount ) {
  20052. const { gl, mode, type, index, object, info } = this;
  20053. if ( primcount === 0 ) return;
  20054. if ( index !== 0 ) {
  20055. gl.drawElementsInstanced( mode, count, type, start, primcount );
  20056. } else {
  20057. gl.drawArraysInstanced( mode, start, count, primcount );
  20058. }
  20059. info.update( object, count, mode, primcount );
  20060. }
  20061. renderMultiDraw( starts, counts, drawCount ) {
  20062. const { extensions, mode, object, info } = this;
  20063. if ( drawCount === 0 ) return;
  20064. const extension = extensions.get( 'WEBGL_multi_draw' );
  20065. if ( extension === null ) {
  20066. for ( let i = 0; i < drawCount; i ++ ) {
  20067. this.render( starts[ i ], counts[ i ] );
  20068. }
  20069. } else {
  20070. if ( this.index !== 0 ) {
  20071. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  20072. } else {
  20073. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  20074. }
  20075. let elementCount = 0;
  20076. for ( let i = 0; i < drawCount; i ++ ) {
  20077. elementCount += counts[ i ];
  20078. }
  20079. info.update( object, elementCount, mode, 1 );
  20080. }
  20081. }
  20082. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  20083. const { extensions, mode, object, info } = this;
  20084. if ( drawCount === 0 ) return;
  20085. const extension = extensions.get( 'WEBGL_multi_draw' );
  20086. if ( extension === null ) {
  20087. for ( let i = 0; i < drawCount; i ++ ) {
  20088. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  20089. }
  20090. } else {
  20091. if ( this.index !== 0 ) {
  20092. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  20093. } else {
  20094. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  20095. }
  20096. let elementCount = 0;
  20097. for ( let i = 0; i < drawCount; i ++ ) {
  20098. elementCount += counts[ i ] * primcount[ i ];
  20099. }
  20100. info.update( object, elementCount, mode, 1 );
  20101. }
  20102. }
  20103. //
  20104. }
  20105. //
  20106. class WebGLBackend extends Backend {
  20107. constructor( parameters = {} ) {
  20108. super( parameters );
  20109. this.isWebGLBackend = true;
  20110. }
  20111. init( renderer ) {
  20112. super.init( renderer );
  20113. //
  20114. const parameters = this.parameters;
  20115. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2' );
  20116. function onContextLost( event ) {
  20117. event.preventDefault();
  20118. const contextLossInfo = {
  20119. api: 'WebGL',
  20120. message: event.statusMessage || 'Unknown reason',
  20121. reason: null,
  20122. originalEvent: event
  20123. };
  20124. renderer.onDeviceLost( contextLossInfo );
  20125. }
  20126. this._onContextLost = onContextLost;
  20127. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  20128. this.gl = glContext;
  20129. this.extensions = new WebGLExtensions( this );
  20130. this.capabilities = new WebGLCapabilities( this );
  20131. this.attributeUtils = new WebGLAttributeUtils( this );
  20132. this.textureUtils = new WebGLTextureUtils( this );
  20133. this.bufferRenderer = new WebGLBufferRenderer( this );
  20134. this.state = new WebGLState( this );
  20135. this.utils = new WebGLUtils( this );
  20136. this.vaoCache = {};
  20137. this.transformFeedbackCache = {};
  20138. this.discard = false;
  20139. this.trackTimestamp = ( parameters.trackTimestamp === true );
  20140. this.extensions.get( 'EXT_color_buffer_float' );
  20141. this.extensions.get( 'WEBGL_clip_cull_distance' );
  20142. this.extensions.get( 'OES_texture_float_linear' );
  20143. this.extensions.get( 'EXT_color_buffer_half_float' );
  20144. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  20145. this.extensions.get( 'WEBGL_render_shared_exponent' );
  20146. this.extensions.get( 'WEBGL_multi_draw' );
  20147. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  20148. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  20149. this._knownBindings = new WeakSet();
  20150. this._currentContext = null;
  20151. }
  20152. get coordinateSystem() {
  20153. return WebGLCoordinateSystem;
  20154. }
  20155. async getArrayBufferAsync( attribute ) {
  20156. return await this.attributeUtils.getArrayBufferAsync( attribute );
  20157. }
  20158. async waitForGPU() {
  20159. await this.utils._clientWaitAsync();
  20160. }
  20161. initTimestampQuery( renderContext ) {
  20162. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  20163. const renderContextData = this.get( renderContext );
  20164. if ( this.queryRunning ) {
  20165. if ( ! renderContextData.queryQueue ) renderContextData.queryQueue = [];
  20166. renderContextData.queryQueue.push( renderContext );
  20167. return;
  20168. }
  20169. if ( renderContextData.activeQuery ) {
  20170. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  20171. renderContextData.activeQuery = null;
  20172. }
  20173. renderContextData.activeQuery = this.gl.createQuery();
  20174. if ( renderContextData.activeQuery !== null ) {
  20175. this.gl.beginQuery( this.disjoint.TIME_ELAPSED_EXT, renderContextData.activeQuery );
  20176. this.queryRunning = true;
  20177. }
  20178. }
  20179. // timestamp utils
  20180. prepareTimestampBuffer( renderContext ) {
  20181. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  20182. const renderContextData = this.get( renderContext );
  20183. if ( renderContextData.activeQuery ) {
  20184. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  20185. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  20186. renderContextData.gpuQueries.push( { query: renderContextData.activeQuery } );
  20187. renderContextData.activeQuery = null;
  20188. this.queryRunning = false;
  20189. if ( renderContextData.queryQueue && renderContextData.queryQueue.length > 0 ) {
  20190. const nextRenderContext = renderContextData.queryQueue.shift();
  20191. this.initTimestampQuery( nextRenderContext );
  20192. }
  20193. }
  20194. }
  20195. async resolveTimestampAsync( renderContext, type = 'render' ) {
  20196. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  20197. const renderContextData = this.get( renderContext );
  20198. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  20199. for ( let i = 0; i < renderContextData.gpuQueries.length; i ++ ) {
  20200. const queryInfo = renderContextData.gpuQueries[ i ];
  20201. const available = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT_AVAILABLE );
  20202. const disjoint = this.gl.getParameter( this.disjoint.GPU_DISJOINT_EXT );
  20203. if ( available && ! disjoint ) {
  20204. const elapsed = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT );
  20205. const duration = Number( elapsed ) / 1000000; // Convert nanoseconds to milliseconds
  20206. this.gl.deleteQuery( queryInfo.query );
  20207. renderContextData.gpuQueries.splice( i, 1 ); // Remove the processed query
  20208. i --;
  20209. this.renderer.info.updateTimestamp( type, duration );
  20210. }
  20211. }
  20212. }
  20213. getContext() {
  20214. return this.gl;
  20215. }
  20216. beginRender( renderContext ) {
  20217. const { gl } = this;
  20218. const renderContextData = this.get( renderContext );
  20219. //
  20220. //
  20221. this.initTimestampQuery( renderContext );
  20222. renderContextData.previousContext = this._currentContext;
  20223. this._currentContext = renderContext;
  20224. this._setFramebuffer( renderContext );
  20225. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  20226. //
  20227. if ( renderContext.viewport ) {
  20228. this.updateViewport( renderContext );
  20229. } else {
  20230. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  20231. }
  20232. if ( renderContext.scissor ) {
  20233. const { x, y, width, height } = renderContext.scissorValue;
  20234. gl.scissor( x, renderContext.height - height - y, width, height );
  20235. }
  20236. const occlusionQueryCount = renderContext.occlusionQueryCount;
  20237. if ( occlusionQueryCount > 0 ) {
  20238. // Get a reference to the array of objects with queries. The renderContextData property
  20239. // can be changed by another render pass before the async reading of all previous queries complete
  20240. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  20241. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  20242. renderContextData.lastOcclusionObject = null;
  20243. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  20244. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  20245. renderContextData.occlusionQueryIndex = 0;
  20246. }
  20247. }
  20248. finishRender( renderContext ) {
  20249. const { gl, state } = this;
  20250. const renderContextData = this.get( renderContext );
  20251. const previousContext = renderContextData.previousContext;
  20252. const occlusionQueryCount = renderContext.occlusionQueryCount;
  20253. if ( occlusionQueryCount > 0 ) {
  20254. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  20255. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  20256. }
  20257. this.resolveOccludedAsync( renderContext );
  20258. }
  20259. const textures = renderContext.textures;
  20260. if ( textures !== null ) {
  20261. for ( let i = 0; i < textures.length; i ++ ) {
  20262. const texture = textures[ i ];
  20263. if ( texture.generateMipmaps ) {
  20264. this.generateMipmaps( texture );
  20265. }
  20266. }
  20267. }
  20268. this._currentContext = previousContext;
  20269. if ( renderContext.textures !== null && renderContext.renderTarget ) {
  20270. const renderTargetContextData = this.get( renderContext.renderTarget );
  20271. const { samples } = renderContext.renderTarget;
  20272. if ( samples > 0 ) {
  20273. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  20274. const mask = gl.COLOR_BUFFER_BIT;
  20275. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  20276. const textures = renderContext.textures;
  20277. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  20278. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  20279. for ( let i = 0; i < textures.length; i ++ ) {
  20280. // TODO Add support for MRT
  20281. if ( renderContext.scissor ) {
  20282. const { x, y, width, height } = renderContext.scissorValue;
  20283. const viewY = renderContext.height - height - y;
  20284. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  20285. gl.invalidateSubFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray, x, viewY, width, height );
  20286. } else {
  20287. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  20288. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  20289. }
  20290. }
  20291. }
  20292. }
  20293. if ( previousContext !== null ) {
  20294. this._setFramebuffer( previousContext );
  20295. if ( previousContext.viewport ) {
  20296. this.updateViewport( previousContext );
  20297. } else {
  20298. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  20299. }
  20300. }
  20301. this.prepareTimestampBuffer( renderContext );
  20302. }
  20303. resolveOccludedAsync( renderContext ) {
  20304. const renderContextData = this.get( renderContext );
  20305. // handle occlusion query results
  20306. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  20307. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  20308. const occluded = new WeakSet();
  20309. const { gl } = this;
  20310. renderContextData.currentOcclusionQueryObjects = null;
  20311. renderContextData.currentOcclusionQueries = null;
  20312. const check = () => {
  20313. let completed = 0;
  20314. // check all queries and requeue as appropriate
  20315. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  20316. const query = currentOcclusionQueries[ i ];
  20317. if ( query === null ) continue;
  20318. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  20319. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) > 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  20320. currentOcclusionQueries[ i ] = null;
  20321. gl.deleteQuery( query );
  20322. completed ++;
  20323. }
  20324. }
  20325. if ( completed < currentOcclusionQueries.length ) {
  20326. requestAnimationFrame( check );
  20327. } else {
  20328. renderContextData.occluded = occluded;
  20329. }
  20330. };
  20331. check();
  20332. }
  20333. }
  20334. isOccluded( renderContext, object ) {
  20335. const renderContextData = this.get( renderContext );
  20336. return renderContextData.occluded && renderContextData.occluded.has( object );
  20337. }
  20338. updateViewport( renderContext ) {
  20339. const gl = this.gl;
  20340. const { x, y, width, height } = renderContext.viewportValue;
  20341. gl.viewport( x, renderContext.height - height - y, width, height );
  20342. }
  20343. setScissorTest( boolean ) {
  20344. const gl = this.gl;
  20345. if ( boolean ) {
  20346. gl.enable( gl.SCISSOR_TEST );
  20347. } else {
  20348. gl.disable( gl.SCISSOR_TEST );
  20349. }
  20350. }
  20351. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  20352. const { gl } = this;
  20353. if ( descriptor === null ) {
  20354. const clearColor = this.getClearColor();
  20355. // premultiply alpha
  20356. clearColor.r *= clearColor.a;
  20357. clearColor.g *= clearColor.a;
  20358. clearColor.b *= clearColor.a;
  20359. descriptor = {
  20360. textures: null,
  20361. clearColorValue: clearColor
  20362. };
  20363. }
  20364. //
  20365. let clear = 0;
  20366. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  20367. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  20368. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  20369. if ( clear !== 0 ) {
  20370. let clearColor;
  20371. if ( descriptor.clearColorValue ) {
  20372. clearColor = descriptor.clearColorValue;
  20373. } else {
  20374. clearColor = this.getClearColor();
  20375. // premultiply alpha
  20376. clearColor.r *= clearColor.a;
  20377. clearColor.g *= clearColor.a;
  20378. clearColor.b *= clearColor.a;
  20379. }
  20380. if ( depth ) this.state.setDepthMask( true );
  20381. if ( descriptor.textures === null ) {
  20382. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  20383. gl.clear( clear );
  20384. } else {
  20385. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  20386. if ( color ) {
  20387. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  20388. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  20389. }
  20390. }
  20391. if ( depth && stencil ) {
  20392. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, 1, 0 );
  20393. } else if ( depth ) {
  20394. gl.clearBufferfv( gl.DEPTH, 0, [ 1.0 ] );
  20395. } else if ( stencil ) {
  20396. gl.clearBufferiv( gl.STENCIL, 0, [ 0 ] );
  20397. }
  20398. }
  20399. }
  20400. }
  20401. beginCompute( computeGroup ) {
  20402. const { state, gl } = this;
  20403. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  20404. this.initTimestampQuery( computeGroup );
  20405. }
  20406. compute( computeGroup, computeNode, bindings, pipeline ) {
  20407. const { state, gl } = this;
  20408. if ( ! this.discard ) {
  20409. // required here to handle async behaviour of render.compute()
  20410. gl.enable( gl.RASTERIZER_DISCARD );
  20411. this.discard = true;
  20412. }
  20413. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  20414. const vaoKey = this._getVaoKey( null, attributes );
  20415. const vaoGPU = this.vaoCache[ vaoKey ];
  20416. if ( vaoGPU === undefined ) {
  20417. this._createVao( null, attributes );
  20418. } else {
  20419. gl.bindVertexArray( vaoGPU );
  20420. }
  20421. state.useProgram( programGPU );
  20422. this._bindUniforms( bindings );
  20423. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  20424. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  20425. gl.beginTransformFeedback( gl.POINTS );
  20426. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  20427. gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count );
  20428. } else {
  20429. gl.drawArrays( gl.POINTS, 0, computeNode.count );
  20430. }
  20431. gl.endTransformFeedback();
  20432. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  20433. // switch active buffers
  20434. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  20435. const dualAttributeData = transformBuffers[ i ];
  20436. if ( dualAttributeData.pbo ) {
  20437. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  20438. }
  20439. dualAttributeData.switchBuffers();
  20440. }
  20441. }
  20442. finishCompute( computeGroup ) {
  20443. const gl = this.gl;
  20444. this.discard = false;
  20445. gl.disable( gl.RASTERIZER_DISCARD );
  20446. this.prepareTimestampBuffer( computeGroup );
  20447. if ( this._currentContext ) {
  20448. this._setFramebuffer( this._currentContext );
  20449. }
  20450. }
  20451. draw( renderObject/*, info*/ ) {
  20452. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  20453. const { programGPU } = this.get( pipeline );
  20454. const { gl, state } = this;
  20455. const contextData = this.get( context );
  20456. const drawParams = renderObject.getDrawParameters();
  20457. if ( drawParams === null ) return;
  20458. //
  20459. this._bindUniforms( renderObject.getBindings() );
  20460. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  20461. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  20462. state.useProgram( programGPU );
  20463. //
  20464. const renderObjectData = this.get( renderObject );
  20465. let vaoGPU = renderObjectData.staticVao;
  20466. if ( vaoGPU === undefined || renderObjectData.geometryId !== renderObject.geometry.id ) {
  20467. const vaoKey = this._getVaoKey( renderObject.getIndex(), renderObject.getAttributes() );
  20468. vaoGPU = this.vaoCache[ vaoKey ];
  20469. if ( vaoGPU === undefined ) {
  20470. let staticVao;
  20471. ( { vaoGPU, staticVao } = this._createVao( renderObject.getIndex(), renderObject.getAttributes() ) );
  20472. if ( staticVao ) {
  20473. renderObjectData.staticVao = vaoGPU;
  20474. renderObjectData.geometryId = renderObject.geometry.id;
  20475. }
  20476. }
  20477. }
  20478. gl.bindVertexArray( vaoGPU );
  20479. //
  20480. const index = renderObject.getIndex();
  20481. //
  20482. const lastObject = contextData.lastOcclusionObject;
  20483. if ( lastObject !== object && lastObject !== undefined ) {
  20484. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  20485. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  20486. contextData.occlusionQueryIndex ++;
  20487. }
  20488. if ( object.occlusionTest === true ) {
  20489. const query = gl.createQuery();
  20490. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  20491. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  20492. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  20493. }
  20494. contextData.lastOcclusionObject = object;
  20495. }
  20496. //
  20497. const renderer = this.bufferRenderer;
  20498. if ( object.isPoints ) renderer.mode = gl.POINTS;
  20499. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  20500. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  20501. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  20502. else {
  20503. if ( material.wireframe === true ) {
  20504. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  20505. renderer.mode = gl.LINES;
  20506. } else {
  20507. renderer.mode = gl.TRIANGLES;
  20508. }
  20509. }
  20510. //
  20511. const { vertexCount, instanceCount } = drawParams;
  20512. let { firstVertex } = drawParams;
  20513. renderer.object = object;
  20514. if ( index !== null ) {
  20515. firstVertex *= index.array.BYTES_PER_ELEMENT;
  20516. const indexData = this.get( index );
  20517. renderer.index = index.count;
  20518. renderer.type = indexData.type;
  20519. } else {
  20520. renderer.index = 0;
  20521. }
  20522. if ( object.isBatchedMesh ) {
  20523. if ( object._multiDrawInstances !== null ) {
  20524. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  20525. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  20526. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  20527. } else {
  20528. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  20529. }
  20530. } else if ( instanceCount > 1 ) {
  20531. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  20532. } else {
  20533. renderer.render( firstVertex, vertexCount );
  20534. }
  20535. //
  20536. gl.bindVertexArray( null );
  20537. }
  20538. needsRenderUpdate( /*renderObject*/ ) {
  20539. return false;
  20540. }
  20541. getRenderCacheKey( /*renderObject*/ ) {
  20542. return '';
  20543. }
  20544. // textures
  20545. createDefaultTexture( texture ) {
  20546. this.textureUtils.createDefaultTexture( texture );
  20547. }
  20548. createTexture( texture, options ) {
  20549. this.textureUtils.createTexture( texture, options );
  20550. }
  20551. updateTexture( texture, options ) {
  20552. this.textureUtils.updateTexture( texture, options );
  20553. }
  20554. generateMipmaps( texture ) {
  20555. this.textureUtils.generateMipmaps( texture );
  20556. }
  20557. destroyTexture( texture ) {
  20558. this.textureUtils.destroyTexture( texture );
  20559. }
  20560. copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  20561. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  20562. }
  20563. createSampler( /*texture*/ ) {
  20564. //console.warn( 'Abstract class.' );
  20565. }
  20566. destroySampler() {}
  20567. // node builder
  20568. createNodeBuilder( object, renderer ) {
  20569. return new GLSLNodeBuilder( object, renderer );
  20570. }
  20571. // program
  20572. createProgram( program ) {
  20573. const gl = this.gl;
  20574. const { stage, code } = program;
  20575. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  20576. gl.shaderSource( shader, code );
  20577. gl.compileShader( shader );
  20578. this.set( program, {
  20579. shaderGPU: shader
  20580. } );
  20581. }
  20582. destroyProgram( /*program*/ ) {
  20583. console.warn( 'Abstract class.' );
  20584. }
  20585. createRenderPipeline( renderObject, promises ) {
  20586. const gl = this.gl;
  20587. const pipeline = renderObject.pipeline;
  20588. // Program
  20589. const { fragmentProgram, vertexProgram } = pipeline;
  20590. const programGPU = gl.createProgram();
  20591. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  20592. const vertexShader = this.get( vertexProgram ).shaderGPU;
  20593. gl.attachShader( programGPU, fragmentShader );
  20594. gl.attachShader( programGPU, vertexShader );
  20595. gl.linkProgram( programGPU );
  20596. this.set( pipeline, {
  20597. programGPU,
  20598. fragmentShader,
  20599. vertexShader
  20600. } );
  20601. if ( promises !== null && this.parallel ) {
  20602. const p = new Promise( ( resolve /*, reject*/ ) => {
  20603. const parallel = this.parallel;
  20604. const checkStatus = () => {
  20605. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  20606. this._completeCompile( renderObject, pipeline );
  20607. resolve();
  20608. } else {
  20609. requestAnimationFrame( checkStatus );
  20610. }
  20611. };
  20612. checkStatus();
  20613. } );
  20614. promises.push( p );
  20615. return;
  20616. }
  20617. this._completeCompile( renderObject, pipeline );
  20618. }
  20619. _handleSource( string, errorLine ) {
  20620. const lines = string.split( '\n' );
  20621. const lines2 = [];
  20622. const from = Math.max( errorLine - 6, 0 );
  20623. const to = Math.min( errorLine + 6, lines.length );
  20624. for ( let i = from; i < to; i ++ ) {
  20625. const line = i + 1;
  20626. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  20627. }
  20628. return lines2.join( '\n' );
  20629. }
  20630. _getShaderErrors( gl, shader, type ) {
  20631. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  20632. const errors = gl.getShaderInfoLog( shader ).trim();
  20633. if ( status && errors === '' ) return '';
  20634. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  20635. if ( errorMatches ) {
  20636. const errorLine = parseInt( errorMatches[ 1 ] );
  20637. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  20638. } else {
  20639. return errors;
  20640. }
  20641. }
  20642. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  20643. if ( this.renderer.debug.checkShaderErrors ) {
  20644. const gl = this.gl;
  20645. const programLog = gl.getProgramInfoLog( programGPU ).trim();
  20646. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  20647. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  20648. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  20649. } else {
  20650. // default error reporting
  20651. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  20652. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  20653. console.error(
  20654. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  20655. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  20656. 'Program Info Log: ' + programLog + '\n' +
  20657. vertexErrors + '\n' +
  20658. fragmentErrors
  20659. );
  20660. }
  20661. } else if ( programLog !== '' ) {
  20662. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  20663. }
  20664. }
  20665. }
  20666. _completeCompile( renderObject, pipeline ) {
  20667. const { state, gl } = this;
  20668. const pipelineData = this.get( pipeline );
  20669. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  20670. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  20671. this._logProgramError( programGPU, fragmentShader, vertexShader );
  20672. }
  20673. state.useProgram( programGPU );
  20674. // Bindings
  20675. const bindings = renderObject.getBindings();
  20676. this._setupBindings( bindings, programGPU );
  20677. //
  20678. this.set( pipeline, {
  20679. programGPU
  20680. } );
  20681. }
  20682. createComputePipeline( computePipeline, bindings ) {
  20683. const { state, gl } = this;
  20684. // Program
  20685. const fragmentProgram = {
  20686. stage: 'fragment',
  20687. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  20688. };
  20689. this.createProgram( fragmentProgram );
  20690. const { computeProgram } = computePipeline;
  20691. const programGPU = gl.createProgram();
  20692. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  20693. const vertexShader = this.get( computeProgram ).shaderGPU;
  20694. const transforms = computeProgram.transforms;
  20695. const transformVaryingNames = [];
  20696. const transformAttributeNodes = [];
  20697. for ( let i = 0; i < transforms.length; i ++ ) {
  20698. const transform = transforms[ i ];
  20699. transformVaryingNames.push( transform.varyingName );
  20700. transformAttributeNodes.push( transform.attributeNode );
  20701. }
  20702. gl.attachShader( programGPU, fragmentShader );
  20703. gl.attachShader( programGPU, vertexShader );
  20704. gl.transformFeedbackVaryings(
  20705. programGPU,
  20706. transformVaryingNames,
  20707. gl.SEPARATE_ATTRIBS
  20708. );
  20709. gl.linkProgram( programGPU );
  20710. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  20711. this._logProgramError( programGPU, fragmentShader, vertexShader );
  20712. }
  20713. state.useProgram( programGPU );
  20714. // Bindings
  20715. this._setupBindings( bindings, programGPU );
  20716. const attributeNodes = computeProgram.attributes;
  20717. const attributes = [];
  20718. const transformBuffers = [];
  20719. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  20720. const attribute = attributeNodes[ i ].node.attribute;
  20721. attributes.push( attribute );
  20722. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  20723. }
  20724. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  20725. const attribute = transformAttributeNodes[ i ].attribute;
  20726. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  20727. const attributeData = this.get( attribute );
  20728. transformBuffers.push( attributeData );
  20729. }
  20730. //
  20731. this.set( computePipeline, {
  20732. programGPU,
  20733. transformBuffers,
  20734. attributes
  20735. } );
  20736. }
  20737. createBindings( bindGroup, bindings ) {
  20738. if ( this._knownBindings.has( bindings ) === false ) {
  20739. this._knownBindings.add( bindings );
  20740. let uniformBuffers = 0;
  20741. let textures = 0;
  20742. for ( const bindGroup of bindings ) {
  20743. this.set( bindGroup, {
  20744. textures: textures,
  20745. uniformBuffers: uniformBuffers
  20746. } );
  20747. for ( const binding of bindGroup.bindings ) {
  20748. if ( binding.isUniformBuffer ) uniformBuffers ++;
  20749. if ( binding.isSampledTexture ) textures ++;
  20750. }
  20751. }
  20752. }
  20753. this.updateBindings( bindGroup, bindings );
  20754. }
  20755. updateBindings( bindGroup /*, bindings*/ ) {
  20756. const { gl } = this;
  20757. const bindGroupData = this.get( bindGroup );
  20758. let i = bindGroupData.uniformBuffers;
  20759. let t = bindGroupData.textures;
  20760. for ( const binding of bindGroup.bindings ) {
  20761. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  20762. const data = binding.buffer;
  20763. const bufferGPU = gl.createBuffer();
  20764. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  20765. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  20766. this.set( binding, {
  20767. index: i ++,
  20768. bufferGPU
  20769. } );
  20770. } else if ( binding.isSampledTexture ) {
  20771. const { textureGPU, glTextureType } = this.get( binding.texture );
  20772. this.set( binding, {
  20773. index: t ++,
  20774. textureGPU,
  20775. glTextureType
  20776. } );
  20777. }
  20778. }
  20779. }
  20780. updateBinding( binding ) {
  20781. const gl = this.gl;
  20782. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  20783. const bindingData = this.get( binding );
  20784. const bufferGPU = bindingData.bufferGPU;
  20785. const data = binding.buffer;
  20786. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  20787. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  20788. }
  20789. }
  20790. // attributes
  20791. createIndexAttribute( attribute ) {
  20792. const gl = this.gl;
  20793. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  20794. }
  20795. createAttribute( attribute ) {
  20796. if ( this.has( attribute ) ) return;
  20797. const gl = this.gl;
  20798. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  20799. }
  20800. createStorageAttribute( attribute ) {
  20801. if ( this.has( attribute ) ) return;
  20802. const gl = this.gl;
  20803. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  20804. }
  20805. updateAttribute( attribute ) {
  20806. this.attributeUtils.updateAttribute( attribute );
  20807. }
  20808. destroyAttribute( attribute ) {
  20809. this.attributeUtils.destroyAttribute( attribute );
  20810. }
  20811. updateSize() {
  20812. //console.warn( 'Abstract class.' );
  20813. }
  20814. hasFeature( name ) {
  20815. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  20816. const extensions = this.extensions;
  20817. for ( let i = 0; i < keysMatching.length; i ++ ) {
  20818. if ( extensions.has( keysMatching[ i ] ) ) return true;
  20819. }
  20820. return false;
  20821. }
  20822. getMaxAnisotropy() {
  20823. return this.capabilities.getMaxAnisotropy();
  20824. }
  20825. copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level ) {
  20826. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  20827. }
  20828. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  20829. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  20830. }
  20831. _setFramebuffer( descriptor ) {
  20832. const { gl, state } = this;
  20833. let currentFrameBuffer = null;
  20834. if ( descriptor.textures !== null ) {
  20835. const renderTarget = descriptor.renderTarget;
  20836. const renderTargetContextData = this.get( renderTarget );
  20837. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  20838. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  20839. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  20840. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  20841. const cacheKey = getCacheKey( descriptor );
  20842. let fb;
  20843. if ( isCube ) {
  20844. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  20845. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  20846. } else {
  20847. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  20848. fb = renderTargetContextData.framebuffers[ cacheKey ];
  20849. }
  20850. if ( fb === undefined ) {
  20851. fb = gl.createFramebuffer();
  20852. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  20853. const textures = descriptor.textures;
  20854. if ( isCube ) {
  20855. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  20856. const { textureGPU } = this.get( textures[ 0 ] );
  20857. const cubeFace = this.renderer._activeCubeFace;
  20858. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  20859. } else {
  20860. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  20861. for ( let i = 0; i < textures.length; i ++ ) {
  20862. const texture = textures[ i ];
  20863. const textureData = this.get( texture );
  20864. textureData.renderTarget = descriptor.renderTarget;
  20865. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  20866. const attachment = gl.COLOR_ATTACHMENT0 + i;
  20867. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  20868. }
  20869. state.drawBuffers( descriptor, fb );
  20870. }
  20871. if ( descriptor.depthTexture !== null ) {
  20872. const textureData = this.get( descriptor.depthTexture );
  20873. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  20874. textureData.renderTarget = descriptor.renderTarget;
  20875. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  20876. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  20877. }
  20878. }
  20879. if ( samples > 0 ) {
  20880. if ( msaaFb === undefined ) {
  20881. const invalidationArray = [];
  20882. msaaFb = gl.createFramebuffer();
  20883. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  20884. const msaaRenderbuffers = [];
  20885. const textures = descriptor.textures;
  20886. for ( let i = 0; i < textures.length; i ++ ) {
  20887. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  20888. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  20889. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  20890. if ( depthBuffer ) {
  20891. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  20892. invalidationArray.push( depthStyle );
  20893. }
  20894. const texture = descriptor.textures[ i ];
  20895. const textureData = this.get( texture );
  20896. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  20897. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  20898. }
  20899. renderTargetContextData.msaaFrameBuffer = msaaFb;
  20900. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  20901. if ( depthRenderbuffer === undefined ) {
  20902. depthRenderbuffer = gl.createRenderbuffer();
  20903. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor );
  20904. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  20905. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  20906. invalidationArray.push( depthStyle );
  20907. }
  20908. renderTargetContextData.invalidationArray = invalidationArray;
  20909. }
  20910. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  20911. } else {
  20912. currentFrameBuffer = fb;
  20913. }
  20914. }
  20915. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  20916. }
  20917. _getVaoKey( index, attributes ) {
  20918. let key = [];
  20919. if ( index !== null ) {
  20920. const indexData = this.get( index );
  20921. key += ':' + indexData.id;
  20922. }
  20923. for ( let i = 0; i < attributes.length; i ++ ) {
  20924. const attributeData = this.get( attributes[ i ] );
  20925. key += ':' + attributeData.id;
  20926. }
  20927. return key;
  20928. }
  20929. _createVao( index, attributes ) {
  20930. const { gl } = this;
  20931. const vaoGPU = gl.createVertexArray();
  20932. let key = '';
  20933. let staticVao = true;
  20934. gl.bindVertexArray( vaoGPU );
  20935. if ( index !== null ) {
  20936. const indexData = this.get( index );
  20937. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexData.bufferGPU );
  20938. key += ':' + indexData.id;
  20939. }
  20940. for ( let i = 0; i < attributes.length; i ++ ) {
  20941. const attribute = attributes[ i ];
  20942. const attributeData = this.get( attribute );
  20943. key += ':' + attributeData.id;
  20944. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  20945. gl.enableVertexAttribArray( i );
  20946. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false;
  20947. let stride, offset;
  20948. if ( attribute.isInterleavedBufferAttribute === true ) {
  20949. stride = attribute.data.stride * attributeData.bytesPerElement;
  20950. offset = attribute.offset * attributeData.bytesPerElement;
  20951. } else {
  20952. stride = 0;
  20953. offset = 0;
  20954. }
  20955. if ( attributeData.isInteger ) {
  20956. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  20957. } else {
  20958. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  20959. }
  20960. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  20961. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  20962. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  20963. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  20964. }
  20965. }
  20966. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  20967. this.vaoCache[ key ] = vaoGPU;
  20968. return { vaoGPU, staticVao };
  20969. }
  20970. _getTransformFeedback( transformBuffers ) {
  20971. let key = '';
  20972. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  20973. key += ':' + transformBuffers[ i ].id;
  20974. }
  20975. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  20976. if ( transformFeedbackGPU !== undefined ) {
  20977. return transformFeedbackGPU;
  20978. }
  20979. const { gl } = this;
  20980. transformFeedbackGPU = gl.createTransformFeedback();
  20981. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  20982. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  20983. const attributeData = transformBuffers[ i ];
  20984. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  20985. }
  20986. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  20987. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  20988. return transformFeedbackGPU;
  20989. }
  20990. _setupBindings( bindings, programGPU ) {
  20991. const gl = this.gl;
  20992. for ( const bindGroup of bindings ) {
  20993. for ( const binding of bindGroup.bindings ) {
  20994. const bindingData = this.get( binding );
  20995. const index = bindingData.index;
  20996. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  20997. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  20998. gl.uniformBlockBinding( programGPU, location, index );
  20999. } else if ( binding.isSampledTexture ) {
  21000. const location = gl.getUniformLocation( programGPU, binding.name );
  21001. gl.uniform1i( location, index );
  21002. }
  21003. }
  21004. }
  21005. }
  21006. _bindUniforms( bindings ) {
  21007. const { gl, state } = this;
  21008. for ( const bindGroup of bindings ) {
  21009. for ( const binding of bindGroup.bindings ) {
  21010. const bindingData = this.get( binding );
  21011. const index = bindingData.index;
  21012. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  21013. // TODO USE bindBufferRange to group multiple uniform buffers
  21014. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  21015. } else if ( binding.isSampledTexture ) {
  21016. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  21017. }
  21018. }
  21019. }
  21020. }
  21021. dispose() {
  21022. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  21023. }
  21024. }
  21025. const GPUPrimitiveTopology = {
  21026. PointList: 'point-list',
  21027. LineList: 'line-list',
  21028. LineStrip: 'line-strip',
  21029. TriangleList: 'triangle-list',
  21030. TriangleStrip: 'triangle-strip',
  21031. };
  21032. const GPUCompareFunction = {
  21033. Never: 'never',
  21034. Less: 'less',
  21035. Equal: 'equal',
  21036. LessEqual: 'less-equal',
  21037. Greater: 'greater',
  21038. NotEqual: 'not-equal',
  21039. GreaterEqual: 'greater-equal',
  21040. Always: 'always'
  21041. };
  21042. const GPUStoreOp = {
  21043. Store: 'store',
  21044. Discard: 'discard'
  21045. };
  21046. const GPULoadOp = {
  21047. Load: 'load',
  21048. Clear: 'clear'
  21049. };
  21050. const GPUFrontFace = {
  21051. CCW: 'ccw',
  21052. CW: 'cw'
  21053. };
  21054. const GPUCullMode = {
  21055. None: 'none',
  21056. Front: 'front',
  21057. Back: 'back'
  21058. };
  21059. const GPUIndexFormat = {
  21060. Uint16: 'uint16',
  21061. Uint32: 'uint32'
  21062. };
  21063. const GPUTextureFormat = {
  21064. // 8-bit formats
  21065. R8Unorm: 'r8unorm',
  21066. R8Snorm: 'r8snorm',
  21067. R8Uint: 'r8uint',
  21068. R8Sint: 'r8sint',
  21069. // 16-bit formats
  21070. R16Uint: 'r16uint',
  21071. R16Sint: 'r16sint',
  21072. R16Float: 'r16float',
  21073. RG8Unorm: 'rg8unorm',
  21074. RG8Snorm: 'rg8snorm',
  21075. RG8Uint: 'rg8uint',
  21076. RG8Sint: 'rg8sint',
  21077. // 32-bit formats
  21078. R32Uint: 'r32uint',
  21079. R32Sint: 'r32sint',
  21080. R32Float: 'r32float',
  21081. RG16Uint: 'rg16uint',
  21082. RG16Sint: 'rg16sint',
  21083. RG16Float: 'rg16float',
  21084. RGBA8Unorm: 'rgba8unorm',
  21085. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  21086. RGBA8Snorm: 'rgba8snorm',
  21087. RGBA8Uint: 'rgba8uint',
  21088. RGBA8Sint: 'rgba8sint',
  21089. BGRA8Unorm: 'bgra8unorm',
  21090. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  21091. // Packed 32-bit formats
  21092. RGB9E5UFloat: 'rgb9e5ufloat',
  21093. RGB10A2Unorm: 'rgb10a2unorm',
  21094. RG11B10uFloat: 'rgb10a2unorm',
  21095. // 64-bit formats
  21096. RG32Uint: 'rg32uint',
  21097. RG32Sint: 'rg32sint',
  21098. RG32Float: 'rg32float',
  21099. RGBA16Uint: 'rgba16uint',
  21100. RGBA16Sint: 'rgba16sint',
  21101. RGBA16Float: 'rgba16float',
  21102. // 128-bit formats
  21103. RGBA32Uint: 'rgba32uint',
  21104. RGBA32Sint: 'rgba32sint',
  21105. RGBA32Float: 'rgba32float',
  21106. // Depth and stencil formats
  21107. Stencil8: 'stencil8',
  21108. Depth16Unorm: 'depth16unorm',
  21109. Depth24Plus: 'depth24plus',
  21110. Depth24PlusStencil8: 'depth24plus-stencil8',
  21111. Depth32Float: 'depth32float',
  21112. // 'depth32float-stencil8' extension
  21113. Depth32FloatStencil8: 'depth32float-stencil8',
  21114. // BC compressed formats usable if 'texture-compression-bc' is both
  21115. // supported by the device/user agent and enabled in requestDevice.
  21116. BC1RGBAUnorm: 'bc1-rgba-unorm',
  21117. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  21118. BC2RGBAUnorm: 'bc2-rgba-unorm',
  21119. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  21120. BC3RGBAUnorm: 'bc3-rgba-unorm',
  21121. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  21122. BC4RUnorm: 'bc4-r-unorm',
  21123. BC4RSnorm: 'bc4-r-snorm',
  21124. BC5RGUnorm: 'bc5-rg-unorm',
  21125. BC5RGSnorm: 'bc5-rg-snorm',
  21126. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  21127. BC6HRGBFloat: 'bc6h-rgb-float',
  21128. BC7RGBAUnorm: 'bc7-rgba-unorm',
  21129. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  21130. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  21131. // supported by the device/user agent and enabled in requestDevice.
  21132. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  21133. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  21134. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  21135. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  21136. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  21137. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  21138. EACR11Unorm: 'eac-r11unorm',
  21139. EACR11Snorm: 'eac-r11snorm',
  21140. EACRG11Unorm: 'eac-rg11unorm',
  21141. EACRG11Snorm: 'eac-rg11snorm',
  21142. // ASTC compressed formats usable if 'texture-compression-astc' is both
  21143. // supported by the device/user agent and enabled in requestDevice.
  21144. ASTC4x4Unorm: 'astc-4x4-unorm',
  21145. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  21146. ASTC5x4Unorm: 'astc-5x4-unorm',
  21147. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  21148. ASTC5x5Unorm: 'astc-5x5-unorm',
  21149. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  21150. ASTC6x5Unorm: 'astc-6x5-unorm',
  21151. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  21152. ASTC6x6Unorm: 'astc-6x6-unorm',
  21153. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  21154. ASTC8x5Unorm: 'astc-8x5-unorm',
  21155. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  21156. ASTC8x6Unorm: 'astc-8x6-unorm',
  21157. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  21158. ASTC8x8Unorm: 'astc-8x8-unorm',
  21159. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  21160. ASTC10x5Unorm: 'astc-10x5-unorm',
  21161. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  21162. ASTC10x6Unorm: 'astc-10x6-unorm',
  21163. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  21164. ASTC10x8Unorm: 'astc-10x8-unorm',
  21165. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  21166. ASTC10x10Unorm: 'astc-10x10-unorm',
  21167. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  21168. ASTC12x10Unorm: 'astc-12x10-unorm',
  21169. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  21170. ASTC12x12Unorm: 'astc-12x12-unorm',
  21171. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  21172. };
  21173. const GPUAddressMode = {
  21174. ClampToEdge: 'clamp-to-edge',
  21175. Repeat: 'repeat',
  21176. MirrorRepeat: 'mirror-repeat'
  21177. };
  21178. const GPUFilterMode = {
  21179. Linear: 'linear',
  21180. Nearest: 'nearest'
  21181. };
  21182. const GPUBlendFactor = {
  21183. Zero: 'zero',
  21184. One: 'one',
  21185. Src: 'src',
  21186. OneMinusSrc: 'one-minus-src',
  21187. SrcAlpha: 'src-alpha',
  21188. OneMinusSrcAlpha: 'one-minus-src-alpha',
  21189. Dst: 'dst',
  21190. OneMinusDstColor: 'one-minus-dst',
  21191. DstAlpha: 'dst-alpha',
  21192. OneMinusDstAlpha: 'one-minus-dst-alpha',
  21193. SrcAlphaSaturated: 'src-alpha-saturated',
  21194. Constant: 'constant',
  21195. OneMinusConstant: 'one-minus-constant'
  21196. };
  21197. const GPUBlendOperation = {
  21198. Add: 'add',
  21199. Subtract: 'subtract',
  21200. ReverseSubtract: 'reverse-subtract',
  21201. Min: 'min',
  21202. Max: 'max'
  21203. };
  21204. const GPUColorWriteFlags = {
  21205. None: 0,
  21206. Red: 0x1,
  21207. Green: 0x2,
  21208. Blue: 0x4,
  21209. Alpha: 0x8,
  21210. All: 0xF
  21211. };
  21212. const GPUStencilOperation = {
  21213. Keep: 'keep',
  21214. Zero: 'zero',
  21215. Replace: 'replace',
  21216. Invert: 'invert',
  21217. IncrementClamp: 'increment-clamp',
  21218. DecrementClamp: 'decrement-clamp',
  21219. IncrementWrap: 'increment-wrap',
  21220. DecrementWrap: 'decrement-wrap'
  21221. };
  21222. const GPUBufferBindingType = {
  21223. Uniform: 'uniform',
  21224. Storage: 'storage',
  21225. ReadOnlyStorage: 'read-only-storage'
  21226. };
  21227. const GPUStorageTextureAccess = {
  21228. WriteOnly: 'write-only',
  21229. ReadOnly: 'read-only',
  21230. ReadWrite: 'read-write',
  21231. };
  21232. const GPUTextureSampleType = {
  21233. Float: 'float',
  21234. UnfilterableFloat: 'unfilterable-float',
  21235. Depth: 'depth',
  21236. SInt: 'sint',
  21237. UInt: 'uint'
  21238. };
  21239. const GPUTextureDimension = {
  21240. OneD: '1d',
  21241. TwoD: '2d',
  21242. ThreeD: '3d'
  21243. };
  21244. const GPUTextureViewDimension = {
  21245. OneD: '1d',
  21246. TwoD: '2d',
  21247. TwoDArray: '2d-array',
  21248. Cube: 'cube',
  21249. CubeArray: 'cube-array',
  21250. ThreeD: '3d'
  21251. };
  21252. const GPUTextureAspect = {
  21253. All: 'all',
  21254. StencilOnly: 'stencil-only',
  21255. DepthOnly: 'depth-only'
  21256. };
  21257. const GPUInputStepMode = {
  21258. Vertex: 'vertex',
  21259. Instance: 'instance'
  21260. };
  21261. const GPUFeatureName = {
  21262. DepthClipControl: 'depth-clip-control',
  21263. Depth32FloatStencil8: 'depth32float-stencil8',
  21264. TextureCompressionBC: 'texture-compression-bc',
  21265. TextureCompressionETC2: 'texture-compression-etc2',
  21266. TextureCompressionASTC: 'texture-compression-astc',
  21267. TimestampQuery: 'timestamp-query',
  21268. IndirectFirstInstance: 'indirect-first-instance',
  21269. ShaderF16: 'shader-f16',
  21270. RG11B10UFloat: 'rg11b10ufloat-renderable',
  21271. BGRA8UNormStorage: 'bgra8unorm-storage',
  21272. Float32Filterable: 'float32-filterable',
  21273. ClipDistances: 'clip-distances',
  21274. DualSourceBlending: 'dual-source-blending',
  21275. Subgroups: 'subgroups'
  21276. };
  21277. class Sampler extends Binding {
  21278. constructor( name, texture ) {
  21279. super( name );
  21280. this.texture = texture;
  21281. this.version = texture ? texture.version : 0;
  21282. this.isSampler = true;
  21283. }
  21284. }
  21285. class NodeSampler extends Sampler {
  21286. constructor( name, textureNode, groupNode ) {
  21287. super( name, textureNode ? textureNode.value : null );
  21288. this.textureNode = textureNode;
  21289. this.groupNode = groupNode;
  21290. }
  21291. update() {
  21292. this.texture = this.textureNode.value;
  21293. }
  21294. }
  21295. class StorageBuffer extends Buffer {
  21296. constructor( name, attribute ) {
  21297. super( name, attribute ? attribute.array : null );
  21298. this.attribute = attribute;
  21299. this.isStorageBuffer = true;
  21300. }
  21301. }
  21302. let _id = 0;
  21303. class NodeStorageBuffer extends StorageBuffer {
  21304. constructor( nodeUniform, groupNode ) {
  21305. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  21306. this.nodeUniform = nodeUniform;
  21307. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  21308. this.groupNode = groupNode;
  21309. }
  21310. get buffer() {
  21311. return this.nodeUniform.value;
  21312. }
  21313. }
  21314. class WebGPUTexturePassUtils extends DataMap {
  21315. constructor( device ) {
  21316. super();
  21317. this.device = device;
  21318. const mipmapVertexSource = `
  21319. struct VarysStruct {
  21320. @builtin( position ) Position: vec4<f32>,
  21321. @location( 0 ) vTex : vec2<f32>
  21322. };
  21323. @vertex
  21324. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  21325. var Varys : VarysStruct;
  21326. var pos = array< vec2<f32>, 4 >(
  21327. vec2<f32>( -1.0, 1.0 ),
  21328. vec2<f32>( 1.0, 1.0 ),
  21329. vec2<f32>( -1.0, -1.0 ),
  21330. vec2<f32>( 1.0, -1.0 )
  21331. );
  21332. var tex = array< vec2<f32>, 4 >(
  21333. vec2<f32>( 0.0, 0.0 ),
  21334. vec2<f32>( 1.0, 0.0 ),
  21335. vec2<f32>( 0.0, 1.0 ),
  21336. vec2<f32>( 1.0, 1.0 )
  21337. );
  21338. Varys.vTex = tex[ vertexIndex ];
  21339. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  21340. return Varys;
  21341. }
  21342. `;
  21343. const mipmapFragmentSource = `
  21344. @group( 0 ) @binding( 0 )
  21345. var imgSampler : sampler;
  21346. @group( 0 ) @binding( 1 )
  21347. var img : texture_2d<f32>;
  21348. @fragment
  21349. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  21350. return textureSample( img, imgSampler, vTex );
  21351. }
  21352. `;
  21353. const flipYFragmentSource = `
  21354. @group( 0 ) @binding( 0 )
  21355. var imgSampler : sampler;
  21356. @group( 0 ) @binding( 1 )
  21357. var img : texture_2d<f32>;
  21358. @fragment
  21359. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  21360. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  21361. }
  21362. `;
  21363. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  21364. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  21365. // We'll need a new pipeline for every texture format used.
  21366. this.transferPipelines = {};
  21367. this.flipYPipelines = {};
  21368. this.mipmapVertexShaderModule = device.createShaderModule( {
  21369. label: 'mipmapVertex',
  21370. code: mipmapVertexSource
  21371. } );
  21372. this.mipmapFragmentShaderModule = device.createShaderModule( {
  21373. label: 'mipmapFragment',
  21374. code: mipmapFragmentSource
  21375. } );
  21376. this.flipYFragmentShaderModule = device.createShaderModule( {
  21377. label: 'flipYFragment',
  21378. code: flipYFragmentSource
  21379. } );
  21380. }
  21381. getTransferPipeline( format ) {
  21382. let pipeline = this.transferPipelines[ format ];
  21383. if ( pipeline === undefined ) {
  21384. pipeline = this.device.createRenderPipeline( {
  21385. label: `mipmap-${ format }`,
  21386. vertex: {
  21387. module: this.mipmapVertexShaderModule,
  21388. entryPoint: 'main'
  21389. },
  21390. fragment: {
  21391. module: this.mipmapFragmentShaderModule,
  21392. entryPoint: 'main',
  21393. targets: [ { format } ]
  21394. },
  21395. primitive: {
  21396. topology: GPUPrimitiveTopology.TriangleStrip,
  21397. stripIndexFormat: GPUIndexFormat.Uint32
  21398. },
  21399. layout: 'auto'
  21400. } );
  21401. this.transferPipelines[ format ] = pipeline;
  21402. }
  21403. return pipeline;
  21404. }
  21405. getFlipYPipeline( format ) {
  21406. let pipeline = this.flipYPipelines[ format ];
  21407. if ( pipeline === undefined ) {
  21408. pipeline = this.device.createRenderPipeline( {
  21409. label: `flipY-${ format }`,
  21410. vertex: {
  21411. module: this.mipmapVertexShaderModule,
  21412. entryPoint: 'main'
  21413. },
  21414. fragment: {
  21415. module: this.flipYFragmentShaderModule,
  21416. entryPoint: 'main',
  21417. targets: [ { format } ]
  21418. },
  21419. primitive: {
  21420. topology: GPUPrimitiveTopology.TriangleStrip,
  21421. stripIndexFormat: GPUIndexFormat.Uint32
  21422. },
  21423. layout: 'auto'
  21424. } );
  21425. this.flipYPipelines[ format ] = pipeline;
  21426. }
  21427. return pipeline;
  21428. }
  21429. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  21430. const format = textureGPUDescriptor.format;
  21431. const { width, height } = textureGPUDescriptor.size;
  21432. const transferPipeline = this.getTransferPipeline( format );
  21433. const flipYPipeline = this.getFlipYPipeline( format );
  21434. const tempTexture = this.device.createTexture( {
  21435. size: { width, height, depthOrArrayLayers: 1 },
  21436. format,
  21437. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  21438. } );
  21439. const srcView = textureGPU.createView( {
  21440. baseMipLevel: 0,
  21441. mipLevelCount: 1,
  21442. dimension: GPUTextureViewDimension.TwoD,
  21443. baseArrayLayer
  21444. } );
  21445. const dstView = tempTexture.createView( {
  21446. baseMipLevel: 0,
  21447. mipLevelCount: 1,
  21448. dimension: GPUTextureViewDimension.TwoD,
  21449. baseArrayLayer: 0
  21450. } );
  21451. const commandEncoder = this.device.createCommandEncoder( {} );
  21452. const pass = ( pipeline, sourceView, destinationView ) => {
  21453. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  21454. const bindGroup = this.device.createBindGroup( {
  21455. layout: bindGroupLayout,
  21456. entries: [ {
  21457. binding: 0,
  21458. resource: this.flipYSampler
  21459. }, {
  21460. binding: 1,
  21461. resource: sourceView
  21462. } ]
  21463. } );
  21464. const passEncoder = commandEncoder.beginRenderPass( {
  21465. colorAttachments: [ {
  21466. view: destinationView,
  21467. loadOp: GPULoadOp.Clear,
  21468. storeOp: GPUStoreOp.Store,
  21469. clearValue: [ 0, 0, 0, 0 ]
  21470. } ]
  21471. } );
  21472. passEncoder.setPipeline( pipeline );
  21473. passEncoder.setBindGroup( 0, bindGroup );
  21474. passEncoder.draw( 4, 1, 0, 0 );
  21475. passEncoder.end();
  21476. };
  21477. pass( transferPipeline, srcView, dstView );
  21478. pass( flipYPipeline, dstView, srcView );
  21479. this.device.queue.submit( [ commandEncoder.finish() ] );
  21480. tempTexture.destroy();
  21481. }
  21482. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  21483. const textureData = this.get( textureGPU );
  21484. if ( textureData.useCount === undefined ) {
  21485. textureData.useCount = 0;
  21486. textureData.layers = [];
  21487. }
  21488. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  21489. const commandEncoder = this.device.createCommandEncoder( {} );
  21490. this._mipmapRunBundles( commandEncoder, passes );
  21491. this.device.queue.submit( [ commandEncoder.finish() ] );
  21492. if ( textureData.useCount !== 0 ) textureData.layers[ baseArrayLayer ] = passes;
  21493. textureData.useCount ++;
  21494. }
  21495. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  21496. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  21497. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  21498. let srcView = textureGPU.createView( {
  21499. baseMipLevel: 0,
  21500. mipLevelCount: 1,
  21501. dimension: GPUTextureViewDimension.TwoD,
  21502. baseArrayLayer
  21503. } );
  21504. const passes = [];
  21505. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  21506. const bindGroup = this.device.createBindGroup( {
  21507. layout: bindGroupLayout,
  21508. entries: [ {
  21509. binding: 0,
  21510. resource: this.mipmapSampler
  21511. }, {
  21512. binding: 1,
  21513. resource: srcView
  21514. } ]
  21515. } );
  21516. const dstView = textureGPU.createView( {
  21517. baseMipLevel: i,
  21518. mipLevelCount: 1,
  21519. dimension: GPUTextureViewDimension.TwoD,
  21520. baseArrayLayer
  21521. } );
  21522. const passDescriptor = {
  21523. colorAttachments: [ {
  21524. view: dstView,
  21525. loadOp: GPULoadOp.Clear,
  21526. storeOp: GPUStoreOp.Store,
  21527. clearValue: [ 0, 0, 0, 0 ]
  21528. } ]
  21529. };
  21530. const passEncoder = this.device.createRenderBundleEncoder( {
  21531. colorFormats: [ textureGPUDescriptor.format ]
  21532. } );
  21533. passEncoder.setPipeline( pipeline );
  21534. passEncoder.setBindGroup( 0, bindGroup );
  21535. passEncoder.draw( 4, 1, 0, 0 );
  21536. passes.push( {
  21537. renderBundles: [ passEncoder.finish() ],
  21538. passDescriptor
  21539. } );
  21540. srcView = dstView;
  21541. }
  21542. return passes;
  21543. }
  21544. _mipmapRunBundles( commandEncoder, passes ) {
  21545. const levels = passes.length;
  21546. for ( let i = 0; i < levels; i ++ ) {
  21547. const pass = passes[ i ];
  21548. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  21549. passEncoder.executeBundles( pass.renderBundles );
  21550. passEncoder.end();
  21551. }
  21552. }
  21553. }
  21554. const _compareToWebGPU = {
  21555. [ NeverCompare ]: 'never',
  21556. [ LessCompare ]: 'less',
  21557. [ EqualCompare ]: 'equal',
  21558. [ LessEqualCompare ]: 'less-equal',
  21559. [ GreaterCompare ]: 'greater',
  21560. [ GreaterEqualCompare ]: 'greater-equal',
  21561. [ AlwaysCompare ]: 'always',
  21562. [ NotEqualCompare ]: 'not-equal'
  21563. };
  21564. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  21565. class WebGPUTextureUtils {
  21566. constructor( backend ) {
  21567. this.backend = backend;
  21568. this._passUtils = null;
  21569. this.defaultTexture = {};
  21570. this.defaultCubeTexture = {};
  21571. this.defaultVideoFrame = null;
  21572. this.colorBuffer = null;
  21573. this.depthTexture = new DepthTexture();
  21574. this.depthTexture.name = 'depthBuffer';
  21575. }
  21576. createSampler( texture ) {
  21577. const backend = this.backend;
  21578. const device = backend.device;
  21579. const textureGPU = backend.get( texture );
  21580. const samplerDescriptorGPU = {
  21581. addressModeU: this._convertAddressMode( texture.wrapS ),
  21582. addressModeV: this._convertAddressMode( texture.wrapT ),
  21583. addressModeW: this._convertAddressMode( texture.wrapR ),
  21584. magFilter: this._convertFilterMode( texture.magFilter ),
  21585. minFilter: this._convertFilterMode( texture.minFilter ),
  21586. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  21587. maxAnisotropy: 1
  21588. };
  21589. // anisotropy can only be used when all filter modes are set to linear.
  21590. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  21591. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  21592. }
  21593. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  21594. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  21595. }
  21596. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  21597. }
  21598. createDefaultTexture( texture ) {
  21599. let textureGPU;
  21600. const format = getFormat( texture );
  21601. if ( texture.isCubeTexture ) {
  21602. textureGPU = this._getDefaultCubeTextureGPU( format );
  21603. } else if ( texture.isVideoTexture ) {
  21604. this.backend.get( texture ).externalTexture = this._getDefaultVideoFrame();
  21605. } else {
  21606. textureGPU = this._getDefaultTextureGPU( format );
  21607. }
  21608. this.backend.get( texture ).texture = textureGPU;
  21609. }
  21610. createTexture( texture, options = {} ) {
  21611. const backend = this.backend;
  21612. const textureData = backend.get( texture );
  21613. if ( textureData.initialized ) {
  21614. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  21615. }
  21616. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  21617. if ( options.levels === undefined ) options.levels = 1;
  21618. if ( options.depth === undefined ) options.depth = 1;
  21619. const { width, height, depth, levels } = options;
  21620. if ( texture.isFramebufferTexture ) {
  21621. if ( options.renderTarget ) {
  21622. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  21623. } else {
  21624. options.format = this.backend.utils.getPreferredCanvasFormat();
  21625. }
  21626. }
  21627. const dimension = this._getDimension( texture );
  21628. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  21629. textureData.format = format;
  21630. let sampleCount = options.sampleCount !== undefined ? options.sampleCount : 1;
  21631. sampleCount = backend.utils.getSampleCount( sampleCount );
  21632. const primarySampleCount = texture.isRenderTargetTexture && ! texture.isMultisampleRenderTargetTexture ? 1 : sampleCount;
  21633. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  21634. if ( texture.isStorageTexture === true ) {
  21635. usage |= GPUTextureUsage.STORAGE_BINDING;
  21636. }
  21637. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true ) {
  21638. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  21639. }
  21640. const textureDescriptorGPU = {
  21641. label: texture.name,
  21642. size: {
  21643. width: width,
  21644. height: height,
  21645. depthOrArrayLayers: depth,
  21646. },
  21647. mipLevelCount: levels,
  21648. sampleCount: primarySampleCount,
  21649. dimension: dimension,
  21650. format: format,
  21651. usage: usage
  21652. };
  21653. // texture creation
  21654. if ( texture.isVideoTexture ) {
  21655. const video = texture.source.data;
  21656. const videoFrame = new VideoFrame( video );
  21657. textureDescriptorGPU.size.width = videoFrame.displayWidth;
  21658. textureDescriptorGPU.size.height = videoFrame.displayHeight;
  21659. videoFrame.close();
  21660. textureData.externalTexture = video;
  21661. } else {
  21662. if ( format === undefined ) {
  21663. console.warn( 'WebGPURenderer: Texture format not supported.' );
  21664. return this.createDefaultTexture( texture );
  21665. }
  21666. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  21667. }
  21668. if ( texture.isRenderTargetTexture && sampleCount > 1 && ! texture.isMultisampleRenderTargetTexture ) {
  21669. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  21670. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  21671. msaaTextureDescriptorGPU.sampleCount = sampleCount;
  21672. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  21673. }
  21674. textureData.initialized = true;
  21675. textureData.textureDescriptorGPU = textureDescriptorGPU;
  21676. }
  21677. destroyTexture( texture ) {
  21678. const backend = this.backend;
  21679. const textureData = backend.get( texture );
  21680. if ( textureData.texture !== undefined ) textureData.texture.destroy();
  21681. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  21682. backend.delete( texture );
  21683. }
  21684. destroySampler( texture ) {
  21685. const backend = this.backend;
  21686. const textureData = backend.get( texture );
  21687. delete textureData.sampler;
  21688. }
  21689. generateMipmaps( texture ) {
  21690. const textureData = this.backend.get( texture );
  21691. if ( texture.isCubeTexture ) {
  21692. for ( let i = 0; i < 6; i ++ ) {
  21693. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  21694. }
  21695. } else {
  21696. const depth = texture.image.depth || 1;
  21697. for ( let i = 0; i < depth; i ++ ) {
  21698. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  21699. }
  21700. }
  21701. }
  21702. getColorBuffer() {
  21703. if ( this.colorBuffer ) this.colorBuffer.destroy();
  21704. const backend = this.backend;
  21705. const { width, height } = backend.getDrawingBufferSize();
  21706. this.colorBuffer = backend.device.createTexture( {
  21707. label: 'colorBuffer',
  21708. size: {
  21709. width: width,
  21710. height: height,
  21711. depthOrArrayLayers: 1
  21712. },
  21713. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  21714. format: backend.utils.getPreferredCanvasFormat(),
  21715. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  21716. } );
  21717. return this.colorBuffer;
  21718. }
  21719. getDepthBuffer( depth = true, stencil = false ) {
  21720. const backend = this.backend;
  21721. const { width, height } = backend.getDrawingBufferSize();
  21722. const depthTexture = this.depthTexture;
  21723. const depthTextureGPU = backend.get( depthTexture ).texture;
  21724. let format, type;
  21725. if ( stencil ) {
  21726. format = DepthStencilFormat;
  21727. type = UnsignedInt248Type;
  21728. } else if ( depth ) {
  21729. format = DepthFormat;
  21730. type = UnsignedIntType;
  21731. }
  21732. if ( depthTextureGPU !== undefined ) {
  21733. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  21734. return depthTextureGPU;
  21735. }
  21736. this.destroyTexture( depthTexture );
  21737. }
  21738. depthTexture.name = 'depthBuffer';
  21739. depthTexture.format = format;
  21740. depthTexture.type = type;
  21741. depthTexture.image.width = width;
  21742. depthTexture.image.height = height;
  21743. this.createTexture( depthTexture, { sampleCount: backend.utils.getSampleCount( backend.renderer.samples ), width, height } );
  21744. return backend.get( depthTexture ).texture;
  21745. }
  21746. updateTexture( texture, options ) {
  21747. const textureData = this.backend.get( texture );
  21748. const { textureDescriptorGPU } = textureData;
  21749. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  21750. return;
  21751. // transfer texture data
  21752. if ( texture.isDataTexture ) {
  21753. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  21754. } else if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  21755. for ( let i = 0; i < options.image.depth; i ++ ) {
  21756. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  21757. }
  21758. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  21759. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  21760. } else if ( texture.isCubeTexture ) {
  21761. this._copyCubeMapToTexture( options.images, textureData.texture, textureDescriptorGPU, texture.flipY );
  21762. } else if ( texture.isVideoTexture ) {
  21763. const video = texture.source.data;
  21764. textureData.externalTexture = video;
  21765. } else {
  21766. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  21767. }
  21768. //
  21769. textureData.version = texture.version;
  21770. if ( texture.onUpdate ) texture.onUpdate( texture );
  21771. }
  21772. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  21773. const device = this.backend.device;
  21774. const textureData = this.backend.get( texture );
  21775. const textureGPU = textureData.texture;
  21776. const format = textureData.textureDescriptorGPU.format;
  21777. const bytesPerTexel = this._getBytesPerTexel( format );
  21778. let bytesPerRow = width * bytesPerTexel;
  21779. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  21780. const readBuffer = device.createBuffer(
  21781. {
  21782. size: width * height * bytesPerTexel,
  21783. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  21784. }
  21785. );
  21786. const encoder = device.createCommandEncoder();
  21787. encoder.copyTextureToBuffer(
  21788. {
  21789. texture: textureGPU,
  21790. origin: { x, y, z: faceIndex },
  21791. },
  21792. {
  21793. buffer: readBuffer,
  21794. bytesPerRow: bytesPerRow
  21795. },
  21796. {
  21797. width: width,
  21798. height: height
  21799. }
  21800. );
  21801. const typedArrayType = this._getTypedArrayType( format );
  21802. device.queue.submit( [ encoder.finish() ] );
  21803. await readBuffer.mapAsync( GPUMapMode.READ );
  21804. const buffer = readBuffer.getMappedRange();
  21805. return new typedArrayType( buffer );
  21806. }
  21807. _isEnvironmentTexture( texture ) {
  21808. const mapping = texture.mapping;
  21809. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  21810. }
  21811. _getDefaultTextureGPU( format ) {
  21812. let defaultTexture = this.defaultTexture[ format ];
  21813. if ( defaultTexture === undefined ) {
  21814. const texture = new Texture();
  21815. texture.minFilter = NearestFilter;
  21816. texture.magFilter = NearestFilter;
  21817. this.createTexture( texture, { width: 1, height: 1, format } );
  21818. this.defaultTexture[ format ] = defaultTexture = texture;
  21819. }
  21820. return this.backend.get( defaultTexture ).texture;
  21821. }
  21822. _getDefaultCubeTextureGPU( format ) {
  21823. let defaultCubeTexture = this.defaultTexture[ format ];
  21824. if ( defaultCubeTexture === undefined ) {
  21825. const texture = new CubeTexture();
  21826. texture.minFilter = NearestFilter;
  21827. texture.magFilter = NearestFilter;
  21828. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  21829. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  21830. }
  21831. return this.backend.get( defaultCubeTexture ).texture;
  21832. }
  21833. _getDefaultVideoFrame() {
  21834. let defaultVideoFrame = this.defaultVideoFrame;
  21835. if ( defaultVideoFrame === null ) {
  21836. const init = {
  21837. timestamp: 0,
  21838. codedWidth: 1,
  21839. codedHeight: 1,
  21840. format: 'RGBA',
  21841. };
  21842. this.defaultVideoFrame = defaultVideoFrame = new VideoFrame( new Uint8Array( [ 0, 0, 0, 0xff ] ), init );
  21843. }
  21844. return defaultVideoFrame;
  21845. }
  21846. _copyCubeMapToTexture( images, textureGPU, textureDescriptorGPU, flipY ) {
  21847. for ( let i = 0; i < 6; i ++ ) {
  21848. const image = images[ i ];
  21849. const flipIndex = flipY === true ? _flipMap[ i ] : i;
  21850. if ( image.isDataTexture ) {
  21851. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  21852. } else {
  21853. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  21854. }
  21855. }
  21856. }
  21857. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY ) {
  21858. const device = this.backend.device;
  21859. device.queue.copyExternalImageToTexture(
  21860. {
  21861. source: image
  21862. }, {
  21863. texture: textureGPU,
  21864. mipLevel: 0,
  21865. origin: { x: 0, y: 0, z: originDepth }
  21866. }, {
  21867. width: image.width,
  21868. height: image.height,
  21869. depthOrArrayLayers: 1
  21870. }
  21871. );
  21872. if ( flipY === true ) {
  21873. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  21874. }
  21875. }
  21876. _getPassUtils() {
  21877. let passUtils = this._passUtils;
  21878. if ( passUtils === null ) {
  21879. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  21880. }
  21881. return passUtils;
  21882. }
  21883. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  21884. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  21885. }
  21886. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  21887. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  21888. }
  21889. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0 ) {
  21890. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  21891. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  21892. const device = this.backend.device;
  21893. const data = image.data;
  21894. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  21895. const bytesPerRow = image.width * bytesPerTexel;
  21896. device.queue.writeTexture(
  21897. {
  21898. texture: textureGPU,
  21899. mipLevel: 0,
  21900. origin: { x: 0, y: 0, z: originDepth }
  21901. },
  21902. data,
  21903. {
  21904. offset: image.width * image.height * bytesPerTexel * depth,
  21905. bytesPerRow
  21906. },
  21907. {
  21908. width: image.width,
  21909. height: image.height,
  21910. depthOrArrayLayers: 1
  21911. } );
  21912. if ( flipY === true ) {
  21913. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  21914. }
  21915. }
  21916. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  21917. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  21918. const device = this.backend.device;
  21919. const blockData = this._getBlockData( textureDescriptorGPU.format );
  21920. const isTextureArray = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  21921. for ( let i = 0; i < mipmaps.length; i ++ ) {
  21922. const mipmap = mipmaps[ i ];
  21923. const width = mipmap.width;
  21924. const height = mipmap.height;
  21925. const depth = isTextureArray ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  21926. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  21927. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  21928. for ( let j = 0; j < depth; j ++ ) {
  21929. device.queue.writeTexture(
  21930. {
  21931. texture: textureGPU,
  21932. mipLevel: i,
  21933. origin: { x: 0, y: 0, z: j }
  21934. },
  21935. mipmap.data,
  21936. {
  21937. offset: j * bytesPerImage,
  21938. bytesPerRow,
  21939. rowsPerImage: Math.ceil( height / blockData.height )
  21940. },
  21941. {
  21942. width: Math.ceil( width / blockData.width ) * blockData.width,
  21943. height: Math.ceil( height / blockData.height ) * blockData.height,
  21944. depthOrArrayLayers: 1
  21945. }
  21946. );
  21947. }
  21948. }
  21949. }
  21950. _getBlockData( format ) {
  21951. // this method is only relevant for compressed texture formats
  21952. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  21953. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  21954. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  21955. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSNorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  21956. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  21957. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  21958. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  21959. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  21960. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  21961. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  21962. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  21963. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  21964. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  21965. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  21966. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  21967. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  21968. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  21969. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  21970. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  21971. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  21972. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  21973. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  21974. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  21975. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  21976. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  21977. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  21978. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  21979. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  21980. }
  21981. _convertAddressMode( value ) {
  21982. let addressMode = GPUAddressMode.ClampToEdge;
  21983. if ( value === RepeatWrapping ) {
  21984. addressMode = GPUAddressMode.Repeat;
  21985. } else if ( value === MirroredRepeatWrapping ) {
  21986. addressMode = GPUAddressMode.MirrorRepeat;
  21987. }
  21988. return addressMode;
  21989. }
  21990. _convertFilterMode( value ) {
  21991. let filterMode = GPUFilterMode.Linear;
  21992. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  21993. filterMode = GPUFilterMode.Nearest;
  21994. }
  21995. return filterMode;
  21996. }
  21997. _getBytesPerTexel( format ) {
  21998. // 8-bit formats
  21999. if ( format === GPUTextureFormat.R8Unorm ||
  22000. format === GPUTextureFormat.R8Snorm ||
  22001. format === GPUTextureFormat.R8Uint ||
  22002. format === GPUTextureFormat.R8Sint ) return 1;
  22003. // 16-bit formats
  22004. if ( format === GPUTextureFormat.R16Uint ||
  22005. format === GPUTextureFormat.R16Sint ||
  22006. format === GPUTextureFormat.R16Float ||
  22007. format === GPUTextureFormat.RG8Unorm ||
  22008. format === GPUTextureFormat.RG8Snorm ||
  22009. format === GPUTextureFormat.RG8Uint ||
  22010. format === GPUTextureFormat.RG8Sint ) return 2;
  22011. // 32-bit formats
  22012. if ( format === GPUTextureFormat.R32Uint ||
  22013. format === GPUTextureFormat.R32Sint ||
  22014. format === GPUTextureFormat.R32Float ||
  22015. format === GPUTextureFormat.RG16Uint ||
  22016. format === GPUTextureFormat.RG16Sint ||
  22017. format === GPUTextureFormat.RG16Float ||
  22018. format === GPUTextureFormat.RGBA8Unorm ||
  22019. format === GPUTextureFormat.RGBA8UnormSRGB ||
  22020. format === GPUTextureFormat.RGBA8Snorm ||
  22021. format === GPUTextureFormat.RGBA8Uint ||
  22022. format === GPUTextureFormat.RGBA8Sint ||
  22023. format === GPUTextureFormat.BGRA8Unorm ||
  22024. format === GPUTextureFormat.BGRA8UnormSRGB ||
  22025. // Packed 32-bit formats
  22026. format === GPUTextureFormat.RGB9E5UFloat ||
  22027. format === GPUTextureFormat.RGB10A2Unorm ||
  22028. format === GPUTextureFormat.RG11B10UFloat ||
  22029. format === GPUTextureFormat.Depth32Float ||
  22030. format === GPUTextureFormat.Depth24Plus ||
  22031. format === GPUTextureFormat.Depth24PlusStencil8 ||
  22032. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  22033. // 64-bit formats
  22034. if ( format === GPUTextureFormat.RG32Uint ||
  22035. format === GPUTextureFormat.RG32Sint ||
  22036. format === GPUTextureFormat.RG32Float ||
  22037. format === GPUTextureFormat.RGBA16Uint ||
  22038. format === GPUTextureFormat.RGBA16Sint ||
  22039. format === GPUTextureFormat.RGBA16Float ) return 8;
  22040. // 128-bit formats
  22041. if ( format === GPUTextureFormat.RGBA32Uint ||
  22042. format === GPUTextureFormat.RGBA32Sint ||
  22043. format === GPUTextureFormat.RGBA32Float ) return 16;
  22044. }
  22045. _getTypedArrayType( format ) {
  22046. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  22047. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  22048. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  22049. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  22050. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  22051. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  22052. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  22053. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  22054. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  22055. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  22056. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  22057. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  22058. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  22059. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  22060. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  22061. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  22062. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  22063. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  22064. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  22065. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  22066. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  22067. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  22068. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  22069. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  22070. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  22071. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  22072. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  22073. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  22074. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  22075. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  22076. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  22077. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  22078. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  22079. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  22080. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  22081. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  22082. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  22083. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  22084. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  22085. }
  22086. _getDimension( texture ) {
  22087. let dimension;
  22088. if ( texture.isData3DTexture ) {
  22089. dimension = GPUTextureDimension.ThreeD;
  22090. } else {
  22091. dimension = GPUTextureDimension.TwoD;
  22092. }
  22093. return dimension;
  22094. }
  22095. }
  22096. function getFormat( texture, device = null ) {
  22097. const format = texture.format;
  22098. const type = texture.type;
  22099. const colorSpace = texture.colorSpace;
  22100. let formatGPU;
  22101. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  22102. switch ( format ) {
  22103. case RGBA_S3TC_DXT1_Format:
  22104. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  22105. break;
  22106. case RGBA_S3TC_DXT3_Format:
  22107. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  22108. break;
  22109. case RGBA_S3TC_DXT5_Format:
  22110. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  22111. break;
  22112. case RGB_ETC2_Format:
  22113. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  22114. break;
  22115. case RGBA_ETC2_EAC_Format:
  22116. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  22117. break;
  22118. case RGBA_ASTC_4x4_Format:
  22119. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  22120. break;
  22121. case RGBA_ASTC_5x4_Format:
  22122. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  22123. break;
  22124. case RGBA_ASTC_5x5_Format:
  22125. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  22126. break;
  22127. case RGBA_ASTC_6x5_Format:
  22128. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  22129. break;
  22130. case RGBA_ASTC_6x6_Format:
  22131. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  22132. break;
  22133. case RGBA_ASTC_8x5_Format:
  22134. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  22135. break;
  22136. case RGBA_ASTC_8x6_Format:
  22137. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  22138. break;
  22139. case RGBA_ASTC_8x8_Format:
  22140. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  22141. break;
  22142. case RGBA_ASTC_10x5_Format:
  22143. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  22144. break;
  22145. case RGBA_ASTC_10x6_Format:
  22146. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  22147. break;
  22148. case RGBA_ASTC_10x8_Format:
  22149. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  22150. break;
  22151. case RGBA_ASTC_10x10_Format:
  22152. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  22153. break;
  22154. case RGBA_ASTC_12x10_Format:
  22155. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  22156. break;
  22157. case RGBA_ASTC_12x12_Format:
  22158. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  22159. break;
  22160. case RGBAFormat:
  22161. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  22162. break;
  22163. default:
  22164. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  22165. }
  22166. } else {
  22167. switch ( format ) {
  22168. case RGBAFormat:
  22169. switch ( type ) {
  22170. case ByteType:
  22171. formatGPU = GPUTextureFormat.RGBA8Snorm;
  22172. break;
  22173. case ShortType:
  22174. formatGPU = GPUTextureFormat.RGBA16Sint;
  22175. break;
  22176. case UnsignedShortType:
  22177. formatGPU = GPUTextureFormat.RGBA16Uint;
  22178. break;
  22179. case UnsignedIntType:
  22180. formatGPU = GPUTextureFormat.RGBA32Uint;
  22181. break;
  22182. case IntType:
  22183. formatGPU = GPUTextureFormat.RGBA32Sint;
  22184. break;
  22185. case UnsignedByteType:
  22186. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  22187. break;
  22188. case HalfFloatType:
  22189. formatGPU = GPUTextureFormat.RGBA16Float;
  22190. break;
  22191. case FloatType:
  22192. formatGPU = GPUTextureFormat.RGBA32Float;
  22193. break;
  22194. default:
  22195. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  22196. }
  22197. break;
  22198. case RGBFormat:
  22199. switch ( type ) {
  22200. case UnsignedInt5999Type:
  22201. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  22202. break;
  22203. default:
  22204. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  22205. }
  22206. break;
  22207. case RedFormat:
  22208. switch ( type ) {
  22209. case ByteType:
  22210. formatGPU = GPUTextureFormat.R8Snorm;
  22211. break;
  22212. case ShortType:
  22213. formatGPU = GPUTextureFormat.R16Sint;
  22214. break;
  22215. case UnsignedShortType:
  22216. formatGPU = GPUTextureFormat.R16Uint;
  22217. break;
  22218. case UnsignedIntType:
  22219. formatGPU = GPUTextureFormat.R32Uint;
  22220. break;
  22221. case IntType:
  22222. formatGPU = GPUTextureFormat.R32Sint;
  22223. break;
  22224. case UnsignedByteType:
  22225. formatGPU = GPUTextureFormat.R8Unorm;
  22226. break;
  22227. case HalfFloatType:
  22228. formatGPU = GPUTextureFormat.R16Float;
  22229. break;
  22230. case FloatType:
  22231. formatGPU = GPUTextureFormat.R32Float;
  22232. break;
  22233. default:
  22234. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  22235. }
  22236. break;
  22237. case RGFormat:
  22238. switch ( type ) {
  22239. case ByteType:
  22240. formatGPU = GPUTextureFormat.RG8Snorm;
  22241. break;
  22242. case ShortType:
  22243. formatGPU = GPUTextureFormat.RG16Sint;
  22244. break;
  22245. case UnsignedShortType:
  22246. formatGPU = GPUTextureFormat.RG16Uint;
  22247. break;
  22248. case UnsignedIntType:
  22249. formatGPU = GPUTextureFormat.RG32Uint;
  22250. break;
  22251. case IntType:
  22252. formatGPU = GPUTextureFormat.RG32Sint;
  22253. break;
  22254. case UnsignedByteType:
  22255. formatGPU = GPUTextureFormat.RG8Unorm;
  22256. break;
  22257. case HalfFloatType:
  22258. formatGPU = GPUTextureFormat.RG16Float;
  22259. break;
  22260. case FloatType:
  22261. formatGPU = GPUTextureFormat.RG32Float;
  22262. break;
  22263. default:
  22264. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  22265. }
  22266. break;
  22267. case DepthFormat:
  22268. switch ( type ) {
  22269. case UnsignedShortType:
  22270. formatGPU = GPUTextureFormat.Depth16Unorm;
  22271. break;
  22272. case UnsignedIntType:
  22273. formatGPU = GPUTextureFormat.Depth24Plus;
  22274. break;
  22275. case FloatType:
  22276. formatGPU = GPUTextureFormat.Depth32Float;
  22277. break;
  22278. default:
  22279. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  22280. }
  22281. break;
  22282. case DepthStencilFormat:
  22283. switch ( type ) {
  22284. case UnsignedInt248Type:
  22285. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  22286. break;
  22287. case FloatType:
  22288. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  22289. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  22290. }
  22291. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  22292. break;
  22293. default:
  22294. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  22295. }
  22296. break;
  22297. case RedIntegerFormat:
  22298. switch ( type ) {
  22299. case IntType:
  22300. formatGPU = GPUTextureFormat.R32Sint;
  22301. break;
  22302. case UnsignedIntType:
  22303. formatGPU = GPUTextureFormat.R32Uint;
  22304. break;
  22305. default:
  22306. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  22307. }
  22308. break;
  22309. case RGIntegerFormat:
  22310. switch ( type ) {
  22311. case IntType:
  22312. formatGPU = GPUTextureFormat.RG32Sint;
  22313. break;
  22314. case UnsignedIntType:
  22315. formatGPU = GPUTextureFormat.RG32Uint;
  22316. break;
  22317. default:
  22318. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  22319. }
  22320. break;
  22321. case RGBAIntegerFormat:
  22322. switch ( type ) {
  22323. case IntType:
  22324. formatGPU = GPUTextureFormat.RGBA32Sint;
  22325. break;
  22326. case UnsignedIntType:
  22327. formatGPU = GPUTextureFormat.RGBA32Uint;
  22328. break;
  22329. default:
  22330. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  22331. }
  22332. break;
  22333. default:
  22334. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  22335. }
  22336. }
  22337. return formatGPU;
  22338. }
  22339. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  22340. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  22341. const wgslTypeLib$1 = {
  22342. 'f32': 'float',
  22343. 'i32': 'int',
  22344. 'u32': 'uint',
  22345. 'bool': 'bool',
  22346. 'vec2<f32>': 'vec2',
  22347. 'vec2<i32>': 'ivec2',
  22348. 'vec2<u32>': 'uvec2',
  22349. 'vec2<bool>': 'bvec2',
  22350. 'vec2f': 'vec2',
  22351. 'vec2i': 'ivec2',
  22352. 'vec2u': 'uvec2',
  22353. 'vec2b': 'bvec2',
  22354. 'vec3<f32>': 'vec3',
  22355. 'vec3<i32>': 'ivec3',
  22356. 'vec3<u32>': 'uvec3',
  22357. 'vec3<bool>': 'bvec3',
  22358. 'vec3f': 'vec3',
  22359. 'vec3i': 'ivec3',
  22360. 'vec3u': 'uvec3',
  22361. 'vec3b': 'bvec3',
  22362. 'vec4<f32>': 'vec4',
  22363. 'vec4<i32>': 'ivec4',
  22364. 'vec4<u32>': 'uvec4',
  22365. 'vec4<bool>': 'bvec4',
  22366. 'vec4f': 'vec4',
  22367. 'vec4i': 'ivec4',
  22368. 'vec4u': 'uvec4',
  22369. 'vec4b': 'bvec4',
  22370. 'mat2x2<f32>': 'mat2',
  22371. 'mat2x2f': 'mat2',
  22372. 'mat3x3<f32>': 'mat3',
  22373. 'mat3x3f': 'mat3',
  22374. 'mat4x4<f32>': 'mat4',
  22375. 'mat4x4f': 'mat4',
  22376. 'sampler': 'sampler',
  22377. 'texture_1d': 'texture',
  22378. 'texture_2d': 'texture',
  22379. 'texture_2d_array': 'texture',
  22380. 'texture_multisampled_2d': 'cubeTexture',
  22381. 'texture_depth_2d': 'depthTexture',
  22382. 'texture_3d': 'texture3D',
  22383. 'texture_cube': 'cubeTexture',
  22384. 'texture_cube_array': 'cubeTexture',
  22385. 'texture_storage_1d': 'storageTexture',
  22386. 'texture_storage_2d': 'storageTexture',
  22387. 'texture_storage_2d_array': 'storageTexture',
  22388. 'texture_storage_3d': 'storageTexture'
  22389. };
  22390. const parse = ( source ) => {
  22391. source = source.trim();
  22392. const declaration = source.match( declarationRegexp );
  22393. if ( declaration !== null && declaration.length === 4 ) {
  22394. const inputsCode = declaration[ 2 ];
  22395. const propsMatches = [];
  22396. let match = null;
  22397. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  22398. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  22399. }
  22400. // Process matches to correctly pair names and types
  22401. const inputs = [];
  22402. for ( let i = 0; i < propsMatches.length; i ++ ) {
  22403. const { name, type } = propsMatches[ i ];
  22404. let resolvedType = type;
  22405. if ( resolvedType.startsWith( 'ptr' ) ) {
  22406. resolvedType = 'pointer';
  22407. } else {
  22408. if ( resolvedType.startsWith( 'texture' ) ) {
  22409. resolvedType = type.split( '<' )[ 0 ];
  22410. }
  22411. resolvedType = wgslTypeLib$1[ resolvedType ];
  22412. }
  22413. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  22414. }
  22415. const blockCode = source.substring( declaration[ 0 ].length );
  22416. const outputType = declaration[ 3 ] || 'void';
  22417. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  22418. const type = wgslTypeLib$1[ outputType ] || outputType;
  22419. return {
  22420. type,
  22421. inputs,
  22422. name,
  22423. inputsCode,
  22424. blockCode,
  22425. outputType
  22426. };
  22427. } else {
  22428. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  22429. }
  22430. };
  22431. class WGSLNodeFunction extends NodeFunction {
  22432. constructor( source ) {
  22433. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  22434. super( type, inputs, name );
  22435. this.inputsCode = inputsCode;
  22436. this.blockCode = blockCode;
  22437. this.outputType = outputType;
  22438. }
  22439. getCode( name = this.name ) {
  22440. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  22441. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  22442. }
  22443. }
  22444. class WGSLNodeParser extends NodeParser {
  22445. parseFunction( source ) {
  22446. return new WGSLNodeFunction( source );
  22447. }
  22448. }
  22449. // GPUShaderStage is not defined in browsers not supporting WebGPU
  22450. const GPUShaderStage = ( typeof self !== 'undefined' ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  22451. const accessNames = {
  22452. [ NodeAccess.READ_ONLY ]: 'read',
  22453. [ NodeAccess.WRITE_ONLY ]: 'write',
  22454. [ NodeAccess.READ_WRITE ]: 'read_write'
  22455. };
  22456. const wrapNames = {
  22457. [ RepeatWrapping ]: 'repeat',
  22458. [ ClampToEdgeWrapping ]: 'clamp',
  22459. [ MirroredRepeatWrapping ]: 'mirror'
  22460. };
  22461. const gpuShaderStageLib = {
  22462. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  22463. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  22464. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  22465. };
  22466. const supports = {
  22467. instance: true,
  22468. swizzleAssign: false,
  22469. storageBuffer: true
  22470. };
  22471. const wgslFnOpLib = {
  22472. '^^': 'tsl_xor'
  22473. };
  22474. const wgslTypeLib = {
  22475. float: 'f32',
  22476. int: 'i32',
  22477. uint: 'u32',
  22478. bool: 'bool',
  22479. color: 'vec3<f32>',
  22480. vec2: 'vec2<f32>',
  22481. ivec2: 'vec2<i32>',
  22482. uvec2: 'vec2<u32>',
  22483. bvec2: 'vec2<bool>',
  22484. vec3: 'vec3<f32>',
  22485. ivec3: 'vec3<i32>',
  22486. uvec3: 'vec3<u32>',
  22487. bvec3: 'vec3<bool>',
  22488. vec4: 'vec4<f32>',
  22489. ivec4: 'vec4<i32>',
  22490. uvec4: 'vec4<u32>',
  22491. bvec4: 'vec4<bool>',
  22492. mat2: 'mat2x2<f32>',
  22493. mat3: 'mat3x3<f32>',
  22494. mat4: 'mat4x4<f32>'
  22495. };
  22496. const wgslCodeCache = {};
  22497. const wgslPolyfill = {
  22498. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  22499. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  22500. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  22501. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  22502. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  22503. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  22504. 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 ); }' ),
  22505. 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 ); }' ),
  22506. 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 ); }' ),
  22507. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  22508. 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 ); }' ),
  22509. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  22510. biquadraticTexture: new CodeNode( /* wgsl */`
  22511. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  22512. let res = vec2f( iRes );
  22513. let uvScaled = coord * res;
  22514. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  22515. // https://www.shadertoy.com/view/WtyXRy
  22516. let uv = uvWrapping - 0.5;
  22517. let iuv = floor( uv );
  22518. let f = fract( uv );
  22519. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  22520. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  22521. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  22522. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  22523. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  22524. }
  22525. ` )
  22526. };
  22527. const wgslMethods = {
  22528. dFdx: 'dpdx',
  22529. dFdy: '- dpdy',
  22530. mod_float: 'tsl_mod_float',
  22531. mod_vec2: 'tsl_mod_vec2',
  22532. mod_vec3: 'tsl_mod_vec3',
  22533. mod_vec4: 'tsl_mod_vec4',
  22534. equals_bool: 'tsl_equals_bool',
  22535. equals_bvec2: 'tsl_equals_bvec2',
  22536. equals_bvec3: 'tsl_equals_bvec3',
  22537. equals_bvec4: 'tsl_equals_bvec4',
  22538. inversesqrt: 'inverseSqrt',
  22539. bitcast: 'bitcast<f32>'
  22540. };
  22541. // WebGPU issue: does not support pow() with negative base on Windows
  22542. if ( typeof navigator !== 'undefined' && /Windows/g.test( navigator.userAgent ) ) {
  22543. 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 ); }' );
  22544. 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 ] );
  22545. 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 ] );
  22546. 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 ] );
  22547. wgslMethods.pow_float = 'tsl_pow_float';
  22548. wgslMethods.pow_vec2 = 'tsl_pow_vec2';
  22549. wgslMethods.pow_vec3 = 'tsl_pow_vec3';
  22550. wgslMethods.pow_vec4 = 'tsl_pow_vec4';
  22551. }
  22552. //
  22553. let diagnostics = '';
  22554. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  22555. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  22556. }
  22557. //
  22558. class WGSLNodeBuilder extends NodeBuilder {
  22559. constructor( object, renderer ) {
  22560. super( object, renderer, new WGSLNodeParser() );
  22561. this.uniformGroups = {};
  22562. this.builtins = {};
  22563. this.directives = {};
  22564. this.scopedArrays = new Map();
  22565. }
  22566. needsToWorkingColorSpace( texture ) {
  22567. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  22568. }
  22569. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  22570. if ( shaderStage === 'fragment' ) {
  22571. if ( depthSnippet ) {
  22572. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  22573. } else {
  22574. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  22575. }
  22576. } else if ( this.isFilteredTexture( texture ) ) {
  22577. return this.generateFilteredTexture( texture, textureProperty, uvSnippet );
  22578. } else {
  22579. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0' );
  22580. }
  22581. }
  22582. _generateVideoSample( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  22583. if ( shaderStage === 'fragment' ) {
  22584. return `textureSampleBaseClampToEdge( ${ textureProperty }, ${ textureProperty }_sampler, vec2<f32>( ${ uvSnippet }.x, 1.0 - ${ uvSnippet }.y ) )`;
  22585. } else {
  22586. console.error( `WebGPURenderer: THREE.VideoTexture does not support ${ shaderStage } shader.` );
  22587. }
  22588. }
  22589. _generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  22590. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false ) {
  22591. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  22592. } else if ( this.isFilteredTexture( texture ) ) {
  22593. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  22594. } else {
  22595. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet );
  22596. }
  22597. }
  22598. generateWrapFunction( texture ) {
  22599. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }T`;
  22600. let nodeCode = wgslCodeCache[ functionName ];
  22601. if ( nodeCode === undefined ) {
  22602. const includes = [];
  22603. let code = `fn ${ functionName }( coord : vec2f ) -> vec2f {\n\n\treturn vec2f(\n`;
  22604. const addWrapSnippet = ( wrap, axis ) => {
  22605. if ( wrap === RepeatWrapping ) {
  22606. includes.push( wgslPolyfill.repeatWrapping_float );
  22607. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  22608. } else if ( wrap === ClampToEdgeWrapping ) {
  22609. includes.push( wgslPolyfill.clampWrapping_float );
  22610. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  22611. } else if ( wrap === MirroredRepeatWrapping ) {
  22612. includes.push( wgslPolyfill.mirrorWrapping_float );
  22613. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  22614. } else {
  22615. code += `\t\tcoord.${ axis }`;
  22616. console.warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  22617. }
  22618. };
  22619. addWrapSnippet( texture.wrapS, 'x' );
  22620. code += ',\n';
  22621. addWrapSnippet( texture.wrapT, 'y' );
  22622. code += '\n\t);\n\n}\n';
  22623. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  22624. }
  22625. nodeCode.build( this );
  22626. return functionName;
  22627. }
  22628. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  22629. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  22630. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  22631. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  22632. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  22633. let textureDimensionsParams;
  22634. if ( texture.isMultisampleRenderTargetTexture === true ) {
  22635. textureDimensionsParams = textureProperty;
  22636. } else {
  22637. textureDimensionsParams = `${ textureProperty }, u32( ${ levelSnippet } )`;
  22638. }
  22639. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, 'uvec2' ) );
  22640. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  22641. }
  22642. return textureDimensionNode.build( this );
  22643. }
  22644. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0u' ) {
  22645. this._include( 'biquadraticTexture' );
  22646. const wrapFunction = this.generateWrapFunction( texture );
  22647. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  22648. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  22649. }
  22650. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet = '0u' ) {
  22651. const wrapFunction = this.generateWrapFunction( texture );
  22652. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  22653. const coordSnippet = `vec2u( ${ wrapFunction }( ${ uvSnippet } ) * vec2f( ${ textureDimension } ) )`;
  22654. return this.generateTextureLoad( texture, textureProperty, coordSnippet, depthSnippet, levelSnippet );
  22655. }
  22656. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  22657. if ( texture.isVideoTexture === true || texture.isStorageTexture === true ) {
  22658. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet } )`;
  22659. } else if ( depthSnippet ) {
  22660. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  22661. } else {
  22662. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  22663. }
  22664. }
  22665. generateTextureStore( texture, textureProperty, uvIndexSnippet, valueSnippet ) {
  22666. return `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  22667. }
  22668. isSampleCompare( texture ) {
  22669. return texture.isDepthTexture === true && texture.compareFunction !== null;
  22670. }
  22671. isUnfilterable( texture ) {
  22672. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  22673. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  22674. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  22675. texture.isMultisampleRenderTargetTexture === true;
  22676. }
  22677. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  22678. let snippet = null;
  22679. if ( texture.isVideoTexture === true ) {
  22680. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  22681. } else if ( this.isUnfilterable( texture ) ) {
  22682. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0', shaderStage );
  22683. } else {
  22684. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  22685. }
  22686. return snippet;
  22687. }
  22688. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  22689. if ( shaderStage === 'fragment' ) {
  22690. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  22691. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  22692. } else {
  22693. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  22694. }
  22695. }
  22696. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  22697. if ( shaderStage === 'fragment' ) {
  22698. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  22699. } else {
  22700. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  22701. }
  22702. }
  22703. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  22704. let snippet = null;
  22705. if ( texture.isVideoTexture === true ) {
  22706. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  22707. } else {
  22708. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage );
  22709. }
  22710. return snippet;
  22711. }
  22712. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  22713. if ( shaderStage === 'fragment' ) {
  22714. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  22715. } else {
  22716. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  22717. }
  22718. }
  22719. getPropertyName( node, shaderStage = this.shaderStage ) {
  22720. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  22721. if ( shaderStage === 'vertex' ) {
  22722. return `varyings.${ node.name }`;
  22723. }
  22724. } else if ( node.isNodeUniform === true ) {
  22725. const name = node.name;
  22726. const type = node.type;
  22727. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  22728. return name;
  22729. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  22730. return `NodeBuffer_${ node.id }.${name}`;
  22731. } else {
  22732. return node.groupNode.name + '.' + name;
  22733. }
  22734. }
  22735. return super.getPropertyName( node );
  22736. }
  22737. getOutputStructName() {
  22738. return 'output';
  22739. }
  22740. _getUniformGroupCount( shaderStage ) {
  22741. return Object.keys( this.uniforms[ shaderStage ] ).length;
  22742. }
  22743. getFunctionOperator( op ) {
  22744. const fnOp = wgslFnOpLib[ op ];
  22745. if ( fnOp !== undefined ) {
  22746. this._include( fnOp );
  22747. return fnOp;
  22748. }
  22749. return null;
  22750. }
  22751. getNodeAccess( node, shaderStage ) {
  22752. if ( shaderStage !== 'compute' )
  22753. return NodeAccess.READ_ONLY;
  22754. return node.access;
  22755. }
  22756. getStorageAccess( node, shaderStage ) {
  22757. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  22758. }
  22759. getUniformFromNode( node, type, shaderStage, name = null ) {
  22760. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  22761. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  22762. if ( nodeData.uniformGPU === undefined ) {
  22763. let uniformGPU;
  22764. const group = node.groupNode;
  22765. const groupName = group.name;
  22766. const bindings = this.getBindGroupArray( groupName, shaderStage );
  22767. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  22768. let texture = null;
  22769. const access = this.getNodeAccess( node, shaderStage );
  22770. if ( type === 'texture' || type === 'storageTexture' ) {
  22771. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  22772. } else if ( type === 'cubeTexture' ) {
  22773. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  22774. } else if ( type === 'texture3D' ) {
  22775. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  22776. }
  22777. texture.store = node.isStorageTextureNode === true;
  22778. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  22779. if ( shaderStage === 'fragment' && this.isUnfilterable( node.value ) === false && texture.store === false ) {
  22780. const sampler = new NodeSampler( `${uniformNode.name}_sampler`, uniformNode.node, group );
  22781. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  22782. bindings.push( sampler, texture );
  22783. uniformGPU = [ sampler, texture ];
  22784. } else {
  22785. bindings.push( texture );
  22786. uniformGPU = [ texture ];
  22787. }
  22788. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  22789. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  22790. const buffer = new bufferClass( node, group );
  22791. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  22792. bindings.push( buffer );
  22793. uniformGPU = buffer;
  22794. } else {
  22795. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  22796. let uniformsGroup = uniformsStage[ groupName ];
  22797. if ( uniformsGroup === undefined ) {
  22798. uniformsGroup = new NodeUniformsGroup( groupName, group );
  22799. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  22800. uniformsStage[ groupName ] = uniformsGroup;
  22801. bindings.push( uniformsGroup );
  22802. }
  22803. uniformGPU = this.getNodeUniform( uniformNode, type );
  22804. uniformsGroup.addUniform( uniformGPU );
  22805. }
  22806. nodeData.uniformGPU = uniformGPU;
  22807. }
  22808. return uniformNode;
  22809. }
  22810. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  22811. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  22812. if ( map.has( name ) === false ) {
  22813. map.set( name, {
  22814. name,
  22815. property,
  22816. type
  22817. } );
  22818. }
  22819. return property;
  22820. }
  22821. hasBuiltin( name, shaderStage = this.shaderStage ) {
  22822. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  22823. }
  22824. getVertexIndex() {
  22825. if ( this.shaderStage === 'vertex' ) {
  22826. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  22827. }
  22828. return 'vertexIndex';
  22829. }
  22830. buildFunctionCode( shaderNode ) {
  22831. const layout = shaderNode.layout;
  22832. const flowData = this.flowShaderNode( shaderNode );
  22833. const parameters = [];
  22834. for ( const input of layout.inputs ) {
  22835. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  22836. }
  22837. //
  22838. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  22839. ${ flowData.vars }
  22840. ${ flowData.code }
  22841. `;
  22842. if ( flowData.result ) {
  22843. code += `\treturn ${ flowData.result };\n`;
  22844. }
  22845. code += '\n}\n';
  22846. //
  22847. return code;
  22848. }
  22849. getInstanceIndex() {
  22850. if ( this.shaderStage === 'vertex' ) {
  22851. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  22852. }
  22853. return 'instanceIndex';
  22854. }
  22855. getInvocationLocalIndex() {
  22856. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  22857. }
  22858. getSubgroupSize() {
  22859. this.enableSubGroups();
  22860. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  22861. }
  22862. getInvocationSubgroupIndex() {
  22863. this.enableSubGroups();
  22864. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  22865. }
  22866. getSubgroupIndex() {
  22867. this.enableSubGroups();
  22868. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  22869. }
  22870. getDrawIndex() {
  22871. return null;
  22872. }
  22873. getFrontFacing() {
  22874. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  22875. }
  22876. getFragCoord() {
  22877. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  22878. }
  22879. getFragDepth() {
  22880. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  22881. }
  22882. getClipDistance() {
  22883. return 'varyings.hw_clip_distances';
  22884. }
  22885. isFlipY() {
  22886. return false;
  22887. }
  22888. enableDirective( name, shaderStage = this.shaderStage ) {
  22889. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  22890. stage.add( name );
  22891. }
  22892. getDirectives( shaderStage ) {
  22893. const snippets = [];
  22894. const directives = this.directives[ shaderStage ];
  22895. if ( directives !== undefined ) {
  22896. for ( const directive of directives ) {
  22897. snippets.push( `enable ${directive};` );
  22898. }
  22899. }
  22900. return snippets.join( '\n' );
  22901. }
  22902. enableSubGroups() {
  22903. this.enableDirective( 'subgroups' );
  22904. }
  22905. enableSubgroupsF16() {
  22906. this.enableDirective( 'subgroups-f16' );
  22907. }
  22908. enableClipDistances() {
  22909. this.enableDirective( 'clip_distances' );
  22910. }
  22911. enableShaderF16() {
  22912. this.enableDirective( 'f16' );
  22913. }
  22914. enableDualSourceBlending() {
  22915. this.enableDirective( 'dual_source_blending' );
  22916. }
  22917. enableHardwareClipping( planeCount ) {
  22918. this.enableClipDistances();
  22919. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  22920. }
  22921. getBuiltins( shaderStage ) {
  22922. const snippets = [];
  22923. const builtins = this.builtins[ shaderStage ];
  22924. if ( builtins !== undefined ) {
  22925. for ( const { name, property, type } of builtins.values() ) {
  22926. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  22927. }
  22928. }
  22929. return snippets.join( ',\n\t' );
  22930. }
  22931. getScopedArray( name, scope, bufferType, bufferCount ) {
  22932. if ( this.scopedArrays.has( name ) === false ) {
  22933. this.scopedArrays.set( name, {
  22934. name,
  22935. scope,
  22936. bufferType,
  22937. bufferCount
  22938. } );
  22939. }
  22940. return name;
  22941. }
  22942. getScopedArrays( shaderStage ) {
  22943. if ( shaderStage !== 'compute' ) {
  22944. return;
  22945. }
  22946. const snippets = [];
  22947. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  22948. const type = this.getType( bufferType );
  22949. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  22950. }
  22951. return snippets.join( '\n' );
  22952. }
  22953. getAttributes( shaderStage ) {
  22954. const snippets = [];
  22955. if ( shaderStage === 'compute' ) {
  22956. this.getBuiltin( 'global_invocation_id', 'id', 'vec3<u32>', 'attribute' );
  22957. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  22958. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  22959. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  22960. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  22961. this.enableDirective( 'subgroups', shaderStage );
  22962. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  22963. }
  22964. }
  22965. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  22966. const builtins = this.getBuiltins( 'attribute' );
  22967. if ( builtins ) snippets.push( builtins );
  22968. const attributes = this.getAttributesArray();
  22969. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  22970. const attribute = attributes[ index ];
  22971. const name = attribute.name;
  22972. const type = this.getType( attribute.type );
  22973. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  22974. }
  22975. }
  22976. return snippets.join( ',\n\t' );
  22977. }
  22978. getStructMembers( struct ) {
  22979. const snippets = [];
  22980. const members = struct.getMemberTypes();
  22981. for ( let i = 0; i < members.length; i ++ ) {
  22982. const member = members[ i ];
  22983. snippets.push( `\t@location( ${i} ) m${i} : ${ member }<f32>` );
  22984. }
  22985. const builtins = this.getBuiltins( 'output' );
  22986. if ( builtins ) snippets.push( '\t' + builtins );
  22987. return snippets.join( ',\n' );
  22988. }
  22989. getStructs( shaderStage ) {
  22990. const snippets = [];
  22991. const structs = this.structs[ shaderStage ];
  22992. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  22993. const struct = structs[ index ];
  22994. const name = struct.name;
  22995. let snippet = `\struct ${ name } {\n`;
  22996. snippet += this.getStructMembers( struct );
  22997. snippet += '\n}';
  22998. snippets.push( snippet );
  22999. snippets.push( `\nvar<private> output : ${ name };\n\n` );
  23000. }
  23001. return snippets.join( '\n\n' );
  23002. }
  23003. getVar( type, name ) {
  23004. return `var ${ name } : ${ this.getType( type ) }`;
  23005. }
  23006. getVars( shaderStage ) {
  23007. const snippets = [];
  23008. const vars = this.vars[ shaderStage ];
  23009. if ( vars !== undefined ) {
  23010. for ( const variable of vars ) {
  23011. snippets.push( `\t${ this.getVar( variable.type, variable.name ) };` );
  23012. }
  23013. }
  23014. return `\n${ snippets.join( '\n' ) }\n`;
  23015. }
  23016. getVaryings( shaderStage ) {
  23017. const snippets = [];
  23018. if ( shaderStage === 'vertex' ) {
  23019. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  23020. }
  23021. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  23022. const varyings = this.varyings;
  23023. const vars = this.vars[ shaderStage ];
  23024. for ( let index = 0; index < varyings.length; index ++ ) {
  23025. const varying = varyings[ index ];
  23026. if ( varying.needsInterpolation ) {
  23027. let attributesSnippet = `@location( ${index} )`;
  23028. if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  23029. attributesSnippet += ' @interpolate( flat )';
  23030. }
  23031. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  23032. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  23033. vars.push( varying );
  23034. }
  23035. }
  23036. }
  23037. const builtins = this.getBuiltins( shaderStage );
  23038. if ( builtins ) snippets.push( builtins );
  23039. const code = snippets.join( ',\n\t' );
  23040. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  23041. }
  23042. getUniforms( shaderStage ) {
  23043. const uniforms = this.uniforms[ shaderStage ];
  23044. const bindingSnippets = [];
  23045. const bufferSnippets = [];
  23046. const structSnippets = [];
  23047. const uniformGroups = {};
  23048. for ( const uniform of uniforms ) {
  23049. const groupName = uniform.groupNode.name;
  23050. const uniformIndexes = this.bindingsIndexes[ groupName ];
  23051. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  23052. const texture = uniform.node.value;
  23053. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  23054. if ( this.isSampleCompare( texture ) ) {
  23055. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  23056. } else {
  23057. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  23058. }
  23059. }
  23060. let textureType;
  23061. let multisampled = '';
  23062. if ( texture.isMultisampleRenderTargetTexture === true ) {
  23063. multisampled = '_multisampled';
  23064. }
  23065. if ( texture.isCubeTexture === true ) {
  23066. textureType = 'texture_cube<f32>';
  23067. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  23068. textureType = 'texture_2d_array<f32>';
  23069. } else if ( texture.isDepthTexture === true ) {
  23070. textureType = `texture_depth${multisampled}_2d`;
  23071. } else if ( texture.isVideoTexture === true ) {
  23072. textureType = 'texture_external';
  23073. } else if ( texture.isData3DTexture === true ) {
  23074. textureType = 'texture_3d<f32>';
  23075. } else if ( uniform.node.isStorageTextureNode === true ) {
  23076. const format = getFormat( texture );
  23077. const access = this.getStorageAccess( uniform.node, shaderStage );
  23078. textureType = `texture_storage_2d<${ format }, ${ access }>`;
  23079. } else {
  23080. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  23081. textureType = `texture${multisampled}_2d<${ componentPrefix }32>`;
  23082. }
  23083. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  23084. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  23085. const bufferNode = uniform.node;
  23086. const bufferType = this.getType( bufferNode.bufferType );
  23087. const bufferCount = bufferNode.bufferCount;
  23088. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  23089. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${bufferType}>` : `${bufferType}`;
  23090. const bufferSnippet = `\t${ uniform.name } : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >\n`;
  23091. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  23092. bufferSnippets.push( this._getWGSLStructBinding( 'NodeBuffer_' + bufferNode.id, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  23093. } else {
  23094. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  23095. const groupName = uniform.groupNode.name;
  23096. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  23097. index: uniformIndexes.binding ++,
  23098. id: uniformIndexes.group,
  23099. snippets: []
  23100. } );
  23101. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  23102. }
  23103. }
  23104. for ( const name in uniformGroups ) {
  23105. const group = uniformGroups[ name ];
  23106. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  23107. }
  23108. let code = bindingSnippets.join( '\n' );
  23109. code += bufferSnippets.join( '\n' );
  23110. code += structSnippets.join( '\n' );
  23111. return code;
  23112. }
  23113. buildCode() {
  23114. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  23115. this.sortBindingGroups();
  23116. for ( const shaderStage in shadersData ) {
  23117. const stageData = shadersData[ shaderStage ];
  23118. stageData.uniforms = this.getUniforms( shaderStage );
  23119. stageData.attributes = this.getAttributes( shaderStage );
  23120. stageData.varyings = this.getVaryings( shaderStage );
  23121. stageData.structs = this.getStructs( shaderStage );
  23122. stageData.vars = this.getVars( shaderStage );
  23123. stageData.codes = this.getCodes( shaderStage );
  23124. stageData.directives = this.getDirectives( shaderStage );
  23125. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  23126. //
  23127. let flow = '// code\n\n';
  23128. flow += this.flowCode[ shaderStage ];
  23129. const flowNodes = this.flowNodes[ shaderStage ];
  23130. const mainNode = flowNodes[ flowNodes.length - 1 ];
  23131. const outputNode = mainNode.outputNode;
  23132. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  23133. for ( const node of flowNodes ) {
  23134. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  23135. const slotName = node.name;
  23136. if ( slotName ) {
  23137. if ( flow.length > 0 ) flow += '\n';
  23138. flow += `\t// flow -> ${ slotName }\n\t`;
  23139. }
  23140. flow += `${ flowSlotData.code }\n\t`;
  23141. if ( node === mainNode && shaderStage !== 'compute' ) {
  23142. flow += '// result\n\n\t';
  23143. if ( shaderStage === 'vertex' ) {
  23144. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  23145. } else if ( shaderStage === 'fragment' ) {
  23146. if ( isOutputStruct ) {
  23147. stageData.returnType = outputNode.nodeType;
  23148. flow += `return ${ flowSlotData.result };`;
  23149. } else {
  23150. let structSnippet = '\t@location(0) color: vec4<f32>';
  23151. const builtins = this.getBuiltins( 'output' );
  23152. if ( builtins ) structSnippet += ',\n\t' + builtins;
  23153. stageData.returnType = 'OutputStruct';
  23154. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  23155. stageData.structs += '\nvar<private> output : OutputStruct;\n\n';
  23156. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  23157. }
  23158. }
  23159. }
  23160. }
  23161. stageData.flow = flow;
  23162. }
  23163. if ( this.material !== null ) {
  23164. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  23165. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  23166. } else {
  23167. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  23168. }
  23169. }
  23170. getMethod( method, output = null ) {
  23171. let wgslMethod;
  23172. if ( output !== null ) {
  23173. wgslMethod = this._getWGSLMethod( method + '_' + output );
  23174. }
  23175. if ( wgslMethod === undefined ) {
  23176. wgslMethod = this._getWGSLMethod( method );
  23177. }
  23178. return wgslMethod || method;
  23179. }
  23180. getType( type ) {
  23181. return wgslTypeLib[ type ] || type;
  23182. }
  23183. isAvailable( name ) {
  23184. let result = supports[ name ];
  23185. if ( result === undefined ) {
  23186. if ( name === 'float32Filterable' ) {
  23187. result = this.renderer.hasFeature( 'float32-filterable' );
  23188. } else if ( name === 'clipDistance' ) {
  23189. result = this.renderer.hasFeature( 'clip-distances' );
  23190. }
  23191. supports[ name ] = result;
  23192. }
  23193. return result;
  23194. }
  23195. _getWGSLMethod( method ) {
  23196. if ( wgslPolyfill[ method ] !== undefined ) {
  23197. this._include( method );
  23198. }
  23199. return wgslMethods[ method ];
  23200. }
  23201. _include( name ) {
  23202. const codeNode = wgslPolyfill[ name ];
  23203. codeNode.build( this );
  23204. if ( this.currentFunctionNode !== null ) {
  23205. this.currentFunctionNode.includes.push( codeNode );
  23206. }
  23207. return codeNode;
  23208. }
  23209. _getWGSLVertexCode( shaderData ) {
  23210. return `${ this.getSignature() }
  23211. // directives
  23212. ${shaderData.directives}
  23213. // uniforms
  23214. ${shaderData.uniforms}
  23215. // varyings
  23216. ${shaderData.varyings}
  23217. var<private> varyings : VaryingsStruct;
  23218. // codes
  23219. ${shaderData.codes}
  23220. @vertex
  23221. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  23222. // vars
  23223. ${shaderData.vars}
  23224. // flow
  23225. ${shaderData.flow}
  23226. return varyings;
  23227. }
  23228. `;
  23229. }
  23230. _getWGSLFragmentCode( shaderData ) {
  23231. return `${ this.getSignature() }
  23232. // global
  23233. ${ diagnostics }
  23234. // uniforms
  23235. ${shaderData.uniforms}
  23236. // structs
  23237. ${shaderData.structs}
  23238. // codes
  23239. ${shaderData.codes}
  23240. @fragment
  23241. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  23242. // vars
  23243. ${shaderData.vars}
  23244. // flow
  23245. ${shaderData.flow}
  23246. }
  23247. `;
  23248. }
  23249. _getWGSLComputeCode( shaderData, workgroupSize ) {
  23250. return `${ this.getSignature() }
  23251. // directives
  23252. ${shaderData.directives}
  23253. // system
  23254. var<private> instanceIndex : u32;
  23255. // locals
  23256. ${shaderData.scopedArrays}
  23257. // uniforms
  23258. ${shaderData.uniforms}
  23259. // codes
  23260. ${shaderData.codes}
  23261. @compute @workgroup_size( ${workgroupSize} )
  23262. fn main( ${shaderData.attributes} ) {
  23263. // system
  23264. instanceIndex = id.x + id.y * numWorkgroups.x * u32(${workgroupSize}) + id.z * numWorkgroups.x * numWorkgroups.y * u32(${workgroupSize});
  23265. // vars
  23266. ${shaderData.vars}
  23267. // flow
  23268. ${shaderData.flow}
  23269. }
  23270. `;
  23271. }
  23272. _getWGSLStruct( name, vars ) {
  23273. return `
  23274. struct ${name} {
  23275. ${vars}
  23276. };`;
  23277. }
  23278. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  23279. const structName = name + 'Struct';
  23280. const structSnippet = this._getWGSLStruct( structName, vars );
  23281. return `${structSnippet}
  23282. @binding( ${binding} ) @group( ${group} )
  23283. var<${access}> ${name} : ${structName};`;
  23284. }
  23285. }
  23286. class WebGPUUtils {
  23287. constructor( backend ) {
  23288. this.backend = backend;
  23289. }
  23290. getCurrentDepthStencilFormat( renderContext ) {
  23291. let format;
  23292. if ( renderContext.depthTexture !== null ) {
  23293. format = this.getTextureFormatGPU( renderContext.depthTexture );
  23294. } else if ( renderContext.depth && renderContext.stencil ) {
  23295. format = GPUTextureFormat.Depth24PlusStencil8;
  23296. } else if ( renderContext.depth ) {
  23297. format = GPUTextureFormat.Depth24Plus;
  23298. }
  23299. return format;
  23300. }
  23301. getTextureFormatGPU( texture ) {
  23302. return this.backend.get( texture ).format;
  23303. }
  23304. getCurrentColorFormat( renderContext ) {
  23305. let format;
  23306. if ( renderContext.textures !== null ) {
  23307. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  23308. } else {
  23309. format = this.getPreferredCanvasFormat(); // default context format
  23310. }
  23311. return format;
  23312. }
  23313. getCurrentColorSpace( renderContext ) {
  23314. if ( renderContext.textures !== null ) {
  23315. return renderContext.textures[ 0 ].colorSpace;
  23316. }
  23317. return this.backend.renderer.outputColorSpace;
  23318. }
  23319. getPrimitiveTopology( object, material ) {
  23320. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  23321. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  23322. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  23323. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  23324. }
  23325. getSampleCount( sampleCount ) {
  23326. let count = 1;
  23327. if ( sampleCount > 1 ) {
  23328. // WebGPU only supports power-of-two sample counts and 2 is not a valid value
  23329. count = Math.pow( 2, Math.floor( Math.log2( sampleCount ) ) );
  23330. if ( count === 2 ) {
  23331. count = 4;
  23332. }
  23333. }
  23334. return count;
  23335. }
  23336. getSampleCountRenderContext( renderContext ) {
  23337. if ( renderContext.textures !== null ) {
  23338. return this.getSampleCount( renderContext.sampleCount );
  23339. }
  23340. return this.getSampleCount( this.backend.renderer.samples );
  23341. }
  23342. getPreferredCanvasFormat() {
  23343. // TODO: Remove this check when Quest 34.5 is out
  23344. // https://github.com/mrdoob/three.js/pull/29221/files#r1731833949
  23345. if ( navigator.userAgent.includes( 'Quest' ) ) {
  23346. return GPUTextureFormat.BGRA8Unorm;
  23347. } else {
  23348. return navigator.gpu.getPreferredCanvasFormat();
  23349. }
  23350. }
  23351. }
  23352. const typedArraysToVertexFormatPrefix = new Map( [
  23353. [ Int8Array, [ 'sint8', 'snorm8' ]],
  23354. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  23355. [ Int16Array, [ 'sint16', 'snorm16' ]],
  23356. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  23357. [ Int32Array, [ 'sint32', 'snorm32' ]],
  23358. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  23359. [ Float32Array, [ 'float32', ]],
  23360. ] );
  23361. const typedAttributeToVertexFormatPrefix = new Map( [
  23362. [ Float16BufferAttribute, [ 'float16', ]],
  23363. ] );
  23364. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  23365. [ Int32Array, 'sint32' ],
  23366. [ Int16Array, 'sint32' ], // patch for INT16
  23367. [ Uint32Array, 'uint32' ],
  23368. [ Uint16Array, 'uint32' ], // patch for UINT16
  23369. [ Float32Array, 'float32' ]
  23370. ] );
  23371. class WebGPUAttributeUtils {
  23372. constructor( backend ) {
  23373. this.backend = backend;
  23374. }
  23375. createAttribute( attribute, usage ) {
  23376. const bufferAttribute = this._getBufferAttribute( attribute );
  23377. const backend = this.backend;
  23378. const bufferData = backend.get( bufferAttribute );
  23379. let buffer = bufferData.buffer;
  23380. if ( buffer === undefined ) {
  23381. const device = backend.device;
  23382. let array = bufferAttribute.array;
  23383. // patch for INT16 and UINT16
  23384. if ( attribute.normalized === false && ( array.constructor === Int16Array || array.constructor === Uint16Array ) ) {
  23385. const tempArray = new Uint32Array( array.length );
  23386. for ( let i = 0; i < array.length; i ++ ) {
  23387. tempArray[ i ] = array[ i ];
  23388. }
  23389. array = tempArray;
  23390. }
  23391. bufferAttribute.array = array;
  23392. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  23393. array = new array.constructor( bufferAttribute.count * 4 );
  23394. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  23395. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  23396. }
  23397. // Update BufferAttribute
  23398. bufferAttribute.itemSize = 4;
  23399. bufferAttribute.array = array;
  23400. }
  23401. const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441
  23402. buffer = device.createBuffer( {
  23403. label: bufferAttribute.name,
  23404. size: size,
  23405. usage: usage,
  23406. mappedAtCreation: true
  23407. } );
  23408. new array.constructor( buffer.getMappedRange() ).set( array );
  23409. buffer.unmap();
  23410. bufferData.buffer = buffer;
  23411. }
  23412. }
  23413. updateAttribute( attribute ) {
  23414. const bufferAttribute = this._getBufferAttribute( attribute );
  23415. const backend = this.backend;
  23416. const device = backend.device;
  23417. const buffer = backend.get( bufferAttribute ).buffer;
  23418. const array = bufferAttribute.array;
  23419. const isTypedArray = this._isTypedArray( array );
  23420. const updateRanges = bufferAttribute.updateRanges;
  23421. if ( updateRanges.length === 0 ) {
  23422. // Not using update ranges
  23423. device.queue.writeBuffer(
  23424. buffer,
  23425. 0,
  23426. array,
  23427. 0
  23428. );
  23429. } else {
  23430. const byteOffsetFactor = isTypedArray ? 1 : array.BYTES_PER_ELEMENT;
  23431. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  23432. const range = updateRanges[ i ];
  23433. const dataOffset = range.start * byteOffsetFactor;
  23434. const size = range.count * byteOffsetFactor;
  23435. device.queue.writeBuffer(
  23436. buffer,
  23437. 0,
  23438. array,
  23439. dataOffset,
  23440. size
  23441. );
  23442. }
  23443. bufferAttribute.clearUpdateRanges();
  23444. }
  23445. }
  23446. createShaderVertexBuffers( renderObject ) {
  23447. const attributes = renderObject.getAttributes();
  23448. const vertexBuffers = new Map();
  23449. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  23450. const geometryAttribute = attributes[ slot ];
  23451. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  23452. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  23453. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  23454. if ( vertexBufferLayout === undefined ) {
  23455. let arrayStride, stepMode;
  23456. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  23457. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  23458. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  23459. } else {
  23460. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  23461. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  23462. }
  23463. // patch for INT16 and UINT16
  23464. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  23465. arrayStride = 4;
  23466. }
  23467. vertexBufferLayout = {
  23468. arrayStride,
  23469. attributes: [],
  23470. stepMode
  23471. };
  23472. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  23473. }
  23474. const format = this._getVertexFormat( geometryAttribute );
  23475. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  23476. vertexBufferLayout.attributes.push( {
  23477. shaderLocation: slot,
  23478. offset,
  23479. format
  23480. } );
  23481. }
  23482. return Array.from( vertexBuffers.values() );
  23483. }
  23484. destroyAttribute( attribute ) {
  23485. const backend = this.backend;
  23486. const data = backend.get( this._getBufferAttribute( attribute ) );
  23487. data.buffer.destroy();
  23488. backend.delete( attribute );
  23489. }
  23490. async getArrayBufferAsync( attribute ) {
  23491. const backend = this.backend;
  23492. const device = backend.device;
  23493. const data = backend.get( this._getBufferAttribute( attribute ) );
  23494. const bufferGPU = data.buffer;
  23495. const size = bufferGPU.size;
  23496. const readBufferGPU = device.createBuffer( {
  23497. label: attribute.name,
  23498. size,
  23499. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  23500. } );
  23501. const cmdEncoder = device.createCommandEncoder( {} );
  23502. cmdEncoder.copyBufferToBuffer(
  23503. bufferGPU,
  23504. 0,
  23505. readBufferGPU,
  23506. 0,
  23507. size
  23508. );
  23509. readBufferGPU.unmap();
  23510. const gpuCommands = cmdEncoder.finish();
  23511. device.queue.submit( [ gpuCommands ] );
  23512. await readBufferGPU.mapAsync( GPUMapMode.READ );
  23513. const arrayBuffer = readBufferGPU.getMappedRange();
  23514. return arrayBuffer;
  23515. }
  23516. _getVertexFormat( geometryAttribute ) {
  23517. const { itemSize, normalized } = geometryAttribute;
  23518. const ArrayType = geometryAttribute.array.constructor;
  23519. const AttributeType = geometryAttribute.constructor;
  23520. let format;
  23521. if ( itemSize == 1 ) {
  23522. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  23523. } else {
  23524. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  23525. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  23526. if ( prefix ) {
  23527. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  23528. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  23529. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  23530. if ( paddedItemSize % 1 ) {
  23531. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  23532. }
  23533. format = `${prefix}x${paddedItemSize}`;
  23534. }
  23535. }
  23536. if ( ! format ) {
  23537. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  23538. }
  23539. return format;
  23540. }
  23541. _isTypedArray( array ) {
  23542. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  23543. }
  23544. _getBufferAttribute( attribute ) {
  23545. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  23546. return attribute;
  23547. }
  23548. }
  23549. class WebGPUBindingUtils {
  23550. constructor( backend ) {
  23551. this.backend = backend;
  23552. this.bindGroupLayoutCache = new WeakMap();
  23553. }
  23554. createBindingsLayout( bindGroup ) {
  23555. const backend = this.backend;
  23556. const device = backend.device;
  23557. const entries = [];
  23558. let index = 0;
  23559. for ( const binding of bindGroup.bindings ) {
  23560. const bindingGPU = {
  23561. binding: index ++,
  23562. visibility: binding.visibility
  23563. };
  23564. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  23565. const buffer = {}; // GPUBufferBindingLayout
  23566. if ( binding.isStorageBuffer ) {
  23567. if ( binding.visibility & 4 ) {
  23568. // compute
  23569. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  23570. buffer.type = GPUBufferBindingType.Storage;
  23571. } else {
  23572. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  23573. }
  23574. } else {
  23575. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  23576. }
  23577. }
  23578. bindingGPU.buffer = buffer;
  23579. } else if ( binding.isSampler ) {
  23580. const sampler = {}; // GPUSamplerBindingLayout
  23581. if ( binding.texture.isDepthTexture ) {
  23582. if ( binding.texture.compareFunction !== null ) {
  23583. sampler.type = 'comparison';
  23584. }
  23585. }
  23586. bindingGPU.sampler = sampler;
  23587. } else if ( binding.isSampledTexture && binding.texture.isVideoTexture ) {
  23588. bindingGPU.externalTexture = {}; // GPUExternalTextureBindingLayout
  23589. } else if ( binding.isSampledTexture && binding.store ) {
  23590. const storageTexture = {}; // GPUStorageTextureBindingLayout
  23591. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  23592. const access = binding.access;
  23593. if ( access === NodeAccess.READ_WRITE ) {
  23594. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  23595. } else if ( access === NodeAccess.WRITE_ONLY ) {
  23596. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  23597. } else {
  23598. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  23599. }
  23600. bindingGPU.storageTexture = storageTexture;
  23601. } else if ( binding.isSampledTexture ) {
  23602. const texture = {}; // GPUTextureBindingLayout
  23603. if ( binding.texture.isMultisampleRenderTargetTexture === true ) {
  23604. texture.multisampled = true;
  23605. }
  23606. if ( binding.texture.isDepthTexture ) {
  23607. texture.sampleType = GPUTextureSampleType.Depth;
  23608. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  23609. const type = binding.texture.type;
  23610. if ( type === IntType ) {
  23611. texture.sampleType = GPUTextureSampleType.SInt;
  23612. } else if ( type === UnsignedIntType ) {
  23613. texture.sampleType = GPUTextureSampleType.UInt;
  23614. } else if ( type === FloatType ) {
  23615. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  23616. texture.sampleType = GPUTextureSampleType.Float;
  23617. } else {
  23618. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  23619. }
  23620. }
  23621. }
  23622. if ( binding.isSampledCubeTexture ) {
  23623. texture.viewDimension = GPUTextureViewDimension.Cube;
  23624. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  23625. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  23626. } else if ( binding.isSampledTexture3D ) {
  23627. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  23628. }
  23629. bindingGPU.texture = texture;
  23630. } else {
  23631. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  23632. }
  23633. entries.push( bindingGPU );
  23634. }
  23635. return device.createBindGroupLayout( { entries } );
  23636. }
  23637. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  23638. const { backend, bindGroupLayoutCache } = this;
  23639. const bindingsData = backend.get( bindGroup );
  23640. // setup (static) binding layout and (dynamic) binding group
  23641. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  23642. if ( bindLayoutGPU === undefined ) {
  23643. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  23644. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  23645. }
  23646. let bindGroupGPU;
  23647. if ( cacheIndex > 0 ) {
  23648. if ( bindingsData.groups === undefined ) {
  23649. bindingsData.groups = [];
  23650. bindingsData.versions = [];
  23651. }
  23652. if ( bindingsData.versions[ cacheIndex ] === version ) {
  23653. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  23654. }
  23655. }
  23656. if ( bindGroupGPU === undefined ) {
  23657. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  23658. if ( cacheIndex > 0 ) {
  23659. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  23660. bindingsData.versions[ cacheIndex ] = version;
  23661. }
  23662. }
  23663. bindingsData.group = bindGroupGPU;
  23664. bindingsData.layout = bindLayoutGPU;
  23665. }
  23666. updateBinding( binding ) {
  23667. const backend = this.backend;
  23668. const device = backend.device;
  23669. const buffer = binding.buffer;
  23670. const bufferGPU = backend.get( binding ).buffer;
  23671. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  23672. }
  23673. createBindGroup( bindGroup, layoutGPU ) {
  23674. const backend = this.backend;
  23675. const device = backend.device;
  23676. let bindingPoint = 0;
  23677. const entriesGPU = [];
  23678. for ( const binding of bindGroup.bindings ) {
  23679. if ( binding.isUniformBuffer ) {
  23680. const bindingData = backend.get( binding );
  23681. if ( bindingData.buffer === undefined ) {
  23682. const byteLength = binding.byteLength;
  23683. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  23684. const bufferGPU = device.createBuffer( {
  23685. label: 'bindingBuffer_' + binding.name,
  23686. size: byteLength,
  23687. usage: usage
  23688. } );
  23689. bindingData.buffer = bufferGPU;
  23690. }
  23691. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  23692. } else if ( binding.isStorageBuffer ) {
  23693. const bindingData = backend.get( binding );
  23694. if ( bindingData.buffer === undefined ) {
  23695. const attribute = binding.attribute;
  23696. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  23697. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  23698. bindingData.buffer = backend.get( attribute ).buffer;
  23699. }
  23700. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  23701. } else if ( binding.isSampler ) {
  23702. const textureGPU = backend.get( binding.texture );
  23703. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  23704. } else if ( binding.isSampledTexture ) {
  23705. const textureData = backend.get( binding.texture );
  23706. let resourceGPU;
  23707. if ( textureData.externalTexture !== undefined ) {
  23708. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  23709. } else {
  23710. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  23711. const propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }-${ mipLevelCount }`;
  23712. resourceGPU = textureData[ propertyName ];
  23713. if ( resourceGPU === undefined ) {
  23714. const aspectGPU = GPUTextureAspect.All;
  23715. let dimensionViewGPU;
  23716. if ( binding.isSampledCubeTexture ) {
  23717. dimensionViewGPU = GPUTextureViewDimension.Cube;
  23718. } else if ( binding.isSampledTexture3D ) {
  23719. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  23720. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  23721. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  23722. } else {
  23723. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  23724. }
  23725. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount } );
  23726. }
  23727. }
  23728. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  23729. }
  23730. bindingPoint ++;
  23731. }
  23732. return device.createBindGroup( {
  23733. label: 'bindGroup_' + bindGroup.name,
  23734. layout: layoutGPU,
  23735. entries: entriesGPU
  23736. } );
  23737. }
  23738. }
  23739. class WebGPUPipelineUtils {
  23740. constructor( backend ) {
  23741. this.backend = backend;
  23742. }
  23743. _getSampleCount( renderObjectContext ) {
  23744. return this.backend.utils.getSampleCountRenderContext( renderObjectContext );
  23745. }
  23746. createRenderPipeline( renderObject, promises ) {
  23747. const { object, material, geometry, pipeline } = renderObject;
  23748. const { vertexProgram, fragmentProgram } = pipeline;
  23749. const backend = this.backend;
  23750. const device = backend.device;
  23751. const utils = backend.utils;
  23752. const pipelineData = backend.get( pipeline );
  23753. // bind group layouts
  23754. const bindGroupLayouts = [];
  23755. for ( const bindGroup of renderObject.getBindings() ) {
  23756. const bindingsData = backend.get( bindGroup );
  23757. bindGroupLayouts.push( bindingsData.layout );
  23758. }
  23759. // vertex buffers
  23760. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  23761. // blending
  23762. let blending;
  23763. if ( material.transparent === true && material.blending !== NoBlending ) {
  23764. blending = this._getBlending( material );
  23765. }
  23766. // stencil
  23767. let stencilFront = {};
  23768. if ( material.stencilWrite === true ) {
  23769. stencilFront = {
  23770. compare: this._getStencilCompare( material ),
  23771. failOp: this._getStencilOperation( material.stencilFail ),
  23772. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  23773. passOp: this._getStencilOperation( material.stencilZPass )
  23774. };
  23775. }
  23776. const colorWriteMask = this._getColorWriteMask( material );
  23777. const targets = [];
  23778. if ( renderObject.context.textures !== null ) {
  23779. const textures = renderObject.context.textures;
  23780. for ( let i = 0; i < textures.length; i ++ ) {
  23781. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  23782. targets.push( {
  23783. format: colorFormat,
  23784. blend: blending,
  23785. writeMask: colorWriteMask
  23786. } );
  23787. }
  23788. } else {
  23789. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  23790. targets.push( {
  23791. format: colorFormat,
  23792. blend: blending,
  23793. writeMask: colorWriteMask
  23794. } );
  23795. }
  23796. const vertexModule = backend.get( vertexProgram ).module;
  23797. const fragmentModule = backend.get( fragmentProgram ).module;
  23798. const primitiveState = this._getPrimitiveState( object, geometry, material );
  23799. const depthCompare = this._getDepthCompare( material );
  23800. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  23801. const sampleCount = this._getSampleCount( renderObject.context );
  23802. const pipelineDescriptor = {
  23803. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  23804. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  23805. fragment: Object.assign( {}, fragmentModule, { targets } ),
  23806. primitive: primitiveState,
  23807. multisample: {
  23808. count: sampleCount,
  23809. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  23810. },
  23811. layout: device.createPipelineLayout( {
  23812. bindGroupLayouts
  23813. } )
  23814. };
  23815. const depthStencil = {};
  23816. const renderDepth = renderObject.context.depth;
  23817. const renderStencil = renderObject.context.stencil;
  23818. if ( renderDepth === true || renderStencil === true ) {
  23819. if ( renderDepth === true ) {
  23820. depthStencil.format = depthStencilFormat;
  23821. depthStencil.depthWriteEnabled = material.depthWrite;
  23822. depthStencil.depthCompare = depthCompare;
  23823. }
  23824. if ( renderStencil === true ) {
  23825. depthStencil.stencilFront = stencilFront;
  23826. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  23827. depthStencil.stencilReadMask = material.stencilFuncMask;
  23828. depthStencil.stencilWriteMask = material.stencilWriteMask;
  23829. }
  23830. pipelineDescriptor.depthStencil = depthStencil;
  23831. }
  23832. if ( promises === null ) {
  23833. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  23834. } else {
  23835. const p = new Promise( ( resolve /*, reject*/ ) => {
  23836. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  23837. pipelineData.pipeline = pipeline;
  23838. resolve();
  23839. } );
  23840. } );
  23841. promises.push( p );
  23842. }
  23843. }
  23844. createBundleEncoder( renderContext ) {
  23845. const backend = this.backend;
  23846. const { utils, device } = backend;
  23847. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  23848. const colorFormat = utils.getCurrentColorFormat( renderContext );
  23849. const sampleCount = this._getSampleCount( renderContext );
  23850. const descriptor = {
  23851. label: 'renderBundleEncoder',
  23852. colorFormats: [ colorFormat ],
  23853. depthStencilFormat,
  23854. sampleCount
  23855. };
  23856. return device.createRenderBundleEncoder( descriptor );
  23857. }
  23858. createComputePipeline( pipeline, bindings ) {
  23859. const backend = this.backend;
  23860. const device = backend.device;
  23861. const computeProgram = backend.get( pipeline.computeProgram ).module;
  23862. const pipelineGPU = backend.get( pipeline );
  23863. // bind group layouts
  23864. const bindGroupLayouts = [];
  23865. for ( const bindingsGroup of bindings ) {
  23866. const bindingsData = backend.get( bindingsGroup );
  23867. bindGroupLayouts.push( bindingsData.layout );
  23868. }
  23869. pipelineGPU.pipeline = device.createComputePipeline( {
  23870. compute: computeProgram,
  23871. layout: device.createPipelineLayout( {
  23872. bindGroupLayouts
  23873. } )
  23874. } );
  23875. }
  23876. _getBlending( material ) {
  23877. let color, alpha;
  23878. const blending = material.blending;
  23879. const blendSrc = material.blendSrc;
  23880. const blendDst = material.blendDst;
  23881. const blendEquation = material.blendEquation;
  23882. if ( blending === CustomBlending ) {
  23883. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  23884. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  23885. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  23886. color = {
  23887. srcFactor: this._getBlendFactor( blendSrc ),
  23888. dstFactor: this._getBlendFactor( blendDst ),
  23889. operation: this._getBlendOperation( blendEquation )
  23890. };
  23891. alpha = {
  23892. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  23893. dstFactor: this._getBlendFactor( blendDstAlpha ),
  23894. operation: this._getBlendOperation( blendEquationAlpha )
  23895. };
  23896. } else {
  23897. const premultipliedAlpha = material.premultipliedAlpha;
  23898. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  23899. color = {
  23900. srcFactor: srcRGB,
  23901. dstFactor: dstRGB,
  23902. operation: GPUBlendOperation.Add
  23903. };
  23904. alpha = {
  23905. srcFactor: srcAlpha,
  23906. dstFactor: dstAlpha,
  23907. operation: GPUBlendOperation.Add
  23908. };
  23909. };
  23910. if ( premultipliedAlpha ) {
  23911. switch ( blending ) {
  23912. case NormalBlending:
  23913. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  23914. break;
  23915. case AdditiveBlending:
  23916. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  23917. break;
  23918. case SubtractiveBlending:
  23919. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  23920. break;
  23921. case MultiplyBlending:
  23922. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.SrcAlpha );
  23923. break;
  23924. }
  23925. } else {
  23926. switch ( blending ) {
  23927. case NormalBlending:
  23928. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  23929. break;
  23930. case AdditiveBlending:
  23931. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.SrcAlpha, GPUBlendFactor.One );
  23932. break;
  23933. case SubtractiveBlending:
  23934. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  23935. break;
  23936. case MultiplyBlending:
  23937. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.Src );
  23938. break;
  23939. }
  23940. }
  23941. }
  23942. if ( color !== undefined && alpha !== undefined ) {
  23943. return { color, alpha };
  23944. } else {
  23945. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  23946. }
  23947. }
  23948. _getBlendFactor( blend ) {
  23949. let blendFactor;
  23950. switch ( blend ) {
  23951. case ZeroFactor:
  23952. blendFactor = GPUBlendFactor.Zero;
  23953. break;
  23954. case OneFactor:
  23955. blendFactor = GPUBlendFactor.One;
  23956. break;
  23957. case SrcColorFactor:
  23958. blendFactor = GPUBlendFactor.Src;
  23959. break;
  23960. case OneMinusSrcColorFactor:
  23961. blendFactor = GPUBlendFactor.OneMinusSrc;
  23962. break;
  23963. case SrcAlphaFactor:
  23964. blendFactor = GPUBlendFactor.SrcAlpha;
  23965. break;
  23966. case OneMinusSrcAlphaFactor:
  23967. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  23968. break;
  23969. case DstColorFactor:
  23970. blendFactor = GPUBlendFactor.Dst;
  23971. break;
  23972. case OneMinusDstColorFactor:
  23973. blendFactor = GPUBlendFactor.OneMinusDstColor;
  23974. break;
  23975. case DstAlphaFactor:
  23976. blendFactor = GPUBlendFactor.DstAlpha;
  23977. break;
  23978. case OneMinusDstAlphaFactor:
  23979. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  23980. break;
  23981. case SrcAlphaSaturateFactor:
  23982. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  23983. break;
  23984. case BlendColorFactor:
  23985. blendFactor = GPUBlendFactor.Constant;
  23986. break;
  23987. case OneMinusBlendColorFactor:
  23988. blendFactor = GPUBlendFactor.OneMinusConstant;
  23989. break;
  23990. default:
  23991. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  23992. }
  23993. return blendFactor;
  23994. }
  23995. _getStencilCompare( material ) {
  23996. let stencilCompare;
  23997. const stencilFunc = material.stencilFunc;
  23998. switch ( stencilFunc ) {
  23999. case NeverStencilFunc:
  24000. stencilCompare = GPUCompareFunction.Never;
  24001. break;
  24002. case AlwaysStencilFunc:
  24003. stencilCompare = GPUCompareFunction.Always;
  24004. break;
  24005. case LessStencilFunc:
  24006. stencilCompare = GPUCompareFunction.Less;
  24007. break;
  24008. case LessEqualStencilFunc:
  24009. stencilCompare = GPUCompareFunction.LessEqual;
  24010. break;
  24011. case EqualStencilFunc:
  24012. stencilCompare = GPUCompareFunction.Equal;
  24013. break;
  24014. case GreaterEqualStencilFunc:
  24015. stencilCompare = GPUCompareFunction.GreaterEqual;
  24016. break;
  24017. case GreaterStencilFunc:
  24018. stencilCompare = GPUCompareFunction.Greater;
  24019. break;
  24020. case NotEqualStencilFunc:
  24021. stencilCompare = GPUCompareFunction.NotEqual;
  24022. break;
  24023. default:
  24024. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  24025. }
  24026. return stencilCompare;
  24027. }
  24028. _getStencilOperation( op ) {
  24029. let stencilOperation;
  24030. switch ( op ) {
  24031. case KeepStencilOp:
  24032. stencilOperation = GPUStencilOperation.Keep;
  24033. break;
  24034. case ZeroStencilOp:
  24035. stencilOperation = GPUStencilOperation.Zero;
  24036. break;
  24037. case ReplaceStencilOp:
  24038. stencilOperation = GPUStencilOperation.Replace;
  24039. break;
  24040. case InvertStencilOp:
  24041. stencilOperation = GPUStencilOperation.Invert;
  24042. break;
  24043. case IncrementStencilOp:
  24044. stencilOperation = GPUStencilOperation.IncrementClamp;
  24045. break;
  24046. case DecrementStencilOp:
  24047. stencilOperation = GPUStencilOperation.DecrementClamp;
  24048. break;
  24049. case IncrementWrapStencilOp:
  24050. stencilOperation = GPUStencilOperation.IncrementWrap;
  24051. break;
  24052. case DecrementWrapStencilOp:
  24053. stencilOperation = GPUStencilOperation.DecrementWrap;
  24054. break;
  24055. default:
  24056. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  24057. }
  24058. return stencilOperation;
  24059. }
  24060. _getBlendOperation( blendEquation ) {
  24061. let blendOperation;
  24062. switch ( blendEquation ) {
  24063. case AddEquation:
  24064. blendOperation = GPUBlendOperation.Add;
  24065. break;
  24066. case SubtractEquation:
  24067. blendOperation = GPUBlendOperation.Subtract;
  24068. break;
  24069. case ReverseSubtractEquation:
  24070. blendOperation = GPUBlendOperation.ReverseSubtract;
  24071. break;
  24072. case MinEquation:
  24073. blendOperation = GPUBlendOperation.Min;
  24074. break;
  24075. case MaxEquation:
  24076. blendOperation = GPUBlendOperation.Max;
  24077. break;
  24078. default:
  24079. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  24080. }
  24081. return blendOperation;
  24082. }
  24083. _getPrimitiveState( object, geometry, material ) {
  24084. const descriptor = {};
  24085. const utils = this.backend.utils;
  24086. descriptor.topology = utils.getPrimitiveTopology( object, material );
  24087. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  24088. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  24089. }
  24090. switch ( material.side ) {
  24091. case FrontSide:
  24092. descriptor.frontFace = GPUFrontFace.CCW;
  24093. descriptor.cullMode = GPUCullMode.Back;
  24094. break;
  24095. case BackSide:
  24096. descriptor.frontFace = GPUFrontFace.CCW;
  24097. descriptor.cullMode = GPUCullMode.Front;
  24098. break;
  24099. case DoubleSide:
  24100. descriptor.frontFace = GPUFrontFace.CCW;
  24101. descriptor.cullMode = GPUCullMode.None;
  24102. break;
  24103. default:
  24104. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  24105. break;
  24106. }
  24107. return descriptor;
  24108. }
  24109. _getColorWriteMask( material ) {
  24110. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  24111. }
  24112. _getDepthCompare( material ) {
  24113. let depthCompare;
  24114. if ( material.depthTest === false ) {
  24115. depthCompare = GPUCompareFunction.Always;
  24116. } else {
  24117. const depthFunc = material.depthFunc;
  24118. switch ( depthFunc ) {
  24119. case NeverDepth:
  24120. depthCompare = GPUCompareFunction.Never;
  24121. break;
  24122. case AlwaysDepth:
  24123. depthCompare = GPUCompareFunction.Always;
  24124. break;
  24125. case LessDepth:
  24126. depthCompare = GPUCompareFunction.Less;
  24127. break;
  24128. case LessEqualDepth:
  24129. depthCompare = GPUCompareFunction.LessEqual;
  24130. break;
  24131. case EqualDepth:
  24132. depthCompare = GPUCompareFunction.Equal;
  24133. break;
  24134. case GreaterEqualDepth:
  24135. depthCompare = GPUCompareFunction.GreaterEqual;
  24136. break;
  24137. case GreaterDepth:
  24138. depthCompare = GPUCompareFunction.Greater;
  24139. break;
  24140. case NotEqualDepth:
  24141. depthCompare = GPUCompareFunction.NotEqual;
  24142. break;
  24143. default:
  24144. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  24145. }
  24146. }
  24147. return depthCompare;
  24148. }
  24149. }
  24150. /*// debugger tools
  24151. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  24152. //*/
  24153. //
  24154. class WebGPUBackend extends Backend {
  24155. constructor( parameters = {} ) {
  24156. super( parameters );
  24157. this.isWebGPUBackend = true;
  24158. // some parameters require default values other than "undefined"
  24159. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  24160. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  24161. this.trackTimestamp = ( parameters.trackTimestamp === true );
  24162. this.device = null;
  24163. this.context = null;
  24164. this.colorBuffer = null;
  24165. this.defaultRenderPassdescriptor = null;
  24166. this.utils = new WebGPUUtils( this );
  24167. this.attributeUtils = new WebGPUAttributeUtils( this );
  24168. this.bindingUtils = new WebGPUBindingUtils( this );
  24169. this.pipelineUtils = new WebGPUPipelineUtils( this );
  24170. this.textureUtils = new WebGPUTextureUtils( this );
  24171. this.occludedResolveCache = new Map();
  24172. }
  24173. async init( renderer ) {
  24174. await super.init( renderer );
  24175. //
  24176. const parameters = this.parameters;
  24177. // create the device if it is not passed with parameters
  24178. let device;
  24179. if ( parameters.device === undefined ) {
  24180. const adapterOptions = {
  24181. powerPreference: parameters.powerPreference
  24182. };
  24183. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  24184. if ( adapter === null ) {
  24185. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  24186. }
  24187. // feature support
  24188. const features = Object.values( GPUFeatureName );
  24189. const supportedFeatures = [];
  24190. for ( const name of features ) {
  24191. if ( adapter.features.has( name ) ) {
  24192. supportedFeatures.push( name );
  24193. }
  24194. }
  24195. const deviceDescriptor = {
  24196. requiredFeatures: supportedFeatures,
  24197. requiredLimits: parameters.requiredLimits
  24198. };
  24199. device = await adapter.requestDevice( deviceDescriptor );
  24200. } else {
  24201. device = parameters.device;
  24202. }
  24203. device.lost.then( ( info ) => {
  24204. const deviceLossInfo = {
  24205. api: 'WebGPU',
  24206. message: info.message || 'Unknown reason',
  24207. reason: info.reason || null,
  24208. originalEvent: info
  24209. };
  24210. renderer.onDeviceLost( deviceLossInfo );
  24211. } );
  24212. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  24213. this.device = device;
  24214. this.context = context;
  24215. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  24216. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  24217. this.context.configure( {
  24218. device: this.device,
  24219. format: this.utils.getPreferredCanvasFormat(),
  24220. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  24221. alphaMode: alphaMode
  24222. } );
  24223. this.updateSize();
  24224. }
  24225. get coordinateSystem() {
  24226. return WebGPUCoordinateSystem;
  24227. }
  24228. async getArrayBufferAsync( attribute ) {
  24229. return await this.attributeUtils.getArrayBufferAsync( attribute );
  24230. }
  24231. getContext() {
  24232. return this.context;
  24233. }
  24234. _getDefaultRenderPassDescriptor() {
  24235. let descriptor = this.defaultRenderPassdescriptor;
  24236. if ( descriptor === null ) {
  24237. const renderer = this.renderer;
  24238. descriptor = {
  24239. colorAttachments: [ {
  24240. view: null
  24241. } ],
  24242. };
  24243. if ( this.renderer.depth === true || this.renderer.stencil === true ) {
  24244. descriptor.depthStencilAttachment = {
  24245. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  24246. };
  24247. }
  24248. const colorAttachment = descriptor.colorAttachments[ 0 ];
  24249. if ( this.renderer.samples > 0 ) {
  24250. colorAttachment.view = this.colorBuffer.createView();
  24251. } else {
  24252. colorAttachment.resolveTarget = undefined;
  24253. }
  24254. this.defaultRenderPassdescriptor = descriptor;
  24255. }
  24256. const colorAttachment = descriptor.colorAttachments[ 0 ];
  24257. if ( this.renderer.samples > 0 ) {
  24258. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  24259. } else {
  24260. colorAttachment.view = this.context.getCurrentTexture().createView();
  24261. }
  24262. return descriptor;
  24263. }
  24264. _getRenderPassDescriptor( renderContext ) {
  24265. const renderTarget = renderContext.renderTarget;
  24266. const renderTargetData = this.get( renderTarget );
  24267. let descriptors = renderTargetData.descriptors;
  24268. if ( descriptors === undefined ||
  24269. renderTargetData.width !== renderTarget.width ||
  24270. renderTargetData.height !== renderTarget.height ||
  24271. renderTargetData.activeMipmapLevel !== renderTarget.activeMipmapLevel ||
  24272. renderTargetData.samples !== renderTarget.samples
  24273. ) {
  24274. descriptors = {};
  24275. renderTargetData.descriptors = descriptors;
  24276. // dispose
  24277. const onDispose = () => {
  24278. renderTarget.removeEventListener( 'dispose', onDispose );
  24279. this.delete( renderTarget );
  24280. };
  24281. renderTarget.addEventListener( 'dispose', onDispose );
  24282. }
  24283. const cacheKey = renderContext.getCacheKey();
  24284. let descriptor = descriptors[ cacheKey ];
  24285. if ( descriptor === undefined ) {
  24286. const textures = renderContext.textures;
  24287. const colorAttachments = [];
  24288. for ( let i = 0; i < textures.length; i ++ ) {
  24289. const textureData = this.get( textures[ i ] );
  24290. const textureView = textureData.texture.createView( {
  24291. baseMipLevel: renderContext.activeMipmapLevel,
  24292. mipLevelCount: 1,
  24293. baseArrayLayer: renderContext.activeCubeFace,
  24294. dimension: GPUTextureViewDimension.TwoD
  24295. } );
  24296. let view, resolveTarget;
  24297. if ( textureData.msaaTexture !== undefined ) {
  24298. view = textureData.msaaTexture.createView();
  24299. resolveTarget = textureView;
  24300. } else {
  24301. view = textureView;
  24302. resolveTarget = undefined;
  24303. }
  24304. colorAttachments.push( {
  24305. view,
  24306. resolveTarget,
  24307. loadOp: GPULoadOp.Load,
  24308. storeOp: GPUStoreOp.Store
  24309. } );
  24310. }
  24311. descriptor = {
  24312. colorAttachments,
  24313. };
  24314. if ( renderContext.depth ) {
  24315. const depthTextureData = this.get( renderContext.depthTexture );
  24316. const depthStencilAttachment = {
  24317. view: depthTextureData.texture.createView()
  24318. };
  24319. descriptor.depthStencilAttachment = depthStencilAttachment;
  24320. }
  24321. descriptors[ cacheKey ] = descriptor;
  24322. renderTargetData.width = renderTarget.width;
  24323. renderTargetData.height = renderTarget.height;
  24324. renderTargetData.samples = renderTarget.samples;
  24325. renderTargetData.activeMipmapLevel = renderTarget.activeMipmapLevel;
  24326. }
  24327. return descriptor;
  24328. }
  24329. beginRender( renderContext ) {
  24330. const renderContextData = this.get( renderContext );
  24331. const device = this.device;
  24332. const occlusionQueryCount = renderContext.occlusionQueryCount;
  24333. let occlusionQuerySet;
  24334. if ( occlusionQueryCount > 0 ) {
  24335. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  24336. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  24337. // Get a reference to the array of objects with queries. The renderContextData property
  24338. // can be changed by another render pass before the buffer.mapAsyc() completes.
  24339. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  24340. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  24341. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  24342. //
  24343. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  24344. renderContextData.occlusionQuerySet = occlusionQuerySet;
  24345. renderContextData.occlusionQueryIndex = 0;
  24346. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  24347. renderContextData.lastOcclusionObject = null;
  24348. }
  24349. let descriptor;
  24350. if ( renderContext.textures === null ) {
  24351. descriptor = this._getDefaultRenderPassDescriptor();
  24352. } else {
  24353. descriptor = this._getRenderPassDescriptor( renderContext );
  24354. }
  24355. this.initTimestampQuery( renderContext, descriptor );
  24356. descriptor.occlusionQuerySet = occlusionQuerySet;
  24357. const depthStencilAttachment = descriptor.depthStencilAttachment;
  24358. if ( renderContext.textures !== null ) {
  24359. const colorAttachments = descriptor.colorAttachments;
  24360. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  24361. const colorAttachment = colorAttachments[ i ];
  24362. if ( renderContext.clearColor ) {
  24363. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  24364. colorAttachment.loadOp = GPULoadOp.Clear;
  24365. colorAttachment.storeOp = GPUStoreOp.Store;
  24366. } else {
  24367. colorAttachment.loadOp = GPULoadOp.Load;
  24368. colorAttachment.storeOp = GPUStoreOp.Store;
  24369. }
  24370. }
  24371. } else {
  24372. const colorAttachment = descriptor.colorAttachments[ 0 ];
  24373. if ( renderContext.clearColor ) {
  24374. colorAttachment.clearValue = renderContext.clearColorValue;
  24375. colorAttachment.loadOp = GPULoadOp.Clear;
  24376. colorAttachment.storeOp = GPUStoreOp.Store;
  24377. } else {
  24378. colorAttachment.loadOp = GPULoadOp.Load;
  24379. colorAttachment.storeOp = GPUStoreOp.Store;
  24380. }
  24381. }
  24382. //
  24383. if ( renderContext.depth ) {
  24384. if ( renderContext.clearDepth ) {
  24385. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  24386. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  24387. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  24388. } else {
  24389. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  24390. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  24391. }
  24392. }
  24393. if ( renderContext.stencil ) {
  24394. if ( renderContext.clearStencil ) {
  24395. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  24396. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  24397. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  24398. } else {
  24399. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  24400. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  24401. }
  24402. }
  24403. //
  24404. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  24405. const currentPass = encoder.beginRenderPass( descriptor );
  24406. //
  24407. renderContextData.descriptor = descriptor;
  24408. renderContextData.encoder = encoder;
  24409. renderContextData.currentPass = currentPass;
  24410. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  24411. renderContextData.renderBundles = [];
  24412. //
  24413. if ( renderContext.viewport ) {
  24414. this.updateViewport( renderContext );
  24415. }
  24416. if ( renderContext.scissor ) {
  24417. const { x, y, width, height } = renderContext.scissorValue;
  24418. currentPass.setScissorRect( x, y, width, height );
  24419. }
  24420. }
  24421. finishRender( renderContext ) {
  24422. const renderContextData = this.get( renderContext );
  24423. const occlusionQueryCount = renderContext.occlusionQueryCount;
  24424. if ( renderContextData.renderBundles.length > 0 ) {
  24425. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  24426. }
  24427. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  24428. renderContextData.currentPass.endOcclusionQuery();
  24429. }
  24430. renderContextData.currentPass.end();
  24431. if ( occlusionQueryCount > 0 ) {
  24432. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  24433. //
  24434. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  24435. if ( queryResolveBuffer === undefined ) {
  24436. queryResolveBuffer = this.device.createBuffer(
  24437. {
  24438. size: bufferSize,
  24439. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  24440. }
  24441. );
  24442. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  24443. }
  24444. //
  24445. const readBuffer = this.device.createBuffer(
  24446. {
  24447. size: bufferSize,
  24448. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  24449. }
  24450. );
  24451. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  24452. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  24453. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  24454. renderContextData.occlusionQueryBuffer = readBuffer;
  24455. //
  24456. this.resolveOccludedAsync( renderContext );
  24457. }
  24458. this.prepareTimestampBuffer( renderContext, renderContextData.encoder );
  24459. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  24460. //
  24461. if ( renderContext.textures !== null ) {
  24462. const textures = renderContext.textures;
  24463. for ( let i = 0; i < textures.length; i ++ ) {
  24464. const texture = textures[ i ];
  24465. if ( texture.generateMipmaps === true ) {
  24466. this.textureUtils.generateMipmaps( texture );
  24467. }
  24468. }
  24469. }
  24470. }
  24471. isOccluded( renderContext, object ) {
  24472. const renderContextData = this.get( renderContext );
  24473. return renderContextData.occluded && renderContextData.occluded.has( object );
  24474. }
  24475. async resolveOccludedAsync( renderContext ) {
  24476. const renderContextData = this.get( renderContext );
  24477. // handle occlusion query results
  24478. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  24479. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  24480. const occluded = new WeakSet();
  24481. renderContextData.currentOcclusionQueryObjects = null;
  24482. renderContextData.currentOcclusionQueryBuffer = null;
  24483. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  24484. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  24485. const results = new BigUint64Array( buffer );
  24486. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  24487. if ( results[ i ] !== BigInt( 0 ) ) {
  24488. occluded.add( currentOcclusionQueryObjects[ i ] );
  24489. }
  24490. }
  24491. currentOcclusionQueryBuffer.destroy();
  24492. renderContextData.occluded = occluded;
  24493. }
  24494. }
  24495. updateViewport( renderContext ) {
  24496. const { currentPass } = this.get( renderContext );
  24497. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  24498. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  24499. }
  24500. clear( color, depth, stencil, renderTargetData = null ) {
  24501. const device = this.device;
  24502. const renderer = this.renderer;
  24503. let colorAttachments = [];
  24504. let depthStencilAttachment;
  24505. let clearValue;
  24506. let supportsDepth;
  24507. let supportsStencil;
  24508. if ( color ) {
  24509. const clearColor = this.getClearColor();
  24510. if ( this.renderer.alpha === true ) {
  24511. // premultiply alpha
  24512. const a = clearColor.a;
  24513. clearValue = { r: clearColor.r * a, g: clearColor.g * a, b: clearColor.b * a, a: a };
  24514. } else {
  24515. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  24516. }
  24517. }
  24518. if ( renderTargetData === null ) {
  24519. supportsDepth = renderer.depth;
  24520. supportsStencil = renderer.stencil;
  24521. const descriptor = this._getDefaultRenderPassDescriptor();
  24522. if ( color ) {
  24523. colorAttachments = descriptor.colorAttachments;
  24524. const colorAttachment = colorAttachments[ 0 ];
  24525. colorAttachment.clearValue = clearValue;
  24526. colorAttachment.loadOp = GPULoadOp.Clear;
  24527. colorAttachment.storeOp = GPUStoreOp.Store;
  24528. }
  24529. if ( supportsDepth || supportsStencil ) {
  24530. depthStencilAttachment = descriptor.depthStencilAttachment;
  24531. }
  24532. } else {
  24533. supportsDepth = renderTargetData.depth;
  24534. supportsStencil = renderTargetData.stencil;
  24535. if ( color ) {
  24536. for ( const texture of renderTargetData.textures ) {
  24537. const textureData = this.get( texture );
  24538. const textureView = textureData.texture.createView();
  24539. let view, resolveTarget;
  24540. if ( textureData.msaaTexture !== undefined ) {
  24541. view = textureData.msaaTexture.createView();
  24542. resolveTarget = textureView;
  24543. } else {
  24544. view = textureView;
  24545. resolveTarget = undefined;
  24546. }
  24547. colorAttachments.push( {
  24548. view,
  24549. resolveTarget,
  24550. clearValue,
  24551. loadOp: GPULoadOp.Clear,
  24552. storeOp: GPUStoreOp.Store
  24553. } );
  24554. }
  24555. }
  24556. if ( supportsDepth || supportsStencil ) {
  24557. const depthTextureData = this.get( renderTargetData.depthTexture );
  24558. depthStencilAttachment = {
  24559. view: depthTextureData.texture.createView()
  24560. };
  24561. }
  24562. }
  24563. //
  24564. if ( supportsDepth ) {
  24565. if ( depth ) {
  24566. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  24567. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  24568. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  24569. } else {
  24570. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  24571. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  24572. }
  24573. }
  24574. //
  24575. if ( supportsStencil ) {
  24576. if ( stencil ) {
  24577. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  24578. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  24579. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  24580. } else {
  24581. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  24582. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  24583. }
  24584. }
  24585. //
  24586. const encoder = device.createCommandEncoder( {} );
  24587. const currentPass = encoder.beginRenderPass( {
  24588. colorAttachments,
  24589. depthStencilAttachment
  24590. } );
  24591. currentPass.end();
  24592. device.queue.submit( [ encoder.finish() ] );
  24593. }
  24594. // compute
  24595. beginCompute( computeGroup ) {
  24596. const groupGPU = this.get( computeGroup );
  24597. const descriptor = {};
  24598. this.initTimestampQuery( computeGroup, descriptor );
  24599. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder();
  24600. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  24601. }
  24602. compute( computeGroup, computeNode, bindings, pipeline ) {
  24603. const { passEncoderGPU } = this.get( computeGroup );
  24604. // pipeline
  24605. const pipelineGPU = this.get( pipeline ).pipeline;
  24606. passEncoderGPU.setPipeline( pipelineGPU );
  24607. // bind groups
  24608. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  24609. const bindGroup = bindings[ i ];
  24610. const bindingsData = this.get( bindGroup );
  24611. passEncoderGPU.setBindGroup( i, bindingsData.group );
  24612. }
  24613. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  24614. const computeNodeData = this.get( computeNode );
  24615. if ( computeNodeData.dispatchSize === undefined ) computeNodeData.dispatchSize = { x: 0, y: 1, z: 1 };
  24616. const { dispatchSize } = computeNodeData;
  24617. if ( computeNode.dispatchCount > maxComputeWorkgroupsPerDimension ) {
  24618. dispatchSize.x = Math.min( computeNode.dispatchCount, maxComputeWorkgroupsPerDimension );
  24619. dispatchSize.y = Math.ceil( computeNode.dispatchCount / maxComputeWorkgroupsPerDimension );
  24620. } else {
  24621. dispatchSize.x = computeNode.dispatchCount;
  24622. }
  24623. passEncoderGPU.dispatchWorkgroups(
  24624. dispatchSize.x,
  24625. dispatchSize.y,
  24626. dispatchSize.z
  24627. );
  24628. }
  24629. finishCompute( computeGroup ) {
  24630. const groupData = this.get( computeGroup );
  24631. groupData.passEncoderGPU.end();
  24632. this.prepareTimestampBuffer( computeGroup, groupData.cmdEncoderGPU );
  24633. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  24634. }
  24635. async waitForGPU() {
  24636. await this.device.queue.onSubmittedWorkDone();
  24637. }
  24638. // render object
  24639. draw( renderObject, info ) {
  24640. const { object, context, pipeline } = renderObject;
  24641. const bindings = renderObject.getBindings();
  24642. const renderContextData = this.get( context );
  24643. const pipelineGPU = this.get( pipeline ).pipeline;
  24644. const currentSets = renderContextData.currentSets;
  24645. const passEncoderGPU = renderContextData.currentPass;
  24646. const drawParams = renderObject.getDrawParameters();
  24647. if ( drawParams === null ) return;
  24648. // pipeline
  24649. if ( currentSets.pipeline !== pipelineGPU ) {
  24650. passEncoderGPU.setPipeline( pipelineGPU );
  24651. currentSets.pipeline = pipelineGPU;
  24652. }
  24653. // bind groups
  24654. const currentBindingGroups = currentSets.bindingGroups;
  24655. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  24656. const bindGroup = bindings[ i ];
  24657. const bindingsData = this.get( bindGroup );
  24658. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  24659. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  24660. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  24661. }
  24662. }
  24663. // attributes
  24664. const index = renderObject.getIndex();
  24665. const hasIndex = ( index !== null );
  24666. // index
  24667. if ( hasIndex === true ) {
  24668. if ( currentSets.index !== index ) {
  24669. const buffer = this.get( index ).buffer;
  24670. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  24671. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  24672. currentSets.index = index;
  24673. }
  24674. }
  24675. // vertex buffers
  24676. const vertexBuffers = renderObject.getVertexBuffers();
  24677. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  24678. const vertexBuffer = vertexBuffers[ i ];
  24679. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  24680. const buffer = this.get( vertexBuffer ).buffer;
  24681. passEncoderGPU.setVertexBuffer( i, buffer );
  24682. currentSets.attributes[ i ] = vertexBuffer;
  24683. }
  24684. }
  24685. // occlusion queries - handle multiple consecutive draw calls for an object
  24686. if ( renderContextData.occlusionQuerySet !== undefined ) {
  24687. const lastObject = renderContextData.lastOcclusionObject;
  24688. if ( lastObject !== object ) {
  24689. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  24690. passEncoderGPU.endOcclusionQuery();
  24691. renderContextData.occlusionQueryIndex ++;
  24692. }
  24693. if ( object.occlusionTest === true ) {
  24694. passEncoderGPU.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  24695. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  24696. }
  24697. renderContextData.lastOcclusionObject = object;
  24698. }
  24699. }
  24700. // draw
  24701. if ( object.isBatchedMesh === true ) {
  24702. const starts = object._multiDrawStarts;
  24703. const counts = object._multiDrawCounts;
  24704. const drawCount = object._multiDrawCount;
  24705. const drawInstances = object._multiDrawInstances;
  24706. const bytesPerElement = hasIndex ? index.array.BYTES_PER_ELEMENT : 1;
  24707. for ( let i = 0; i < drawCount; i ++ ) {
  24708. const count = drawInstances ? drawInstances[ i ] : 1;
  24709. const firstInstance = count > 1 ? 0 : i;
  24710. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / bytesPerElement, 0, firstInstance );
  24711. }
  24712. } else if ( hasIndex === true ) {
  24713. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  24714. const indirect = renderObject.getIndirect();
  24715. if ( indirect !== null ) {
  24716. const buffer = this.get( indirect ).buffer;
  24717. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  24718. } else {
  24719. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  24720. }
  24721. info.update( object, indexCount, instanceCount );
  24722. } else {
  24723. const { vertexCount, instanceCount, firstVertex } = drawParams;
  24724. const indirect = renderObject.getIndirect();
  24725. if ( indirect !== null ) {
  24726. const buffer = this.get( indirect ).buffer;
  24727. passEncoderGPU.drawIndirect( buffer, 0 );
  24728. } else {
  24729. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  24730. }
  24731. info.update( object, vertexCount, instanceCount );
  24732. }
  24733. }
  24734. // cache key
  24735. needsRenderUpdate( renderObject ) {
  24736. const data = this.get( renderObject );
  24737. const { object, material } = renderObject;
  24738. const utils = this.utils;
  24739. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  24740. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  24741. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  24742. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  24743. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  24744. let needsUpdate = false;
  24745. if ( data.material !== material || data.materialVersion !== material.version ||
  24746. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  24747. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  24748. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  24749. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  24750. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  24751. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  24752. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  24753. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  24754. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  24755. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  24756. data.primitiveTopology !== primitiveTopology ||
  24757. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  24758. ) {
  24759. data.material = material; data.materialVersion = material.version;
  24760. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  24761. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  24762. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  24763. data.colorWrite = material.colorWrite;
  24764. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  24765. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  24766. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  24767. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  24768. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  24769. data.sampleCount = sampleCount;
  24770. data.colorSpace = colorSpace;
  24771. data.colorFormat = colorFormat;
  24772. data.depthStencilFormat = depthStencilFormat;
  24773. data.primitiveTopology = primitiveTopology;
  24774. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  24775. needsUpdate = true;
  24776. }
  24777. return needsUpdate;
  24778. }
  24779. getRenderCacheKey( renderObject ) {
  24780. const { object, material } = renderObject;
  24781. const utils = this.utils;
  24782. const renderContext = renderObject.context;
  24783. return [
  24784. material.transparent, material.blending, material.premultipliedAlpha,
  24785. material.blendSrc, material.blendDst, material.blendEquation,
  24786. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  24787. material.colorWrite,
  24788. material.depthWrite, material.depthTest, material.depthFunc,
  24789. material.stencilWrite, material.stencilFunc,
  24790. material.stencilFail, material.stencilZFail, material.stencilZPass,
  24791. material.stencilFuncMask, material.stencilWriteMask,
  24792. material.side,
  24793. utils.getSampleCountRenderContext( renderContext ),
  24794. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  24795. utils.getPrimitiveTopology( object, material ),
  24796. renderObject.getGeometryCacheKey(),
  24797. renderObject.clippingContextCacheKey
  24798. ].join();
  24799. }
  24800. // textures
  24801. createSampler( texture ) {
  24802. this.textureUtils.createSampler( texture );
  24803. }
  24804. destroySampler( texture ) {
  24805. this.textureUtils.destroySampler( texture );
  24806. }
  24807. createDefaultTexture( texture ) {
  24808. this.textureUtils.createDefaultTexture( texture );
  24809. }
  24810. createTexture( texture, options ) {
  24811. this.textureUtils.createTexture( texture, options );
  24812. }
  24813. updateTexture( texture, options ) {
  24814. this.textureUtils.updateTexture( texture, options );
  24815. }
  24816. generateMipmaps( texture ) {
  24817. this.textureUtils.generateMipmaps( texture );
  24818. }
  24819. destroyTexture( texture ) {
  24820. this.textureUtils.destroyTexture( texture );
  24821. }
  24822. copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  24823. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  24824. }
  24825. initTimestampQuery( renderContext, descriptor ) {
  24826. if ( ! this.trackTimestamp ) return;
  24827. const renderContextData = this.get( renderContext );
  24828. if ( ! renderContextData.timeStampQuerySet ) {
  24829. const type = renderContext.isComputeNode ? 'compute' : 'render';
  24830. const timeStampQuerySet = this.device.createQuerySet( { type: 'timestamp', count: 2, label: `timestamp_${type}_${renderContext.id}` } );
  24831. const timestampWrites = {
  24832. querySet: timeStampQuerySet,
  24833. beginningOfPassWriteIndex: 0, // Write timestamp in index 0 when pass begins.
  24834. endOfPassWriteIndex: 1, // Write timestamp in index 1 when pass ends.
  24835. };
  24836. Object.assign( descriptor, { timestampWrites } );
  24837. renderContextData.timeStampQuerySet = timeStampQuerySet;
  24838. }
  24839. }
  24840. // timestamp utils
  24841. prepareTimestampBuffer( renderContext, encoder ) {
  24842. if ( ! this.trackTimestamp ) return;
  24843. const renderContextData = this.get( renderContext );
  24844. const size = 2 * BigInt64Array.BYTES_PER_ELEMENT;
  24845. if ( renderContextData.currentTimestampQueryBuffers === undefined ) {
  24846. renderContextData.currentTimestampQueryBuffers = {
  24847. resolveBuffer: this.device.createBuffer( {
  24848. label: 'timestamp resolve buffer',
  24849. size: size,
  24850. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC,
  24851. } ),
  24852. resultBuffer: this.device.createBuffer( {
  24853. label: 'timestamp result buffer',
  24854. size: size,
  24855. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
  24856. } )
  24857. };
  24858. }
  24859. const { resolveBuffer, resultBuffer } = renderContextData.currentTimestampQueryBuffers;
  24860. encoder.resolveQuerySet( renderContextData.timeStampQuerySet, 0, 2, resolveBuffer, 0 );
  24861. if ( resultBuffer.mapState === 'unmapped' ) {
  24862. encoder.copyBufferToBuffer( resolveBuffer, 0, resultBuffer, 0, size );
  24863. }
  24864. }
  24865. async resolveTimestampAsync( renderContext, type = 'render' ) {
  24866. if ( ! this.trackTimestamp ) return;
  24867. const renderContextData = this.get( renderContext );
  24868. if ( renderContextData.currentTimestampQueryBuffers === undefined ) return;
  24869. const { resultBuffer } = renderContextData.currentTimestampQueryBuffers;
  24870. await this.device.queue.onSubmittedWorkDone();
  24871. if ( resultBuffer.mapState === 'unmapped' ) {
  24872. resultBuffer.mapAsync( GPUMapMode.READ ).then( () => {
  24873. const times = new BigUint64Array( resultBuffer.getMappedRange() );
  24874. const duration = Number( times[ 1 ] - times[ 0 ] ) / 1000000;
  24875. this.renderer.info.updateTimestamp( type, duration );
  24876. resultBuffer.unmap();
  24877. } );
  24878. }
  24879. }
  24880. // node builder
  24881. createNodeBuilder( object, renderer ) {
  24882. return new WGSLNodeBuilder( object, renderer );
  24883. }
  24884. // program
  24885. createProgram( program ) {
  24886. const programGPU = this.get( program );
  24887. programGPU.module = {
  24888. module: this.device.createShaderModule( { code: program.code, label: program.stage } ),
  24889. entryPoint: 'main'
  24890. };
  24891. }
  24892. destroyProgram( program ) {
  24893. this.delete( program );
  24894. }
  24895. // pipelines
  24896. createRenderPipeline( renderObject, promises ) {
  24897. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  24898. }
  24899. createComputePipeline( computePipeline, bindings ) {
  24900. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  24901. }
  24902. beginBundle( renderContext ) {
  24903. const renderContextData = this.get( renderContext );
  24904. renderContextData._currentPass = renderContextData.currentPass;
  24905. renderContextData._currentSets = renderContextData.currentSets;
  24906. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  24907. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  24908. }
  24909. finishBundle( renderContext, bundle ) {
  24910. const renderContextData = this.get( renderContext );
  24911. const bundleEncoder = renderContextData.currentPass;
  24912. const bundleGPU = bundleEncoder.finish();
  24913. this.get( bundle ).bundleGPU = bundleGPU;
  24914. // restore render pass state
  24915. renderContextData.currentSets = renderContextData._currentSets;
  24916. renderContextData.currentPass = renderContextData._currentPass;
  24917. }
  24918. addBundle( renderContext, bundle ) {
  24919. const renderContextData = this.get( renderContext );
  24920. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  24921. }
  24922. // bindings
  24923. createBindings( bindGroup, bindings, cacheIndex, version ) {
  24924. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  24925. }
  24926. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  24927. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  24928. }
  24929. updateBinding( binding ) {
  24930. this.bindingUtils.updateBinding( binding );
  24931. }
  24932. // attributes
  24933. createIndexAttribute( attribute ) {
  24934. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  24935. }
  24936. createAttribute( attribute ) {
  24937. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  24938. }
  24939. createStorageAttribute( attribute ) {
  24940. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  24941. }
  24942. createIndirectStorageAttribute( attribute ) {
  24943. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  24944. }
  24945. updateAttribute( attribute ) {
  24946. this.attributeUtils.updateAttribute( attribute );
  24947. }
  24948. destroyAttribute( attribute ) {
  24949. this.attributeUtils.destroyAttribute( attribute );
  24950. }
  24951. // canvas
  24952. updateSize() {
  24953. this.colorBuffer = this.textureUtils.getColorBuffer();
  24954. this.defaultRenderPassdescriptor = null;
  24955. }
  24956. // utils public
  24957. getMaxAnisotropy() {
  24958. return 16;
  24959. }
  24960. hasFeature( name ) {
  24961. return this.device.features.has( name );
  24962. }
  24963. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  24964. let dstX = 0;
  24965. let dstY = 0;
  24966. let dstLayer = 0;
  24967. let srcX = 0;
  24968. let srcY = 0;
  24969. let srcLayer = 0;
  24970. let srcWidth = srcTexture.image.width;
  24971. let srcHeight = srcTexture.image.height;
  24972. if ( srcRegion !== null ) {
  24973. srcX = srcRegion.x;
  24974. srcY = srcRegion.y;
  24975. srcLayer = srcRegion.z || 0;
  24976. srcWidth = srcRegion.width;
  24977. srcHeight = srcRegion.height;
  24978. }
  24979. if ( dstPosition !== null ) {
  24980. dstX = dstPosition.x;
  24981. dstY = dstPosition.y;
  24982. dstLayer = dstPosition.z || 0;
  24983. }
  24984. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  24985. const sourceGPU = this.get( srcTexture ).texture;
  24986. const destinationGPU = this.get( dstTexture ).texture;
  24987. encoder.copyTextureToTexture(
  24988. {
  24989. texture: sourceGPU,
  24990. mipLevel: level,
  24991. origin: { x: srcX, y: srcY, z: srcLayer }
  24992. },
  24993. {
  24994. texture: destinationGPU,
  24995. mipLevel: level,
  24996. origin: { x: dstX, y: dstY, z: dstLayer }
  24997. },
  24998. [
  24999. srcWidth,
  25000. srcHeight,
  25001. 1
  25002. ]
  25003. );
  25004. this.device.queue.submit( [ encoder.finish() ] );
  25005. }
  25006. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  25007. const renderContextData = this.get( renderContext );
  25008. let sourceGPU = null;
  25009. if ( renderContext.renderTarget ) {
  25010. if ( texture.isDepthTexture ) {
  25011. sourceGPU = this.get( renderContext.depthTexture ).texture;
  25012. } else {
  25013. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  25014. }
  25015. } else {
  25016. if ( texture.isDepthTexture ) {
  25017. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  25018. } else {
  25019. sourceGPU = this.context.getCurrentTexture();
  25020. }
  25021. }
  25022. const destinationGPU = this.get( texture ).texture;
  25023. if ( sourceGPU.format !== destinationGPU.format ) {
  25024. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  25025. return;
  25026. }
  25027. let encoder;
  25028. if ( renderContextData.currentPass ) {
  25029. renderContextData.currentPass.end();
  25030. encoder = renderContextData.encoder;
  25031. } else {
  25032. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  25033. }
  25034. encoder.copyTextureToTexture(
  25035. {
  25036. texture: sourceGPU,
  25037. origin: [ rectangle.x, rectangle.y, 0 ],
  25038. },
  25039. {
  25040. texture: destinationGPU
  25041. },
  25042. [
  25043. rectangle.z,
  25044. rectangle.w
  25045. ]
  25046. );
  25047. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  25048. if ( renderContextData.currentPass ) {
  25049. const { descriptor } = renderContextData;
  25050. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  25051. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  25052. }
  25053. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  25054. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  25055. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  25056. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  25057. if ( renderContext.viewport ) {
  25058. this.updateViewport( renderContext );
  25059. }
  25060. if ( renderContext.scissor ) {
  25061. const { x, y, width, height } = renderContext.scissorValue;
  25062. renderContextData.currentPass.setScissorRect( x, y, width, height );
  25063. }
  25064. } else {
  25065. this.device.queue.submit( [ encoder.finish() ] );
  25066. }
  25067. }
  25068. }
  25069. class IESSpotLight extends SpotLight {
  25070. constructor( color, intensity, distance, angle, penumbra, decay ) {
  25071. super( color, intensity, distance, angle, penumbra, decay );
  25072. this.iesMap = null;
  25073. }
  25074. copy( source, recursive ) {
  25075. super.copy( source, recursive );
  25076. this.iesMap = source.iesMap;
  25077. return this;
  25078. }
  25079. }
  25080. class StandardNodeLibrary extends NodeLibrary {
  25081. constructor() {
  25082. super();
  25083. this.addMaterial( MeshPhongNodeMaterial, 'MeshPhongMaterial' );
  25084. this.addMaterial( MeshStandardNodeMaterial, 'MeshStandardMaterial' );
  25085. this.addMaterial( MeshPhysicalNodeMaterial, 'MeshPhysicalMaterial' );
  25086. this.addMaterial( MeshToonNodeMaterial, 'MeshToonMaterial' );
  25087. this.addMaterial( MeshBasicNodeMaterial, 'MeshBasicMaterial' );
  25088. this.addMaterial( MeshLambertNodeMaterial, 'MeshLambertMaterial' );
  25089. this.addMaterial( MeshNormalNodeMaterial, 'MeshNormalMaterial' );
  25090. this.addMaterial( MeshMatcapNodeMaterial, 'MeshMatcapMaterial' );
  25091. this.addMaterial( LineBasicNodeMaterial, 'LineBasicMaterial' );
  25092. this.addMaterial( LineDashedNodeMaterial, 'LineDashedMaterial' );
  25093. this.addMaterial( PointsNodeMaterial, 'PointsMaterial' );
  25094. this.addMaterial( SpriteNodeMaterial, 'SpriteMaterial' );
  25095. this.addMaterial( ShadowNodeMaterial, 'ShadowMaterial' );
  25096. this.addLight( PointLightNode, PointLight );
  25097. this.addLight( DirectionalLightNode, DirectionalLight );
  25098. this.addLight( RectAreaLightNode, RectAreaLight );
  25099. this.addLight( SpotLightNode, SpotLight );
  25100. this.addLight( AmbientLightNode, AmbientLight );
  25101. this.addLight( HemisphereLightNode, HemisphereLight );
  25102. this.addLight( LightProbeNode, LightProbe );
  25103. this.addLight( IESSpotLightNode, IESSpotLight );
  25104. this.addToneMapping( linearToneMapping, LinearToneMapping );
  25105. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  25106. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  25107. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  25108. this.addToneMapping( agxToneMapping, AgXToneMapping );
  25109. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  25110. }
  25111. }
  25112. /*
  25113. const debugHandler = {
  25114. get: function ( target, name ) {
  25115. // Add |update
  25116. if ( /^(create|destroy)/.test( name ) ) console.log( 'WebGPUBackend.' + name );
  25117. return target[ name ];
  25118. }
  25119. };
  25120. */
  25121. class WebGPURenderer extends Renderer {
  25122. constructor( parameters = {} ) {
  25123. let BackendClass;
  25124. if ( parameters.forceWebGL ) {
  25125. BackendClass = WebGLBackend;
  25126. } else {
  25127. BackendClass = WebGPUBackend;
  25128. parameters.getFallback = () => {
  25129. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  25130. return new WebGLBackend( parameters );
  25131. };
  25132. }
  25133. const backend = new BackendClass( parameters );
  25134. //super( new Proxy( backend, debugHandler ) );
  25135. super( backend, parameters );
  25136. this.library = new StandardNodeLibrary();
  25137. this.isWebGPURenderer = true;
  25138. }
  25139. }
  25140. class BundleGroup extends Group {
  25141. constructor() {
  25142. super();
  25143. this.isBundleGroup = true;
  25144. this.type = 'BundleGroup';
  25145. this.static = true;
  25146. this.version = 0;
  25147. }
  25148. set needsUpdate( value ) {
  25149. if ( value === true ) this.version ++;
  25150. }
  25151. }
  25152. const _material = /*@__PURE__*/ new NodeMaterial();
  25153. const _quadMesh = /*@__PURE__*/ new QuadMesh( _material );
  25154. class PostProcessing {
  25155. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  25156. this.renderer = renderer;
  25157. this.outputNode = outputNode;
  25158. this.outputColorTransform = true;
  25159. this.needsUpdate = true;
  25160. _material.name = 'PostProcessing';
  25161. }
  25162. render() {
  25163. this.update();
  25164. const renderer = this.renderer;
  25165. const toneMapping = renderer.toneMapping;
  25166. const outputColorSpace = renderer.outputColorSpace;
  25167. renderer.toneMapping = NoToneMapping;
  25168. renderer.outputColorSpace = LinearSRGBColorSpace;
  25169. //
  25170. _quadMesh.render( renderer );
  25171. //
  25172. renderer.toneMapping = toneMapping;
  25173. renderer.outputColorSpace = outputColorSpace;
  25174. }
  25175. update() {
  25176. if ( this.needsUpdate === true ) {
  25177. const renderer = this.renderer;
  25178. const toneMapping = renderer.toneMapping;
  25179. const outputColorSpace = renderer.outputColorSpace;
  25180. _quadMesh.material.fragmentNode = this.outputColorTransform === true ? renderOutput( this.outputNode, toneMapping, outputColorSpace ) : this.outputNode.context( { toneMapping, outputColorSpace } );
  25181. _quadMesh.material.needsUpdate = true;
  25182. this.needsUpdate = false;
  25183. }
  25184. }
  25185. async renderAsync() {
  25186. this.update();
  25187. const renderer = this.renderer;
  25188. const toneMapping = renderer.toneMapping;
  25189. const outputColorSpace = renderer.outputColorSpace;
  25190. renderer.toneMapping = NoToneMapping;
  25191. renderer.outputColorSpace = LinearSRGBColorSpace;
  25192. //
  25193. await _quadMesh.renderAsync( renderer );
  25194. //
  25195. renderer.toneMapping = toneMapping;
  25196. renderer.outputColorSpace = outputColorSpace;
  25197. }
  25198. }
  25199. // renderer state
  25200. function saveRendererState( renderer, state = {} ) {
  25201. state.toneMapping = renderer.toneMapping;
  25202. state.toneMappingExposure = renderer.toneMappingExposure;
  25203. state.outputColorSpace = renderer.outputColorSpace;
  25204. state.renderTarget = renderer.getRenderTarget();
  25205. state.activeCubeFace = renderer.getActiveCubeFace();
  25206. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  25207. state.renderObjectFunction = renderer.getRenderObjectFunction();
  25208. state.pixelRatio = renderer.getPixelRatio();
  25209. state.mrt = renderer.getMRT();
  25210. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  25211. state.clearAlpha = renderer.getClearAlpha();
  25212. state.autoClear = renderer.autoClear;
  25213. state.scissorTest = renderer.getScissorTest();
  25214. return state;
  25215. }
  25216. function resetRendererState( renderer, state ) {
  25217. state = saveRendererState( renderer, state );
  25218. renderer.setMRT( null );
  25219. renderer.setRenderObjectFunction( null );
  25220. renderer.setClearColor( 0x000000, 1 );
  25221. renderer.autoClear = true;
  25222. return state;
  25223. }
  25224. function restoreRendererState( renderer, state ) {
  25225. renderer.toneMapping = state.toneMapping;
  25226. renderer.toneMappingExposure = state.toneMappingExposure;
  25227. renderer.outputColorSpace = state.outputColorSpace;
  25228. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  25229. renderer.setRenderObjectFunction( state.renderObjectFunction );
  25230. renderer.setPixelRatio( state.pixelRatio );
  25231. renderer.setMRT( state.mrt );
  25232. renderer.setClearColor( state.clearColor, state.clearAlpha );
  25233. renderer.autoClear = state.autoClear;
  25234. renderer.setScissorTest( state.scissorTest );
  25235. }
  25236. // renderer and scene state
  25237. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  25238. state = saveRendererState( renderer, state );
  25239. state.background = scene.background;
  25240. state.backgroundNode = scene.backgroundNode;
  25241. state.overrideMaterial = scene.overrideMaterial;
  25242. return state;
  25243. }
  25244. function resetRendererAndSceneState( renderer, scene, state ) {
  25245. state = saveRendererAndSceneState( renderer, scene, state );
  25246. scene.background = null;
  25247. scene.backgroundNode = null;
  25248. scene.overrideMaterial = null;
  25249. return state;
  25250. }
  25251. function restoreRendererAndSceneState( renderer, scene, state ) {
  25252. restoreRendererState( renderer, state );
  25253. scene.background = state.background;
  25254. scene.backgroundNode = state.backgroundNode;
  25255. scene.overrideMaterial = state.overrideMaterial;
  25256. }
  25257. var PostProcessingUtils = /*#__PURE__*/Object.freeze({
  25258. __proto__: null,
  25259. resetRendererAndSceneState: resetRendererAndSceneState,
  25260. resetRendererState: resetRendererState,
  25261. restoreRendererAndSceneState: restoreRendererAndSceneState,
  25262. restoreRendererState: restoreRendererState,
  25263. saveRendererAndSceneState: saveRendererAndSceneState,
  25264. saveRendererState: saveRendererState
  25265. });
  25266. class StorageTexture extends Texture {
  25267. constructor( width = 1, height = 1 ) {
  25268. super();
  25269. this.image = { width, height };
  25270. this.magFilter = LinearFilter;
  25271. this.minFilter = LinearFilter;
  25272. this.isStorageTexture = true;
  25273. }
  25274. }
  25275. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  25276. constructor( array, itemSize ) {
  25277. super( array, itemSize, Uint32Array );
  25278. this.isIndirectStorageBufferAttribute = true;
  25279. }
  25280. }
  25281. class NodeLoader extends Loader {
  25282. constructor( manager ) {
  25283. super( manager );
  25284. this.textures = {};
  25285. this.nodes = {};
  25286. }
  25287. load( url, onLoad, onProgress, onError ) {
  25288. const loader = new FileLoader( this.manager );
  25289. loader.setPath( this.path );
  25290. loader.setRequestHeader( this.requestHeader );
  25291. loader.setWithCredentials( this.withCredentials );
  25292. loader.load( url, ( text ) => {
  25293. try {
  25294. onLoad( this.parse( JSON.parse( text ) ) );
  25295. } catch ( e ) {
  25296. if ( onError ) {
  25297. onError( e );
  25298. } else {
  25299. console.error( e );
  25300. }
  25301. this.manager.itemError( url );
  25302. }
  25303. }, onProgress, onError );
  25304. }
  25305. parseNodes( json ) {
  25306. const nodes = {};
  25307. if ( json !== undefined ) {
  25308. for ( const nodeJSON of json ) {
  25309. const { uuid, type } = nodeJSON;
  25310. nodes[ uuid ] = this.createNodeFromType( type );
  25311. nodes[ uuid ].uuid = uuid;
  25312. }
  25313. const meta = { nodes, textures: this.textures };
  25314. for ( const nodeJSON of json ) {
  25315. nodeJSON.meta = meta;
  25316. const node = nodes[ nodeJSON.uuid ];
  25317. node.deserialize( nodeJSON );
  25318. delete nodeJSON.meta;
  25319. }
  25320. }
  25321. return nodes;
  25322. }
  25323. parse( json ) {
  25324. const node = this.createNodeFromType( json.type );
  25325. node.uuid = json.uuid;
  25326. const nodes = this.parseNodes( json.nodes );
  25327. const meta = { nodes, textures: this.textures };
  25328. json.meta = meta;
  25329. node.deserialize( json );
  25330. delete json.meta;
  25331. return node;
  25332. }
  25333. setTextures( value ) {
  25334. this.textures = value;
  25335. return this;
  25336. }
  25337. setNodes( value ) {
  25338. this.nodes = value;
  25339. return this;
  25340. }
  25341. createNodeFromType( type ) {
  25342. if ( this.nodes[ type ] === undefined ) {
  25343. console.error( 'THREE.NodeLoader: Node type not found:', type );
  25344. return float();
  25345. }
  25346. return nodeObject( new this.nodes[ type ]() );
  25347. }
  25348. }
  25349. class NodeMaterialLoader extends MaterialLoader {
  25350. constructor( manager ) {
  25351. super( manager );
  25352. this.nodes = {};
  25353. this.nodeMaterials = {};
  25354. }
  25355. parse( json ) {
  25356. const material = super.parse( json );
  25357. const nodes = this.nodes;
  25358. const inputNodes = json.inputNodes;
  25359. for ( const property in inputNodes ) {
  25360. const uuid = inputNodes[ property ];
  25361. material[ property ] = nodes[ uuid ];
  25362. }
  25363. return material;
  25364. }
  25365. setNodes( value ) {
  25366. this.nodes = value;
  25367. return this;
  25368. }
  25369. setNodeMaterials( value ) {
  25370. this.nodeMaterials = value;
  25371. return this;
  25372. }
  25373. createMaterialFromType( type ) {
  25374. const materialClass = this.nodeMaterials[ type ];
  25375. if ( materialClass !== undefined ) {
  25376. return new materialClass();
  25377. }
  25378. return super.createMaterialFromType( type );
  25379. }
  25380. }
  25381. class NodeObjectLoader extends ObjectLoader {
  25382. constructor( manager ) {
  25383. super( manager );
  25384. this.nodes = {};
  25385. this.nodeMaterials = {};
  25386. this._nodesJSON = null;
  25387. }
  25388. setNodes( value ) {
  25389. this.nodes = value;
  25390. return this;
  25391. }
  25392. setNodeMaterials( value ) {
  25393. this.nodeMaterials = value;
  25394. return this;
  25395. }
  25396. parse( json, onLoad ) {
  25397. this._nodesJSON = json.nodes;
  25398. const data = super.parse( json, onLoad );
  25399. this._nodesJSON = null; // dispose
  25400. return data;
  25401. }
  25402. parseNodes( json, textures ) {
  25403. if ( json !== undefined ) {
  25404. const loader = new NodeLoader();
  25405. loader.setNodes( this.nodes );
  25406. loader.setTextures( textures );
  25407. return loader.parseNodes( json );
  25408. }
  25409. return {};
  25410. }
  25411. parseMaterials( json, textures ) {
  25412. const materials = {};
  25413. if ( json !== undefined ) {
  25414. const nodes = this.parseNodes( this._nodesJSON, textures );
  25415. const loader = new NodeMaterialLoader();
  25416. loader.setTextures( textures );
  25417. loader.setNodes( nodes );
  25418. loader.setNodeMaterials( this.nodeMaterials );
  25419. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25420. const data = json[ i ];
  25421. materials[ data.uuid ] = loader.parse( data );
  25422. }
  25423. }
  25424. return materials;
  25425. }
  25426. }
  25427. class ClippingGroup extends Group {
  25428. constructor() {
  25429. super();
  25430. this.isClippingGroup = true;
  25431. this.clippingPlanes = [];
  25432. this.enabled = true;
  25433. this.clipIntersection = false;
  25434. this.clipShadows = false;
  25435. }
  25436. }
  25437. export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnalyticLightNode, ArrayElementNode, AssignNode, AttributeNode, BackSide, BasicEnvironmentNode, BasicShadowMap, BatchNode, BoxGeometry, BufferAttribute, BufferAttributeNode, BufferGeometry, BufferNode, BumpMapNode, BundleGroup, BypassNode, ByteType, CacheNode, CineonToneMapping, ClampToEdgeWrapping, ClippingGroup, CodeNode, Color, ColorManagement, ColorSpaceNode, ComputeNode, ConstNode, ContextNode, ConvertNode, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureNode, CubeUVReflectionMapping, CullFaceBack, CullFaceFront, CullFaceNone, CustomBlending, DataArrayTexture, DataTexture, DecrementStencilOp, DecrementWrapStencilOp, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DirectionalLightNode, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicDrawUsage, EnvironmentNode, EqualCompare, EqualDepth, EqualStencilFunc, EquirectUVNode, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExpressionNode, FileLoader, Float16BufferAttribute, Float32BufferAttribute, FloatType, FogExp2Node, FogNode, FogRangeNode, FramebufferTexture, FrontFacingNode, FrontSide, Frustum, FunctionCallNode, FunctionNode, FunctionOverloadingNode, GLSLNodeParser, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, Group, HalfFloatType, HemisphereLight, HemisphereLightNode, IESSpotLight, IESSpotLightNode, IncrementStencilOp, IncrementWrapStencilOp, IndexNode, IndirectStorageBufferAttribute, InstanceNode, InstancedBufferAttribute, InstancedInterleavedBuffer, InstancedMeshNode, InstancedPointsNodeMaterial, IntType, InterleavedBuffer, InterleavedBufferAttribute, InvertStencilOp, IrradianceNode, JoinNode, KeepStencilOp, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, LightProbe, LightProbeNode, Lighting, LightingContextNode, LightingModel, LightingNode, LightsNode, Line2NodeMaterial, LineBasicMaterial, LineBasicNodeMaterial, LineDashedMaterial, LineDashedNodeMaterial, LinearFilter, LinearMipMapLinearFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, Loader, LoopNode, LuminanceAlphaFormat, LuminanceFormat, MRTNode, MatcapUVNode, Material, MaterialLoader, MaterialNode, MaterialReferenceNode, MathUtils, Matrix3, Matrix4, MaxEquation, MaxMipLevelNode, Mesh, MeshBasicMaterial, MeshBasicNodeMaterial, MeshLambertMaterial, MeshLambertNodeMaterial, MeshMatcapMaterial, MeshMatcapNodeMaterial, MeshNormalMaterial, MeshNormalNodeMaterial, MeshPhongMaterial, MeshPhongNodeMaterial, MeshPhysicalMaterial, MeshPhysicalNodeMaterial, MeshSSSNodeMaterial, MeshStandardMaterial, MeshStandardNodeMaterial, MeshToonMaterial, MeshToonNodeMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, ModelNode, ModelViewProjectionNode, MorphNode, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, Node, NodeAccess, NodeAttribute, NodeBuilder, NodeCache, NodeCode, NodeFrame, NodeFunctionInput, NodeLoader, NodeMaterial, NodeMaterialLoader, NodeMaterialObserver, NodeObjectLoader, NodeShaderStage, NodeType, NodeUniform, NodeUpdateType, NodeUtils, NodeVar, NodeVarying, NormalBlending, NormalMapNode, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, Object3D, Object3DNode, ObjectLoader, ObjectSpaceNormalMap, OneFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, OutputStructNode, PCFShadowMap, PMREMGenerator, PMREMNode, ParameterNode, PassNode, PerspectiveCamera, PhongLightingModel, PhysicalLightingModel, Plane, PointLight, PointLightNode, PointUVNode, PointsMaterial, PointsNodeMaterial, PostProcessing, PostProcessingUtils, PosterizeNode, PropertyNode, QuadMesh, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBFormat, RGBIntegerFormat, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RTTNode, RangeNode, RectAreaLight, RectAreaLightNode, RedFormat, RedIntegerFormat, ReferenceNode, ReflectorNode, ReinhardToneMapping, RemapNode, RenderOutputNode, RenderTarget, RendererReferenceNode, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RotateNode, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, Scene, SceneNode, ScreenNode, ScriptableNode, ScriptableValueNode, SetNode, ShadowMaterial, ShadowNode, ShadowNodeMaterial, ShortType, SkinningNode, SphereGeometry, SplitNode, SpotLight, SpotLightNode, SpriteMaterial, SpriteNodeMaterial, SpriteSheetUVNode, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StackNode, StaticDrawUsage, StorageArrayElementNode, StorageBufferAttribute, StorageBufferNode, StorageInstancedBufferAttribute, StorageTexture, StorageTextureNode, SubtractEquation, SubtractiveBlending, TSL, TangentSpaceNormalMap, TempNode, Texture, Texture3DNode, TextureNode, TextureSizeNode, ToneMappingNode, ToonOutlinePassNode, TriplanarTexturesNode, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, UniformArrayNode, UniformGroupNode, UniformNode, UnsignedByteType, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, UserDataNode, VSMShadowMap, VarNode, VaryingNode, Vector2, Vector3, Vector4, VertexColorNode, ViewportDepthNode, ViewportDepthTextureNode, ViewportSharedTextureNode, ViewportTextureNode, VolumeNodeMaterial, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGPUCoordinateSystem, WebGPURenderer, ZeroFactor, ZeroStencilOp, createCanvasElement, defaultBuildStages, defaultShaderStages, shaderStages, vectorComponents };
粤ICP备19079148号