three.module.js 617 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115
  1. /**
  2. * @license
  3. * Copyright 2010-2025 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. import { Matrix3, Vector2, Color, mergeUniforms, Vector3, CubeUVReflectionMapping, Mesh, BoxGeometry, ShaderMaterial, BackSide, cloneUniforms, Euler, Matrix4, ColorManagement, SRGBTransfer, PlaneGeometry, FrontSide, getUnlitUniformColorSpace, IntType, warn, HalfFloatType, UnsignedByteType, FloatType, RGBAFormat, Plane, EquirectangularReflectionMapping, EquirectangularRefractionMapping, WebGLCubeRenderTarget, CubeReflectionMapping, CubeRefractionMapping, BufferGeometry, OrthographicCamera, PerspectiveCamera, NoToneMapping, MeshBasicMaterial, error, NoBlending, WebGLRenderTarget, BufferAttribute, LinearSRGBColorSpace, LinearFilter, warnOnce, Uint32BufferAttribute, Uint16BufferAttribute, arrayNeedsUint32, Vector4, DataArrayTexture, Float32BufferAttribute, RawShaderMaterial, CustomToneMapping, NeutralToneMapping, AgXToneMapping, ACESFilmicToneMapping, CineonToneMapping, ReinhardToneMapping, LinearToneMapping, CubeTexture, Data3DTexture, GreaterEqualCompare, LessEqualCompare, DepthTexture, Texture, GLSL3, VSMShadowMap, PCFShadowMap, AddOperation, MixOperation, MultiplyOperation, LinearTransfer, UniformsUtils, DoubleSide, NormalBlending, TangentSpaceNormalMap, ObjectSpaceNormalMap, Layers, RGFormat, Frustum, MeshDepthMaterial, MeshDistanceMaterial, PCFSoftShadowMap, DepthFormat, NearestFilter, CubeDepthTexture, UnsignedIntType, LessEqualDepth, ReverseSubtractEquation, SubtractEquation, AddEquation, OneMinusConstantAlphaFactor, ConstantAlphaFactor, OneMinusConstantColorFactor, ConstantColorFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, DstAlphaFactor, DstColorFactor, SrcAlphaSaturateFactor, SrcAlphaFactor, SrcColorFactor, OneFactor, ZeroFactor, NotEqualDepth, GreaterDepth, GreaterEqualDepth, EqualDepth, LessDepth, AlwaysDepth, NeverDepth, CullFaceNone, CullFaceBack, CullFaceFront, CustomBlending, MultiplyBlending, SubtractiveBlending, AdditiveBlending, MinEquation, MaxEquation, MirroredRepeatWrapping, ClampToEdgeWrapping, RepeatWrapping, LinearMipmapLinearFilter, LinearMipmapNearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NotEqualCompare, GreaterCompare, EqualCompare, LessCompare, AlwaysCompare, NeverCompare, NoColorSpace, DepthStencilFormat, getByteLength, UnsignedInt248Type, UnsignedShortType, createElementNS, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedInt5999Type, UnsignedInt101111Type, ByteType, ShortType, AlphaFormat, RGBFormat, RedFormat, RedIntegerFormat, RGIntegerFormat, RGBAIntegerFormat, 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, R11_EAC_Format, SIGNED_R11_EAC_Format, RG11_EAC_Format, SIGNED_RG11_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, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RED_RGTC1_Format, SIGNED_RED_RGTC1_Format, RED_GREEN_RGTC2_Format, SIGNED_RED_GREEN_RGTC2_Format, ExternalTexture, EventDispatcher, ArrayCamera, WebXRController, RAD2DEG, DataTexture, createCanvasElement, SRGBColorSpace, REVISION, log, WebGLCoordinateSystem, probeAsync } from './three.core.js';
  7. export { AdditiveAnimationBlendMode, AlwaysStencilFunc, AmbientLight, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrowHelper, AttachedBindMode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BasicDepthPacking, BasicShadowMap, BatchedMesh, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxHelper, BufferGeometryLoader, Cache, Camera, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CircleGeometry, Clock, ColorKeyframeTrack, Compatibility, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ConeGeometry, Controls, CubeCamera, CubeTextureLoader, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceFrontBack, Curve, CurvePath, CylinderGeometry, Cylindrical, DataTextureLoader, DataUtils, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DetachedBindMode, DirectionalLight, DirectionalLightHelper, DiscreteInterpolant, DodecahedronGeometry, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, EqualStencilFunc, ExtrudeGeometry, FileLoader, Float16BufferAttribute, Fog, FogExp2, FramebufferTexture, FrustumArray, GLBufferAttribute, GLSL1, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HemisphereLight, HemisphereLightHelper, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, IncrementStencilOp, IncrementWrapStencilOp, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InterpolationSamplingMode, InterpolationSamplingType, InvertStencilOp, KeepStencilOp, KeyframeTrack, LOD, LatheGeometry, LessEqualStencilFunc, LessStencilFunc, Light, LightProbe, Line, Line3, LineBasicMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineLoop, LineSegments, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, Loader, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, MOUSE, Material, MaterialLoader, MathUtils, Matrix2, MeshLambertMaterial, MeshMatcapMaterial, MeshNormalMaterial, MeshPhongMaterial, MeshPhysicalMaterial, MeshStandardMaterial, MeshToonMaterial, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NeverStencilFunc, NoNormalPacking, NormalAnimationBlendMode, NormalGAPacking, NormalRGPacking, NotEqualStencilFunc, NumberKeyframeTrack, Object3D, ObjectLoader, OctahedronGeometry, Path, PlaneHelper, PointLight, PointLightHelper, Points, PointsMaterial, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RGBADepthPacking, RGBDepthPacking, RGBIntegerFormat, RGDepthPacking, Ray, Raycaster, RectAreaLight, RenderTarget, RenderTarget3D, ReplaceStencilOp, RingGeometry, Scene, ShadowMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, Skeleton, SkeletonHelper, SkinnedMesh, Source, Sphere, SphereGeometry, Spherical, SphericalHarmonics3, SplineCurve, SpotLight, SpotLightHelper, Sprite, SpriteMaterial, StaticCopyUsage, StaticDrawUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, TOUCH, TetrahedronGeometry, TextureLoader, TextureUtils, Timer, TimestampQuery, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, UVMapping, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, VectorKeyframeTrack, VideoFrameTexture, VideoTexture, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGPUCoordinateSystem, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroSlopeEnding, ZeroStencilOp, getConsoleFunction, setConsoleFunction } from './three.core.js';
  8. function WebGLAnimation() {
  9. let context = null;
  10. let isAnimating = false;
  11. let animationLoop = null;
  12. let requestId = null;
  13. function onAnimationFrame( time, frame ) {
  14. animationLoop( time, frame );
  15. requestId = context.requestAnimationFrame( onAnimationFrame );
  16. }
  17. return {
  18. start: function () {
  19. if ( isAnimating === true ) return;
  20. if ( animationLoop === null ) return;
  21. requestId = context.requestAnimationFrame( onAnimationFrame );
  22. isAnimating = true;
  23. },
  24. stop: function () {
  25. context.cancelAnimationFrame( requestId );
  26. isAnimating = false;
  27. },
  28. setAnimationLoop: function ( callback ) {
  29. animationLoop = callback;
  30. },
  31. setContext: function ( value ) {
  32. context = value;
  33. }
  34. };
  35. }
  36. function WebGLAttributes( gl ) {
  37. const buffers = new WeakMap();
  38. function createBuffer( attribute, bufferType ) {
  39. const array = attribute.array;
  40. const usage = attribute.usage;
  41. const size = array.byteLength;
  42. const buffer = gl.createBuffer();
  43. gl.bindBuffer( bufferType, buffer );
  44. gl.bufferData( bufferType, array, usage );
  45. attribute.onUploadCallback();
  46. let type;
  47. if ( array instanceof Float32Array ) {
  48. type = gl.FLOAT;
  49. } else if ( typeof Float16Array !== 'undefined' && array instanceof Float16Array ) {
  50. type = gl.HALF_FLOAT;
  51. } else if ( array instanceof Uint16Array ) {
  52. if ( attribute.isFloat16BufferAttribute ) {
  53. type = gl.HALF_FLOAT;
  54. } else {
  55. type = gl.UNSIGNED_SHORT;
  56. }
  57. } else if ( array instanceof Int16Array ) {
  58. type = gl.SHORT;
  59. } else if ( array instanceof Uint32Array ) {
  60. type = gl.UNSIGNED_INT;
  61. } else if ( array instanceof Int32Array ) {
  62. type = gl.INT;
  63. } else if ( array instanceof Int8Array ) {
  64. type = gl.BYTE;
  65. } else if ( array instanceof Uint8Array ) {
  66. type = gl.UNSIGNED_BYTE;
  67. } else if ( array instanceof Uint8ClampedArray ) {
  68. type = gl.UNSIGNED_BYTE;
  69. } else {
  70. throw new Error( 'THREE.WebGLAttributes: Unsupported buffer data format: ' + array );
  71. }
  72. return {
  73. buffer: buffer,
  74. type: type,
  75. bytesPerElement: array.BYTES_PER_ELEMENT,
  76. version: attribute.version,
  77. size: size
  78. };
  79. }
  80. function updateBuffer( buffer, attribute, bufferType ) {
  81. const array = attribute.array;
  82. const updateRanges = attribute.updateRanges;
  83. gl.bindBuffer( bufferType, buffer );
  84. if ( updateRanges.length === 0 ) {
  85. // Not using update ranges
  86. gl.bufferSubData( bufferType, 0, array );
  87. } else {
  88. // Before applying update ranges, we merge any adjacent / overlapping
  89. // ranges to reduce load on `gl.bufferSubData`. Empirically, this has led
  90. // to performance improvements for applications which make heavy use of
  91. // update ranges. Likely due to GPU command overhead.
  92. //
  93. // Note that to reduce garbage collection between frames, we merge the
  94. // update ranges in-place. This is safe because this method will clear the
  95. // update ranges once updated.
  96. updateRanges.sort( ( a, b ) => a.start - b.start );
  97. // To merge the update ranges in-place, we work from left to right in the
  98. // existing updateRanges array, merging ranges. This may result in a final
  99. // array which is smaller than the original. This index tracks the last
  100. // index representing a merged range, any data after this index can be
  101. // trimmed once the merge algorithm is completed.
  102. let mergeIndex = 0;
  103. for ( let i = 1; i < updateRanges.length; i ++ ) {
  104. const previousRange = updateRanges[ mergeIndex ];
  105. const range = updateRanges[ i ];
  106. // We add one here to merge adjacent ranges. This is safe because ranges
  107. // operate over positive integers.
  108. if ( range.start <= previousRange.start + previousRange.count + 1 ) {
  109. previousRange.count = Math.max(
  110. previousRange.count,
  111. range.start + range.count - previousRange.start
  112. );
  113. } else {
  114. ++ mergeIndex;
  115. updateRanges[ mergeIndex ] = range;
  116. }
  117. }
  118. // Trim the array to only contain the merged ranges.
  119. updateRanges.length = mergeIndex + 1;
  120. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  121. const range = updateRanges[ i ];
  122. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  123. array, range.start, range.count );
  124. }
  125. attribute.clearUpdateRanges();
  126. }
  127. attribute.onUploadCallback();
  128. }
  129. //
  130. function get( attribute ) {
  131. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  132. return buffers.get( attribute );
  133. }
  134. function remove( attribute ) {
  135. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  136. const data = buffers.get( attribute );
  137. if ( data ) {
  138. gl.deleteBuffer( data.buffer );
  139. buffers.delete( attribute );
  140. }
  141. }
  142. function update( attribute, bufferType ) {
  143. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  144. if ( attribute.isGLBufferAttribute ) {
  145. const cached = buffers.get( attribute );
  146. if ( ! cached || cached.version < attribute.version ) {
  147. buffers.set( attribute, {
  148. buffer: attribute.buffer,
  149. type: attribute.type,
  150. bytesPerElement: attribute.elementSize,
  151. version: attribute.version
  152. } );
  153. }
  154. return;
  155. }
  156. const data = buffers.get( attribute );
  157. if ( data === undefined ) {
  158. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  159. } else if ( data.version < attribute.version ) {
  160. if ( data.size !== attribute.array.byteLength ) {
  161. throw new Error( 'THREE.WebGLAttributes: The size of the buffer attribute\'s array buffer does not match the original size. Resizing buffer attributes is not supported.' );
  162. }
  163. updateBuffer( data.buffer, attribute, bufferType );
  164. data.version = attribute.version;
  165. }
  166. }
  167. return {
  168. get: get,
  169. remove: remove,
  170. update: update
  171. };
  172. }
  173. var alphahash_fragment = "#ifdef USE_ALPHAHASH\n\tif ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;\n#endif";
  174. var alphahash_pars_fragment = "#ifdef USE_ALPHAHASH\n\tconst float ALPHA_HASH_SCALE = 0.05;\n\tfloat hash2D( vec2 value ) {\n\t\treturn fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) );\n\t}\n\tfloat hash3D( vec3 value ) {\n\t\treturn hash2D( vec2( hash2D( value.xy ), value.z ) );\n\t}\n\tfloat getAlphaHashThreshold( vec3 position ) {\n\t\tfloat maxDeriv = max(\n\t\t\tlength( dFdx( position.xyz ) ),\n\t\t\tlength( dFdy( position.xyz ) )\n\t\t);\n\t\tfloat pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv );\n\t\tvec2 pixScales = vec2(\n\t\t\texp2( floor( log2( pixScale ) ) ),\n\t\t\texp2( ceil( log2( pixScale ) ) )\n\t\t);\n\t\tvec2 alpha = vec2(\n\t\t\thash3D( floor( pixScales.x * position.xyz ) ),\n\t\t\thash3D( floor( pixScales.y * position.xyz ) )\n\t\t);\n\t\tfloat lerpFactor = fract( log2( pixScale ) );\n\t\tfloat x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y;\n\t\tfloat a = min( lerpFactor, 1.0 - lerpFactor );\n\t\tvec3 cases = vec3(\n\t\t\tx * x / ( 2.0 * a * ( 1.0 - a ) ),\n\t\t\t( x - 0.5 * a ) / ( 1.0 - a ),\n\t\t\t1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) )\n\t\t);\n\t\tfloat threshold = ( x < ( 1.0 - a ) )\n\t\t\t? ( ( x < a ) ? cases.x : cases.y )\n\t\t\t: cases.z;\n\t\treturn clamp( threshold , 1.0e-6, 1.0 );\n\t}\n#endif";
  175. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;\n#endif";
  176. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  177. var alphatest_fragment = "#ifdef USE_ALPHATEST\n\t#ifdef ALPHA_TO_COVERAGE\n\tdiffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a );\n\tif ( diffuseColor.a == 0.0 ) discard;\n\t#else\n\tif ( diffuseColor.a < alphaTest ) discard;\n\t#endif\n#endif";
  178. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  179. var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_CLEARCOAT ) \n\t\tclearcoatSpecularIndirect *= ambientOcclusion;\n\t#endif\n\t#if defined( USE_SHEEN ) \n\t\tsheenSpecularIndirect *= ambientOcclusion;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometryNormal, geometryViewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n\t#endif\n#endif";
  180. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  181. var batching_pars_vertex = "#ifdef USE_BATCHING\n\t#if ! defined( GL_ANGLE_multi_draw )\n\t#define gl_DrawID _gl_DrawID\n\tuniform int _gl_DrawID;\n\t#endif\n\tuniform highp sampler2D batchingTexture;\n\tuniform highp usampler2D batchingIdTexture;\n\tmat4 getBatchingMatrix( const in float i ) {\n\t\tint size = textureSize( batchingTexture, 0 ).x;\n\t\tint j = int( i ) * 4;\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\tvec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 );\n\t\tvec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 );\n\t\tvec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 );\n\t\tvec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 );\n\t\treturn mat4( v1, v2, v3, v4 );\n\t}\n\tfloat getIndirectIndex( const in int i ) {\n\t\tint size = textureSize( batchingIdTexture, 0 ).x;\n\t\tint x = i % size;\n\t\tint y = i / size;\n\t\treturn float( texelFetch( batchingIdTexture, ivec2( x, y ), 0 ).r );\n\t}\n#endif\n#ifdef USE_BATCHING_COLOR\n\tuniform sampler2D batchingColorTexture;\n\tvec3 getBatchingColor( const in float i ) {\n\t\tint size = textureSize( batchingColorTexture, 0 ).x;\n\t\tint j = int( i );\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\treturn texelFetch( batchingColorTexture, ivec2( x, y ), 0 ).rgb;\n\t}\n#endif";
  182. var batching_vertex = "#ifdef USE_BATCHING\n\tmat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );\n#endif";
  183. var begin_vertex = "vec3 transformed = vec3( position );\n#ifdef USE_ALPHAHASH\n\tvPosition = vec3( position );\n#endif";
  184. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  185. var bsdfs = "float G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, 1.0, dotVH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n} // validated";
  186. var iridescence_fragment = "#ifdef USE_IRIDESCENCE\n\tconst mat3 XYZ_TO_REC709 = mat3(\n\t\t 3.2404542, -0.9692660, 0.0556434,\n\t\t-1.5371385, 1.8760108, -0.2040259,\n\t\t-0.4985314, 0.0415560, 1.0572252\n\t);\n\tvec3 Fresnel0ToIor( vec3 fresnel0 ) {\n\t\tvec3 sqrtF0 = sqrt( fresnel0 );\n\t\treturn ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );\n\t}\n\tvec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );\n\t}\n\tfloat IorToFresnel0( float transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));\n\t}\n\tvec3 evalSensitivity( float OPD, vec3 shift ) {\n\t\tfloat phase = 2.0 * PI * OPD * 1.0e-9;\n\t\tvec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );\n\t\tvec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );\n\t\tvec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );\n\t\tvec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );\n\t\txyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );\n\t\txyz /= 1.0685e-7;\n\t\tvec3 rgb = XYZ_TO_REC709 * xyz;\n\t\treturn rgb;\n\t}\n\tvec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {\n\t\tvec3 I;\n\t\tfloat iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );\n\t\tfloat sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );\n\t\tfloat cosTheta2Sq = 1.0 - sinTheta2Sq;\n\t\tif ( cosTheta2Sq < 0.0 ) {\n\t\t\treturn vec3( 1.0 );\n\t\t}\n\t\tfloat cosTheta2 = sqrt( cosTheta2Sq );\n\t\tfloat R0 = IorToFresnel0( iridescenceIOR, outsideIOR );\n\t\tfloat R12 = F_Schlick( R0, 1.0, cosTheta1 );\n\t\tfloat T121 = 1.0 - R12;\n\t\tfloat phi12 = 0.0;\n\t\tif ( iridescenceIOR < outsideIOR ) phi12 = PI;\n\t\tfloat phi21 = PI - phi12;\n\t\tvec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) );\t\tvec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );\n\t\tvec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );\n\t\tvec3 phi23 = vec3( 0.0 );\n\t\tif ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;\n\t\tif ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;\n\t\tif ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;\n\t\tfloat OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;\n\t\tvec3 phi = vec3( phi21 ) + phi23;\n\t\tvec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );\n\t\tvec3 r123 = sqrt( R123 );\n\t\tvec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );\n\t\tvec3 C0 = R12 + Rs;\n\t\tI = C0;\n\t\tvec3 Cm = Rs - T121;\n\t\tfor ( int m = 1; m <= 2; ++ m ) {\n\t\t\tCm *= r123;\n\t\t\tvec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );\n\t\t\tI += Cm * Sm;\n\t\t}\n\t\treturn max( I, vec3( 0.0 ) );\n\t}\n#endif";
  187. var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vBumpMapUv );\n\t\tvec2 dSTdy = dFdy( vBumpMapUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {\n\t\tvec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) );\n\t\tvec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 ) * faceDirection;\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif";
  188. var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#ifdef ALPHA_TO_COVERAGE\n\t\tfloat distanceToPlane, distanceGradient;\n\t\tfloat clipOpacity = 1.0;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\tclipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\tif ( clipOpacity == 0.0 ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tfloat unionClipOpacity = 1.0;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\t\tunionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tclipOpacity *= 1.0 - unionClipOpacity;\n\t\t#endif\n\t\tdiffuseColor.a *= clipOpacity;\n\t\tif ( diffuseColor.a == 0.0 ) discard;\n\t#else\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tbool clipped = true;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tif ( clipped ) discard;\n\t\t#endif\n\t#endif\n#endif";
  189. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  190. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  191. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  192. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  193. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  194. var color_pars_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n\tvarying vec3 vColor;\n#endif";
  195. var color_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif\n#ifdef USE_BATCHING_COLOR\n\tvec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) );\n\tvColor.xyz *= batchingColor.xyz;\n#endif";
  196. var common = "#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nvec3 pow2( const in vec3 x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\n#ifdef USE_ALPHAHASH\n\tvarying vec3 vPosition;\n#endif\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}\nvec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat F_Schlick( const in float f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n} // validated";
  197. var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\thighp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tuv.x += filterInt * 3.0 * cubeUV_minTileSize;\n\t\tuv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );\n\t\tuv.x *= CUBEUV_TEXEL_WIDTH;\n\t\tuv.y *= CUBEUV_TEXEL_HEIGHT;\n\t\t#ifdef texture2DGradEXT\n\t\t\treturn texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;\n\t\t#else\n\t\t\treturn texture2D( envMap, uv ).rgb;\n\t\t#endif\n\t}\n\t#define cubeUV_r0 1.0\n\t#define cubeUV_m0 - 2.0\n\t#define cubeUV_r1 0.8\n\t#define cubeUV_m1 - 1.0\n\t#define cubeUV_r4 0.4\n\t#define cubeUV_m4 2.0\n\t#define cubeUV_r5 0.305\n\t#define cubeUV_m5 3.0\n\t#define cubeUV_r6 0.21\n\t#define cubeUV_m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= cubeUV_r1 ) {\n\t\t\tmip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;\n\t\t} else if ( roughness >= cubeUV_r4 ) {\n\t\t\tmip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;\n\t\t} else if ( roughness >= cubeUV_r5 ) {\n\t\t\tmip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;\n\t\t} else if ( roughness >= cubeUV_r6 ) {\n\t\t\tmip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif";
  198. var defaultnormal_vertex = "vec3 transformedNormal = objectNormal;\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = objectTangent;\n#endif\n#ifdef USE_BATCHING\n\tmat3 bm = mat3( batchingMatrix );\n\ttransformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) );\n\ttransformedNormal = bm * transformedNormal;\n\t#ifdef USE_TANGENT\n\t\ttransformedTangent = bm * transformedTangent;\n\t#endif\n#endif\n#ifdef USE_INSTANCING\n\tmat3 im = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) );\n\ttransformedNormal = im * transformedNormal;\n\t#ifdef USE_TANGENT\n\t\ttransformedTangent = im * transformedTangent;\n\t#endif\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\ttransformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif";
  199. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  200. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif";
  201. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );\n\t#ifdef DECODE_VIDEO_TEXTURE_EMISSIVE\n\t\temissiveColor = sRGBTransferEOTF( emissiveColor );\n\t#endif\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  202. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  203. var colorspace_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  204. var colorspace_pars_fragment = "vec4 LinearTransferOETF( in vec4 value ) {\n\treturn value;\n}\nvec4 sRGBTransferEOTF( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );\n}\nvec4 sRGBTransferOETF( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}";
  205. var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif";
  206. var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\tuniform mat3 envMapRotation;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n#endif";
  207. var envmap_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif";
  208. var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif";
  209. var envmap_vertex = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif";
  210. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  211. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  212. var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif";
  213. var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float vFogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif";
  214. var gradientmap_pars_fragment = "#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn vec3( texture2D( gradientMap, coord ).r );\n\t#else\n\t\tvec2 fw = fwidth( coord ) * 0.5;\n\t\treturn mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );\n\t#endif\n}";
  215. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  216. var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;";
  217. var lights_lambert_pars_fragment = "varying vec3 vViewPosition;\nstruct LambertMaterial {\n\tvec3 diffuseColor;\n\tfloat specularStrength;\n};\nvoid RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Lambert\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Lambert";
  218. var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\n#if defined( USE_LIGHT_PROBES )\n\tuniform vec3 lightProbe[ 9 ];\n#endif\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\n\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif ( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n\t\tfloat dotNL = dot( normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif";
  219. var envmap_physical_pars_fragment = "#ifdef USE_ENVMAP\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 reflectVec = reflect( - viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, pow4( roughness ) ) );\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\t#ifdef USE_ANISOTROPY\n\t\tvec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {\n\t\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\t\tvec3 bentNormal = cross( bitangent, viewDir );\n\t\t\t\tbentNormal = normalize( cross( bentNormal, bitangent ) );\n\t\t\t\tbentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );\n\t\t\t\treturn getIBLRadiance( viewDir, bentNormal, roughness );\n\t\t\t#else\n\t\t\t\treturn vec3( 0.0 );\n\t\t\t#endif\n\t\t}\n\t#endif\n#endif";
  220. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  221. var lights_toon_pars_fragment = "varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon";
  222. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  223. var lights_phong_pars_fragment = "varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong";
  224. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.diffuseContribution = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.metalness = metalnessFactor;\nvec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\tmaterial.ior = ior;\n\t#ifdef USE_SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULAR_COLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;\n\t\t#endif\n\t\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor;\n\tmaterial.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = vec3( 0.04 );\n\tmaterial.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_DISPERSION\n\tmaterial.dispersion = dispersion;\n#endif\n#ifdef USE_IRIDESCENCE\n\tmaterial.iridescence = iridescence;\n\tmaterial.iridescenceIOR = iridescenceIOR;\n\t#ifdef USE_IRIDESCENCEMAP\n\t\tmaterial.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;\n\t#endif\n\t#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\t\tmaterial.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;\n\t#else\n\t\tmaterial.iridescenceThickness = iridescenceThicknessMaximum;\n\t#endif\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.0001, 1.0 );\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\t#ifdef USE_ANISOTROPYMAP\n\t\tmat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );\n\t\tvec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;\n\t\tvec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;\n\t#else\n\t\tvec2 anisotropyV = anisotropyVector;\n\t#endif\n\tmaterial.anisotropy = length( anisotropyV );\n\tif( material.anisotropy == 0.0 ) {\n\t\tanisotropyV = vec2( 1.0, 0.0 );\n\t} else {\n\t\tanisotropyV /= material.anisotropy;\n\t\tmaterial.anisotropy = saturate( material.anisotropy );\n\t}\n\tmaterial.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );\n\tmaterial.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;\n\tmaterial.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;\n#endif";
  225. var lights_physical_pars_fragment = "uniform sampler2D dfgLUT;\nstruct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tvec3 diffuseContribution;\n\tvec3 specularColor;\n\tvec3 specularColorBlended;\n\tfloat roughness;\n\tfloat metalness;\n\tfloat specularF90;\n\tfloat dispersion;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\tfloat iridescence;\n\t\tfloat iridescenceIOR;\n\t\tfloat iridescenceThickness;\n\t\tvec3 iridescenceFresnel;\n\t\tvec3 iridescenceF0;\n\t\tvec3 iridescenceFresnelDielectric;\n\t\tvec3 iridescenceFresnelMetallic;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n\t#ifdef IOR\n\t\tfloat ior;\n\t#endif\n\t#ifdef USE_TRANSMISSION\n\t\tfloat transmission;\n\t\tfloat transmissionAlpha;\n\t\tfloat thickness;\n\t\tfloat attenuationDistance;\n\t\tvec3 attenuationColor;\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat anisotropy;\n\t\tfloat alphaT;\n\t\tvec3 anisotropyT;\n\t\tvec3 anisotropyB;\n\t#endif\n};\nvec3 clearcoatSpecularDirect = vec3( 0.0 );\nvec3 clearcoatSpecularIndirect = vec3( 0.0 );\nvec3 sheenSpecularDirect = vec3( 0.0 );\nvec3 sheenSpecularIndirect = vec3(0.0 );\nvec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {\n float x = clamp( 1.0 - dotVH, 0.0, 1.0 );\n float x2 = x * x;\n float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );\n return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\n#ifdef USE_ANISOTROPY\n\tfloat V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) {\n\t\tfloat gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );\n\t\tfloat gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );\n\t\tfloat v = 0.5 / ( gv + gl );\n\t\treturn v;\n\t}\n\tfloat D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {\n\t\tfloat a2 = alphaT * alphaB;\n\t\thighp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );\n\t\thighp float v2 = dot( v, v );\n\t\tfloat w2 = a2 / v2;\n\t\treturn RECIPROCAL_PI * a2 * pow2 ( w2 );\n\t}\n#endif\n#ifdef USE_CLEARCOAT\n\tvec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {\n\t\tvec3 f0 = material.clearcoatF0;\n\t\tfloat f90 = material.clearcoatF90;\n\t\tfloat roughness = material.clearcoatRoughness;\n\t\tfloat alpha = pow2( roughness );\n\t\tvec3 halfDir = normalize( lightDir + viewDir );\n\t\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\t\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\t\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\t\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\t\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t\treturn F * ( V * D );\n\t}\n#endif\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {\n\tvec3 f0 = material.specularColorBlended;\n\tfloat f90 = material.specularF90;\n\tfloat roughness = material.roughness;\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t#ifdef USE_IRIDESCENCE\n\t\tF = mix( F, material.iridescenceFresnel, material.iridescence );\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat dotTL = dot( material.anisotropyT, lightDir );\n\t\tfloat dotTV = dot( material.anisotropyT, viewDir );\n\t\tfloat dotTH = dot( material.anisotropyT, halfDir );\n\t\tfloat dotBL = dot( material.anisotropyB, lightDir );\n\t\tfloat dotBV = dot( material.anisotropyB, viewDir );\n\t\tfloat dotBH = dot( material.anisotropyB, halfDir );\n\t\tfloat V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );\n\t\tfloat D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );\n\t#else\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t#endif\n\treturn F * ( V * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transpose( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenColor * ( D * V );\n}\n#endif\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat rInv = 1.0 / ( roughness + 0.1 );\n\tfloat a = -1.9362 + 1.0678 * roughness + 0.4573 * r2 - 0.8469 * rInv;\n\tfloat b = -0.6014 + 0.5538 * roughness - 0.4670 * r2 - 0.1255 * rInv;\n\tfloat DG = exp( a * dotNV + b );\n\treturn saturate( DG );\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg;\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\n#ifdef USE_IRIDESCENCE\nvoid computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#else\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#endif\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg;\n\t#ifdef USE_IRIDESCENCE\n\t\tvec3 Fr = mix( specularColor, iridescenceF0, iridescence );\n\t#else\n\t\tvec3 Fr = specularColor;\n\t#endif\n\tvec3 FssEss = Fr * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\nvec3 BRDF_GGX_Multiscatter( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {\n\tvec3 singleScatter = BRDF_GGX( lightDir, viewDir, normal, material );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 dfgV = texture2D( dfgLUT, vec2( material.roughness, dotNV ) ).rg;\n\tvec2 dfgL = texture2D( dfgLUT, vec2( material.roughness, dotNL ) ).rg;\n\tvec3 FssEss_V = material.specularColorBlended * dfgV.x + material.specularF90 * dfgV.y;\n\tvec3 FssEss_L = material.specularColorBlended * dfgL.x + material.specularF90 * dfgL.y;\n\tfloat Ess_V = dfgV.x + dfgV.y;\n\tfloat Ess_L = dfgL.x + dfgL.y;\n\tfloat Ems_V = 1.0 - Ess_V;\n\tfloat Ems_L = 1.0 - Ess_L;\n\tvec3 Favg = material.specularColorBlended + ( 1.0 - material.specularColorBlended ) * 0.047619;\n\tvec3 Fms = FssEss_V * FssEss_L * Favg / ( 1.0 - Ems_V * Ems_L * Favg + EPSILON );\n\tfloat compensationFactor = Ems_V * Ems_L;\n\tvec3 multiScatter = Fms * compensationFactor;\n\treturn singleScatter + multiScatter;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometryNormal;\n\t\tvec3 viewDir = geometryViewDir;\n\t\tvec3 position = geometryPosition;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColorBlended * t2.x + ( vec3( 1.0 ) - material.specularColorBlended ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseContribution * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );\n\t#endif\n\t#ifdef USE_SHEEN\n \n \t\tsheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );\n \n \t\tfloat sheenAlbedoV = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n \t\tfloat sheenAlbedoL = IBLSheenBRDF( geometryNormal, directLight.direction, material.sheenRoughness );\n \n \t\tfloat sheenEnergyComp = 1.0 - max3( material.sheenColor ) * max( sheenAlbedoV, sheenAlbedoL );\n \n \t\tirradiance *= sheenEnergyComp;\n \n \t#endif\n\treflectedLight.directSpecular += irradiance * BRDF_GGX_Multiscatter( directLight.direction, geometryViewDir, geometryNormal, material );\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseContribution );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 diffuse = irradiance * BRDF_Lambert( material.diffuseContribution );\n\t#ifdef USE_SHEEN\n\t\tfloat sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n\t\tfloat sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo;\n\t\tdiffuse *= sheenEnergyComp;\n\t#endif\n\treflectedLight.indirectDiffuse += diffuse;\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ) * RECIPROCAL_PI;\n \t#endif\n\tvec3 singleScatteringDielectric = vec3( 0.0 );\n\tvec3 multiScatteringDielectric = vec3( 0.0 );\n\tvec3 singleScatteringMetallic = vec3( 0.0 );\n\tvec3 multiScatteringMetallic = vec3( 0.0 );\n\t#ifdef USE_IRIDESCENCE\n\t\tcomputeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnelDielectric, material.roughness, singleScatteringDielectric, multiScatteringDielectric );\n\t\tcomputeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.iridescence, material.iridescenceFresnelMetallic, material.roughness, singleScatteringMetallic, multiScatteringMetallic );\n\t#else\n\t\tcomputeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScatteringDielectric, multiScatteringDielectric );\n\t\tcomputeMultiscattering( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.roughness, singleScatteringMetallic, multiScatteringMetallic );\n\t#endif\n\tvec3 singleScattering = mix( singleScatteringDielectric, singleScatteringMetallic, material.metalness );\n\tvec3 multiScattering = mix( multiScatteringDielectric, multiScatteringMetallic, material.metalness );\n\tvec3 totalScatteringDielectric = singleScatteringDielectric + multiScatteringDielectric;\n\tvec3 diffuse = material.diffuseContribution * ( 1.0 - totalScatteringDielectric );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tvec3 indirectSpecular = radiance * singleScattering;\n\tindirectSpecular += multiScattering * cosineWeightedIrradiance;\n\tvec3 indirectDiffuse = diffuse * cosineWeightedIrradiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n\t\tfloat sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo;\n\t\tindirectSpecular *= sheenEnergyComp;\n\t\tindirectDiffuse *= sheenEnergyComp;\n\t#endif\n\treflectedLight.indirectSpecular += indirectSpecular;\n\treflectedLight.indirectDiffuse += indirectDiffuse;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}";
  226. var lights_fragment_begin = "\nvec3 geometryPosition = - vViewPosition;\nvec3 geometryNormal = normal;\nvec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\nvec3 geometryClearcoatNormal = vec3( 0.0 );\n#ifdef USE_CLEARCOAT\n\tgeometryClearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n\tfloat dotNVi = saturate( dot( normal, geometryViewDir ) );\n\tif ( material.iridescenceThickness == 0.0 ) {\n\t\tmaterial.iridescence = 0.0;\n\t} else {\n\t\tmaterial.iridescence = saturate( material.iridescence );\n\t}\n\tif ( material.iridescence > 0.0 ) {\n\t\tmaterial.iridescenceFresnelDielectric = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n\t\tmaterial.iridescenceFresnelMetallic = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.diffuseColor );\n\t\tmaterial.iridescenceFresnel = mix( material.iridescenceFresnelDielectric, material.iridescenceFresnelMetallic, material.metalness );\n\t\tmaterial.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );\n\t}\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometryPosition, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tvec4 spotColor;\n\tvec3 spotLightCoord;\n\tbool inSpotLightMap;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometryPosition, directLight );\n\t\t#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX\n\t\t#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS\n\t\t#else\n\t\t#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#endif\n\t\t#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )\n\t\t\tspotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;\n\t\t\tinSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );\n\t\t\tspotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );\n\t\t\tdirectLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;\n\t\t#endif\n\t\t#undef SPOT_LIGHT_MAP_INDEX\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#if defined( USE_LIGHT_PROBES )\n\t\tirradiance += getLightProbeIrradiance( lightProbe, geometryNormal );\n\t#endif\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif";
  227. var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometryNormal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\t#ifdef USE_ANISOTROPY\n\t\tradiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );\n\t#else\n\t\tradiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif";
  228. var lights_fragment_end = "#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif";
  229. var logdepthbuf_fragment = "#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )\n\tgl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif";
  230. var logdepthbuf_pars_fragment = "#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  231. var logdepthbuf_pars_vertex = "#ifdef USE_LOGARITHMIC_DEPTH_BUFFER\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  232. var logdepthbuf_vertex = "#ifdef USE_LOGARITHMIC_DEPTH_BUFFER\n\tvFragDepth = 1.0 + gl_Position.w;\n\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n#endif";
  233. var map_fragment = "#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vMapUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tsampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor );\n\t#endif\n\tdiffuseColor *= sampledDiffuseColor;\n#endif";
  234. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  235. var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t#if defined( USE_POINTS_UV )\n\t\tvec2 uv = vUv;\n\t#else\n\t\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tdiffuseColor *= texture2D( map, uv );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif";
  236. var map_particle_pars_fragment = "#if defined( USE_POINTS_UV )\n\tvarying vec2 vUv;\n#else\n\t#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t\tuniform mat3 uvTransform;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  237. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  238. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  239. var morphinstance_vertex = "#ifdef USE_INSTANCING_MORPH\n\tfloat morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\tfloat morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tmorphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r;\n\t}\n#endif";
  240. var morphcolor_vertex = "#if defined( USE_MORPHCOLORS )\n\tvColor *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t#if defined( USE_COLOR_ALPHA )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];\n\t\t#elif defined( USE_COLOR )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];\n\t\t#endif\n\t}\n#endif";
  241. var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n\t}\n#endif";
  242. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\t#ifndef USE_INSTANCING_MORPH\n\t\tuniform float morphTargetBaseInfluence;\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t#endif\n\tuniform sampler2DArray morphTargetsTexture;\n\tuniform ivec2 morphTargetsTextureSize;\n\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t}\n#endif";
  243. var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n\t}\n#endif";
  244. var normal_fragment_begin = "float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n\tvec3 fdx = dFdx( vViewPosition );\n\tvec3 fdy = dFdy( vViewPosition );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal *= faceDirection;\n\t#endif\n#endif\n#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn = getTangentFrame( - vViewPosition, normal,\n\t\t#if defined( USE_NORMALMAP )\n\t\t\tvNormalMapUv\n\t\t#elif defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tvClearcoatNormalMapUv\n\t\t#else\n\t\t\tvUv\n\t\t#endif\n\t\t);\n\t#endif\n\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\t\ttbn[0] *= faceDirection;\n\t\ttbn[1] *= faceDirection;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );\n\t#endif\n\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\t\ttbn2[0] *= faceDirection;\n\t\ttbn2[1] *= faceDirection;\n\t#endif\n#endif\nvec3 nonPerturbedNormal = normal;";
  245. var normal_fragment_maps = "#ifdef USE_NORMALMAP_OBJECTSPACE\n\tnormal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( USE_NORMALMAP_TANGENTSPACE )\n\tvec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\tnormal = normalize( tbn * mapN );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif";
  246. var normal_pars_fragment = "#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif";
  247. var normal_pars_vertex = "#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif";
  248. var normal_vertex = "#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif";
  249. var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef USE_NORMALMAP_OBJECTSPACE\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )\n\tmat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( uv.st );\n\t\tvec2 st1 = dFdy( uv.st );\n\t\tvec3 N = surf_norm;\n\t\tvec3 q1perp = cross( q1, N );\n\t\tvec3 q0perp = cross( N, q0 );\n\t\tvec3 T = q1perp * st0.x + q0perp * st1.x;\n\t\tvec3 B = q1perp * st0.y + q0perp * st1.y;\n\t\tfloat det = max( dot( T, T ), dot( B, B ) );\n\t\tfloat scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );\n\t\treturn mat3( T * scale, B * scale, N );\n\t}\n#endif";
  250. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = nonPerturbedNormal;\n#endif";
  251. var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\tclearcoatNormal = normalize( tbn2 * clearcoatMapN );\n#endif";
  252. var clearcoat_pars_fragment = "#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif";
  253. var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif";
  254. var opaque_fragment = "#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= material.transmissionAlpha;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );";
  255. var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.;\nconst float Inv255 = 1. / 255.;\nconst vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 );\nconst vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g );\nconst vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b );\nconst vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a );\nvec4 packDepthToRGBA( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec4( 0., 0., 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec4( 1., 1., 1., 1. );\n\tfloat vuf;\n\tfloat af = modf( v * PackFactors.a, vuf );\n\tfloat bf = modf( vuf * ShiftRight8, vuf );\n\tfloat gf = modf( vuf * ShiftRight8, vuf );\n\treturn vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af );\n}\nvec3 packDepthToRGB( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec3( 0., 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec3( 1., 1., 1. );\n\tfloat vuf;\n\tfloat bf = modf( v * PackFactors.b, vuf );\n\tfloat gf = modf( vuf * ShiftRight8, vuf );\n\treturn vec3( vuf * Inv255, gf * PackUpscale, bf );\n}\nvec2 packDepthToRG( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec2( 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec2( 1., 1. );\n\tfloat vuf;\n\tfloat gf = modf( v * 256., vuf );\n\treturn vec2( vuf * Inv255, gf );\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors4 );\n}\nfloat unpackRGBToDepth( const in vec3 v ) {\n\treturn dot( v, UnpackFactors3 );\n}\nfloat unpackRGToDepth( const in vec2 v ) {\n\treturn v.r * UnpackFactors2.r + v.g * UnpackFactors2.g;\n}\nvec4 pack2HalfToRGBA( const in vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( const in vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\treturn depth * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * depth - far );\n}";
  256. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  257. var project_vertex = "vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_BATCHING\n\tmvPosition = batchingMatrix * mvPosition;\n#endif\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;";
  258. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  259. var dithering_pars_fragment = "#ifdef DITHERING\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif";
  260. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  261. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  262. var shadowmap_pars_fragment = "#if NUM_SPOT_LIGHT_COORDS > 0\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n\tuniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tuniform sampler2DShadow directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\t#else\n\t\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\t#endif\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tuniform sampler2DShadow spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\t#else\n\t\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\t#endif\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tuniform samplerCubeShadow pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\t#elif defined( SHADOWMAP_TYPE_BASIC )\n\t\t\tuniform samplerCube pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\t#endif\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\tfloat interleavedGradientNoise( vec2 position ) {\n\t\t\treturn fract( 52.9829189 * fract( dot( position, vec2( 0.06711056, 0.00583715 ) ) ) );\n\t\t}\n\t\tvec2 vogelDiskSample( int sampleIndex, int samplesCount, float phi ) {\n\t\t\tconst float goldenAngle = 2.399963229728653;\n\t\t\tfloat r = sqrt( ( float( sampleIndex ) + 0.5 ) / float( samplesCount ) );\n\t\t\tfloat theta = float( sampleIndex ) * goldenAngle + phi;\n\t\t\treturn vec2( cos( theta ), sin( theta ) ) * r;\n\t\t}\n\t#endif\n\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\tfloat getShadow( sampler2DShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\t\tfloat shadow = 1.0;\n\t\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\t\tshadowCoord.z += shadowBias;\n\t\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\t\tif ( frustumTest ) {\n\t\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\t\tfloat radius = shadowRadius * texelSize.x;\n\t\t\t\tfloat phi = interleavedGradientNoise( gl_FragCoord.xy ) * 6.28318530718;\n\t\t\t\tshadow = (\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 0, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 1, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 2, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 3, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 4, 5, phi ) * radius, shadowCoord.z ) )\n\t\t\t\t) * 0.2;\n\t\t\t}\n\t\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t\t}\n\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\t\tfloat shadow = 1.0;\n\t\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\t\tshadowCoord.z += shadowBias;\n\t\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\t\tif ( frustumTest ) {\n\t\t\t\tvec2 distribution = texture2D( shadowMap, shadowCoord.xy ).rg;\n\t\t\t\tfloat mean = distribution.x;\n\t\t\t\tfloat variance = distribution.y * distribution.y;\n\t\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\t\tfloat hard_shadow = step( mean, shadowCoord.z );\n\t\t\t\t#else\n\t\t\t\t\tfloat hard_shadow = step( shadowCoord.z, mean );\n\t\t\t\t#endif\n\t\t\t\tif ( hard_shadow == 1.0 ) {\n\t\t\t\t\tshadow = 1.0;\n\t\t\t\t} else {\n\t\t\t\t\tvariance = max( variance, 0.0000001 );\n\t\t\t\t\tfloat d = shadowCoord.z - mean;\n\t\t\t\t\tfloat p_max = variance / ( variance + d * d );\n\t\t\t\t\tp_max = clamp( ( p_max - 0.3 ) / 0.65, 0.0, 1.0 );\n\t\t\t\t\tshadow = max( hard_shadow, p_max );\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t\t}\n\t#else\n\t\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\t\tfloat shadow = 1.0;\n\t\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\t\tshadowCoord.z += shadowBias;\n\t\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\t\tif ( frustumTest ) {\n\t\t\t\tfloat depth = texture2D( shadowMap, shadowCoord.xy ).r;\n\t\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\t\tshadow = step( depth, shadowCoord.z );\n\t\t\t\t#else\n\t\t\t\t\tshadow = step( shadowCoord.z, depth );\n\t\t\t\t#endif\n\t\t\t}\n\t\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t\t}\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#if defined( SHADOWMAP_TYPE_PCF )\n\tfloat getPointShadow( samplerCubeShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tfloat shadow = 1.0;\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\tvec3 absVec = abs( lightToPosition );\n\t\tfloat viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z );\n\t\tif ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) {\n\t\t\tfloat dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );\n\t\t\tdp += shadowBias;\n\t\t\tfloat texelSize = shadowRadius / shadowMapSize.x;\n\t\t\tvec3 absDir = abs( bd3D );\n\t\t\tvec3 tangent = absDir.x > absDir.z ? vec3( 0.0, 1.0, 0.0 ) : vec3( 1.0, 0.0, 0.0 );\n\t\t\ttangent = normalize( cross( bd3D, tangent ) );\n\t\t\tvec3 bitangent = cross( bd3D, tangent );\n\t\t\tfloat phi = interleavedGradientNoise( gl_FragCoord.xy ) * 6.28318530718;\n\t\t\tshadow = (\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * vogelDiskSample( 0, 5, phi ).x + bitangent * vogelDiskSample( 0, 5, phi ).y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * vogelDiskSample( 1, 5, phi ).x + bitangent * vogelDiskSample( 1, 5, phi ).y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * vogelDiskSample( 2, 5, phi ).x + bitangent * vogelDiskSample( 2, 5, phi ).y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * vogelDiskSample( 3, 5, phi ).x + bitangent * vogelDiskSample( 3, 5, phi ).y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * vogelDiskSample( 4, 5, phi ).x + bitangent * vogelDiskSample( 4, 5, phi ).y ) * texelSize, dp ) )\n\t\t\t) * 0.2;\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n\t#elif defined( SHADOWMAP_TYPE_BASIC )\n\tfloat getPointShadow( samplerCube shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tfloat shadow = 1.0;\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\tvec3 absVec = abs( lightToPosition );\n\t\tfloat viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z );\n\t\tif ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) {\n\t\t\tfloat dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );\n\t\t\tdp += shadowBias;\n\t\t\tfloat depth = textureCube( shadowMap, bd3D ).r;\n\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\tshadow = step( depth, dp );\n\t\t\t#else\n\t\t\t\tshadow = step( dp, depth );\n\t\t\t#endif\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n\t#endif\n\t#endif\n#endif";
  263. var shadowmap_pars_vertex = "#if NUM_SPOT_LIGHT_COORDS > 0\n\tuniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif";
  264. var shadowmap_vertex = "#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )\n\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\tvec4 shadowWorldPosition;\n#endif\n#if defined( USE_SHADOWMAP )\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if NUM_SPOT_LIGHT_COORDS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition;\n\t\t#if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t\tshadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;\n\t\t#endif\n\t\tvSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n#endif";
  265. var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0 && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) )\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}";
  266. var skinbase_vertex = "#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif";
  267. var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\tuniform highp sampler2D boneTexture;\n\tmat4 getBoneMatrix( const in float i ) {\n\t\tint size = textureSize( boneTexture, 0 ).x;\n\t\tint j = int( i ) * 4;\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\tvec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 );\n\t\tvec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 );\n\t\tvec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 );\n\t\tvec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );\n\t\treturn mat4( v1, v2, v3, v4 );\n\t}\n#endif";
  268. var skinning_vertex = "#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif";
  269. var skinnormal_vertex = "#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif";
  270. var specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif";
  271. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  272. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  273. var tonemapping_pars_fragment = "#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn saturate( toneMappingExposure * color );\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 CineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nconst mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(\n\tvec3( 1.6605, - 0.1246, - 0.0182 ),\n\tvec3( - 0.5876, 1.1329, - 0.1006 ),\n\tvec3( - 0.0728, - 0.0083, 1.1187 )\n);\nconst mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(\n\tvec3( 0.6274, 0.0691, 0.0164 ),\n\tvec3( 0.3293, 0.9195, 0.0880 ),\n\tvec3( 0.0433, 0.0113, 0.8956 )\n);\nvec3 agxDefaultContrastApprox( vec3 x ) {\n\tvec3 x2 = x * x;\n\tvec3 x4 = x2 * x2;\n\treturn + 15.5 * x4 * x2\n\t\t- 40.14 * x4 * x\n\t\t+ 31.96 * x4\n\t\t- 6.868 * x2 * x\n\t\t+ 0.4298 * x2\n\t\t+ 0.1191 * x\n\t\t- 0.00232;\n}\nvec3 AgXToneMapping( vec3 color ) {\n\tconst mat3 AgXInsetMatrix = mat3(\n\t\tvec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),\n\t\tvec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),\n\t\tvec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )\n\t);\n\tconst mat3 AgXOutsetMatrix = mat3(\n\t\tvec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),\n\t\tvec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),\n\t\tvec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )\n\t);\n\tconst float AgxMinEv = - 12.47393;\tconst float AgxMaxEv = 4.026069;\n\tcolor *= toneMappingExposure;\n\tcolor = LINEAR_SRGB_TO_LINEAR_REC2020 * color;\n\tcolor = AgXInsetMatrix * color;\n\tcolor = max( color, 1e-10 );\tcolor = log2( color );\n\tcolor = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );\n\tcolor = clamp( color, 0.0, 1.0 );\n\tcolor = agxDefaultContrastApprox( color );\n\tcolor = AgXOutsetMatrix * color;\n\tcolor = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );\n\tcolor = LINEAR_REC2020_TO_LINEAR_SRGB * color;\n\tcolor = clamp( color, 0.0, 1.0 );\n\treturn color;\n}\nvec3 NeutralToneMapping( vec3 color ) {\n\tconst float StartCompression = 0.8 - 0.04;\n\tconst float Desaturation = 0.15;\n\tcolor *= toneMappingExposure;\n\tfloat x = min( color.r, min( color.g, color.b ) );\n\tfloat offset = x < 0.08 ? x - 6.25 * x * x : 0.04;\n\tcolor -= offset;\n\tfloat peak = max( color.r, max( color.g, color.b ) );\n\tif ( peak < StartCompression ) return color;\n\tfloat d = 1. - StartCompression;\n\tfloat newPeak = 1. - d * d / ( peak + d - StartCompression );\n\tcolor *= newPeak / peak;\n\tfloat g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );\n\treturn mix( color, vec3( newPeak ), g );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }";
  274. var transmission_fragment = "#ifdef USE_TRANSMISSION\n\tmaterial.transmission = transmission;\n\tmaterial.transmissionAlpha = 1.0;\n\tmaterial.thickness = thickness;\n\tmaterial.attenuationDistance = attenuationDistance;\n\tmaterial.attenuationColor = attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tmaterial.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tmaterial.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmitted = getIBLVolumeRefraction(\n\t\tn, v, material.roughness, material.diffuseContribution, material.specularColorBlended, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness,\n\t\tmaterial.attenuationColor, material.attenuationDistance );\n\tmaterial.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );\n\ttotalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );\n#endif";
  275. var transmission_pars_fragment = "#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tfloat w0( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );\n\t}\n\tfloat w1( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 );\n\t}\n\tfloat w2( float a ){\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );\n\t}\n\tfloat w3( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * a );\n\t}\n\tfloat g0( float a ) {\n\t\treturn w0( a ) + w1( a );\n\t}\n\tfloat g1( float a ) {\n\t\treturn w2( a ) + w3( a );\n\t}\n\tfloat h0( float a ) {\n\t\treturn - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );\n\t}\n\tfloat h1( float a ) {\n\t\treturn 1.0 + w3( a ) / ( w2( a ) + w3( a ) );\n\t}\n\tvec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {\n\t\tuv = uv * texelSize.zw + 0.5;\n\t\tvec2 iuv = floor( uv );\n\t\tvec2 fuv = fract( uv );\n\t\tfloat g0x = g0( fuv.x );\n\t\tfloat g1x = g1( fuv.x );\n\t\tfloat h0x = h0( fuv.x );\n\t\tfloat h1x = h1( fuv.x );\n\t\tfloat h0y = h0( fuv.y );\n\t\tfloat h1y = h1( fuv.y );\n\t\tvec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\treturn g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +\n\t\t\tg1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );\n\t}\n\tvec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {\n\t\tvec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );\n\t\tvec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );\n\t\tvec2 fLodSizeInv = 1.0 / fLodSize;\n\t\tvec2 cLodSizeInv = 1.0 / cLodSize;\n\t\tvec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );\n\t\tvec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );\n\t\treturn mix( fSample, cSample, fract( lod ) );\n\t}\n\tvec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( const in float roughness, const in float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n\t\tfloat lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\treturn textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );\n\t}\n\tvec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( isinf( attenuationDistance ) ) {\n\t\t\treturn vec3( 1.0 );\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n\t\tconst in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n\t\tconst in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec4 transmittedLight;\n\t\tvec3 transmittance;\n\t\t#ifdef USE_DISPERSION\n\t\t\tfloat halfSpread = ( ior - 1.0 ) * 0.025 * dispersion;\n\t\t\tvec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread );\n\t\t\tfor ( int i = 0; i < 3; i ++ ) {\n\t\t\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix );\n\t\t\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\t\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\t\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\t\t\trefractionCoords += 1.0;\n\t\t\t\trefractionCoords /= 2.0;\n\t\t\t\tvec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] );\n\t\t\t\ttransmittedLight[ i ] = transmissionSample[ i ];\n\t\t\t\ttransmittedLight.a += transmissionSample.a;\n\t\t\t\ttransmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ];\n\t\t\t}\n\t\t\ttransmittedLight.a /= 3.0;\n\t\t#else\n\t\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\t\trefractionCoords += 1.0;\n\t\t\trefractionCoords /= 2.0;\n\t\t\ttransmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\t\ttransmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\t#endif\n\t\tvec3 attenuatedColor = transmittance * transmittedLight.rgb;\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\tfloat transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );\n\t}\n#endif";
  276. var uv_pars_fragment = "#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif";
  277. var uv_pars_vertex = "#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tuniform mat3 mapTransform;\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform mat3 alphaMapTransform;\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tuniform mat3 lightMapTransform;\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tuniform mat3 aoMapTransform;\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tuniform mat3 bumpMapTransform;\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tuniform mat3 normalMapTransform;\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tuniform mat3 displacementMapTransform;\n\tvarying vec2 vDisplacementMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tuniform mat3 emissiveMapTransform;\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tuniform mat3 metalnessMapTransform;\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tuniform mat3 roughnessMapTransform;\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tuniform mat3 anisotropyMapTransform;\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tuniform mat3 clearcoatMapTransform;\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform mat3 clearcoatNormalMapTransform;\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform mat3 clearcoatRoughnessMapTransform;\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tuniform mat3 sheenColorMapTransform;\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tuniform mat3 sheenRoughnessMapTransform;\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tuniform mat3 iridescenceMapTransform;\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform mat3 iridescenceThicknessMapTransform;\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tuniform mat3 specularMapTransform;\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tuniform mat3 specularColorMapTransform;\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tuniform mat3 specularIntensityMapTransform;\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif";
  278. var uv_vertex = "#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvUv = vec3( uv, 1 ).xy;\n#endif\n#ifdef USE_MAP\n\tvMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ALPHAMAP\n\tvAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_LIGHTMAP\n\tvLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_AOMAP\n\tvAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_BUMPMAP\n\tvBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_NORMALMAP\n\tvNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tvDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_METALNESSMAP\n\tvMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULARMAP\n\tvSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tvTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_THICKNESSMAP\n\tvThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;\n#endif";
  279. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_BATCHING\n\t\tworldPosition = batchingMatrix * worldPosition;\n\t#endif\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif";
  280. const vertex$h = "varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}";
  281. const fragment$h = "uniform sampler2D t2D;\nuniform float backgroundIntensity;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\ttexColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}";
  282. const vertex$g = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\tgl_Position.z = gl_Position.w;\n}";
  283. const fragment$g = "#ifdef ENVMAP_TYPE_CUBE\n\tuniform samplerCube envMap;\n#elif defined( ENVMAP_TYPE_CUBE_UV )\n\tuniform sampler2D envMap;\n#endif\nuniform float flipEnvMap;\nuniform float backgroundBlurriness;\nuniform float backgroundIntensity;\nuniform mat3 backgroundRotation;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness );\n\t#else\n\t\tvec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}";
  284. const vertex$f = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\tgl_Position.z = gl_Position.w;\n}";
  285. const fragment$f = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldDirection;\nvoid main() {\n\tvec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );\n\tgl_FragColor = texColor;\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}";
  286. const vertex$e = "#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <uv_vertex>\n\t#include <batching_vertex>\n\t#include <skinbase_vertex>\n\t#include <morphinstance_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvHighPrecisionZW = gl_Position.zw;\n}";
  287. const fragment$e = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <clipping_planes_fragment>\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <logdepthbuf_fragment>\n\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\tfloat fragCoordZ = vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ];\n\t#else\n\t\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ] + 0.5;\n\t#endif\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#elif DEPTH_PACKING == 3202\n\t\tgl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 );\n\t#elif DEPTH_PACKING == 3203\n\t\tgl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 );\n\t#endif\n}";
  288. const vertex$d = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <batching_vertex>\n\t#include <skinbase_vertex>\n\t#include <morphinstance_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition.xyz;\n}";
  289. const fragment$d = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <clipping_planes_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = vec4( dist, 0.0, 0.0, 1.0 );\n}";
  290. const vertex$c = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}";
  291. const fragment$c = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}";
  292. const vertex$b = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  293. const fragment$b = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  294. const vertex$a = "#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinbase_vertex>\n\t\t#include <skinnormal_vertex>\n\t\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}";
  295. const fragment$a = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\treflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  296. const vertex$9 = "#define LAMBERT\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  297. const fragment$9 = "#define LAMBERT\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_lambert_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_lambert_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  298. const vertex$8 = "#define MATCAP\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\tvViewPosition = - mvPosition.xyz;\n}";
  299. const fragment$8 = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t#else\n\t\tvec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  300. const vertex$7 = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvarying vec3 vViewPosition;\n#endif\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}";
  301. const fragment$7 = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvarying vec3 vViewPosition;\n#endif\n#include <uv_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity );\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tgl_FragColor = vec4( normalize( normal ) * 0.5 + 0.5, diffuseColor.a );\n\t#ifdef OPAQUE\n\t\tgl_FragColor.a = 1.0;\n\t#endif\n}";
  302. const vertex$6 = "#define PHONG\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  303. const fragment$6 = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  304. const vertex$5 = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\n#endif\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}";
  305. const fragment$5 = "#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define USE_SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef USE_SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULAR_COLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_DISPERSION\n\tuniform float dispersion;\n#endif\n#ifdef USE_IRIDESCENCE\n\tuniform float iridescence;\n\tuniform float iridescenceIOR;\n\tuniform float iridescenceThicknessMinimum;\n\tuniform float iridescenceThicknessMaximum;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenColor;\n\tuniform float sheenRoughness;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\tuniform vec2 anisotropyVector;\n\t#ifdef USE_ANISOTROPYMAP\n\t\tuniform sampler2D anisotropyMap;\n\t#endif\n#endif\nvarying vec3 vViewPosition;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <iridescence_fragment>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_physical_pars_fragment>\n#include <transmission_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_pars_fragment>\n#include <iridescence_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include <transmission_fragment>\n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_SHEEN\n \n\t\toutgoingLight = outgoingLight + sheenSpecularDirect + sheenSpecularIndirect;\n \n \t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;\n\t#endif\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  306. const vertex$4 = "#define TOON\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  307. const fragment$4 = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_toon_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_toon_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  308. const vertex$3 = "uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\n#ifdef USE_POINTS_UV\n\tvarying vec2 vUv;\n\tuniform mat3 uvTransform;\n#endif\nvoid main() {\n\t#ifdef USE_POINTS_UV\n\t\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\t#endif\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <fog_vertex>\n}";
  309. const fragment$3 = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  310. const vertex$2 = "#include <common>\n#include <batching_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  311. const fragment$2 = "uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <logdepthbuf_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\t#include <logdepthbuf_fragment>\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  312. const vertex$1 = "uniform float rotation;\nuniform vec2 center;\n#include <common>\n#include <uv_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\tvec4 mvPosition = modelViewMatrix[ 3 ];\n\tvec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  313. const fragment$1 = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n}";
  314. const ShaderChunk = {
  315. alphahash_fragment: alphahash_fragment,
  316. alphahash_pars_fragment: alphahash_pars_fragment,
  317. alphamap_fragment: alphamap_fragment,
  318. alphamap_pars_fragment: alphamap_pars_fragment,
  319. alphatest_fragment: alphatest_fragment,
  320. alphatest_pars_fragment: alphatest_pars_fragment,
  321. aomap_fragment: aomap_fragment,
  322. aomap_pars_fragment: aomap_pars_fragment,
  323. batching_pars_vertex: batching_pars_vertex,
  324. batching_vertex: batching_vertex,
  325. begin_vertex: begin_vertex,
  326. beginnormal_vertex: beginnormal_vertex,
  327. bsdfs: bsdfs,
  328. iridescence_fragment: iridescence_fragment,
  329. bumpmap_pars_fragment: bumpmap_pars_fragment,
  330. clipping_planes_fragment: clipping_planes_fragment,
  331. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  332. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  333. clipping_planes_vertex: clipping_planes_vertex,
  334. color_fragment: color_fragment,
  335. color_pars_fragment: color_pars_fragment,
  336. color_pars_vertex: color_pars_vertex,
  337. color_vertex: color_vertex,
  338. common: common,
  339. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  340. defaultnormal_vertex: defaultnormal_vertex,
  341. displacementmap_pars_vertex: displacementmap_pars_vertex,
  342. displacementmap_vertex: displacementmap_vertex,
  343. emissivemap_fragment: emissivemap_fragment,
  344. emissivemap_pars_fragment: emissivemap_pars_fragment,
  345. colorspace_fragment: colorspace_fragment,
  346. colorspace_pars_fragment: colorspace_pars_fragment,
  347. envmap_fragment: envmap_fragment,
  348. envmap_common_pars_fragment: envmap_common_pars_fragment,
  349. envmap_pars_fragment: envmap_pars_fragment,
  350. envmap_pars_vertex: envmap_pars_vertex,
  351. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  352. envmap_vertex: envmap_vertex,
  353. fog_vertex: fog_vertex,
  354. fog_pars_vertex: fog_pars_vertex,
  355. fog_fragment: fog_fragment,
  356. fog_pars_fragment: fog_pars_fragment,
  357. gradientmap_pars_fragment: gradientmap_pars_fragment,
  358. lightmap_pars_fragment: lightmap_pars_fragment,
  359. lights_lambert_fragment: lights_lambert_fragment,
  360. lights_lambert_pars_fragment: lights_lambert_pars_fragment,
  361. lights_pars_begin: lights_pars_begin,
  362. lights_toon_fragment: lights_toon_fragment,
  363. lights_toon_pars_fragment: lights_toon_pars_fragment,
  364. lights_phong_fragment: lights_phong_fragment,
  365. lights_phong_pars_fragment: lights_phong_pars_fragment,
  366. lights_physical_fragment: lights_physical_fragment,
  367. lights_physical_pars_fragment: lights_physical_pars_fragment,
  368. lights_fragment_begin: lights_fragment_begin,
  369. lights_fragment_maps: lights_fragment_maps,
  370. lights_fragment_end: lights_fragment_end,
  371. logdepthbuf_fragment: logdepthbuf_fragment,
  372. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  373. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  374. logdepthbuf_vertex: logdepthbuf_vertex,
  375. map_fragment: map_fragment,
  376. map_pars_fragment: map_pars_fragment,
  377. map_particle_fragment: map_particle_fragment,
  378. map_particle_pars_fragment: map_particle_pars_fragment,
  379. metalnessmap_fragment: metalnessmap_fragment,
  380. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  381. morphinstance_vertex: morphinstance_vertex,
  382. morphcolor_vertex: morphcolor_vertex,
  383. morphnormal_vertex: morphnormal_vertex,
  384. morphtarget_pars_vertex: morphtarget_pars_vertex,
  385. morphtarget_vertex: morphtarget_vertex,
  386. normal_fragment_begin: normal_fragment_begin,
  387. normal_fragment_maps: normal_fragment_maps,
  388. normal_pars_fragment: normal_pars_fragment,
  389. normal_pars_vertex: normal_pars_vertex,
  390. normal_vertex: normal_vertex,
  391. normalmap_pars_fragment: normalmap_pars_fragment,
  392. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  393. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  394. clearcoat_pars_fragment: clearcoat_pars_fragment,
  395. iridescence_pars_fragment: iridescence_pars_fragment,
  396. opaque_fragment: opaque_fragment,
  397. packing: packing,
  398. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  399. project_vertex: project_vertex,
  400. dithering_fragment: dithering_fragment,
  401. dithering_pars_fragment: dithering_pars_fragment,
  402. roughnessmap_fragment: roughnessmap_fragment,
  403. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  404. shadowmap_pars_fragment: shadowmap_pars_fragment,
  405. shadowmap_pars_vertex: shadowmap_pars_vertex,
  406. shadowmap_vertex: shadowmap_vertex,
  407. shadowmask_pars_fragment: shadowmask_pars_fragment,
  408. skinbase_vertex: skinbase_vertex,
  409. skinning_pars_vertex: skinning_pars_vertex,
  410. skinning_vertex: skinning_vertex,
  411. skinnormal_vertex: skinnormal_vertex,
  412. specularmap_fragment: specularmap_fragment,
  413. specularmap_pars_fragment: specularmap_pars_fragment,
  414. tonemapping_fragment: tonemapping_fragment,
  415. tonemapping_pars_fragment: tonemapping_pars_fragment,
  416. transmission_fragment: transmission_fragment,
  417. transmission_pars_fragment: transmission_pars_fragment,
  418. uv_pars_fragment: uv_pars_fragment,
  419. uv_pars_vertex: uv_pars_vertex,
  420. uv_vertex: uv_vertex,
  421. worldpos_vertex: worldpos_vertex,
  422. background_vert: vertex$h,
  423. background_frag: fragment$h,
  424. backgroundCube_vert: vertex$g,
  425. backgroundCube_frag: fragment$g,
  426. cube_vert: vertex$f,
  427. cube_frag: fragment$f,
  428. depth_vert: vertex$e,
  429. depth_frag: fragment$e,
  430. distance_vert: vertex$d,
  431. distance_frag: fragment$d,
  432. equirect_vert: vertex$c,
  433. equirect_frag: fragment$c,
  434. linedashed_vert: vertex$b,
  435. linedashed_frag: fragment$b,
  436. meshbasic_vert: vertex$a,
  437. meshbasic_frag: fragment$a,
  438. meshlambert_vert: vertex$9,
  439. meshlambert_frag: fragment$9,
  440. meshmatcap_vert: vertex$8,
  441. meshmatcap_frag: fragment$8,
  442. meshnormal_vert: vertex$7,
  443. meshnormal_frag: fragment$7,
  444. meshphong_vert: vertex$6,
  445. meshphong_frag: fragment$6,
  446. meshphysical_vert: vertex$5,
  447. meshphysical_frag: fragment$5,
  448. meshtoon_vert: vertex$4,
  449. meshtoon_frag: fragment$4,
  450. points_vert: vertex$3,
  451. points_frag: fragment$3,
  452. shadow_vert: vertex$2,
  453. shadow_frag: fragment$2,
  454. sprite_vert: vertex$1,
  455. sprite_frag: fragment$1
  456. };
  457. // Uniforms library for shared webgl shaders
  458. const UniformsLib = {
  459. common: {
  460. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  461. opacity: { value: 1.0 },
  462. map: { value: null },
  463. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  464. alphaMap: { value: null },
  465. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  466. alphaTest: { value: 0 }
  467. },
  468. specularmap: {
  469. specularMap: { value: null },
  470. specularMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  471. },
  472. envmap: {
  473. envMap: { value: null },
  474. envMapRotation: { value: /*@__PURE__*/ new Matrix3() },
  475. flipEnvMap: { value: -1 },
  476. reflectivity: { value: 1.0 }, // basic, lambert, phong
  477. ior: { value: 1.5 }, // physical
  478. refractionRatio: { value: 0.98 }, // basic, lambert, phong
  479. dfgLUT: { value: null } // DFG LUT for physically-based rendering
  480. },
  481. aomap: {
  482. aoMap: { value: null },
  483. aoMapIntensity: { value: 1 },
  484. aoMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  485. },
  486. lightmap: {
  487. lightMap: { value: null },
  488. lightMapIntensity: { value: 1 },
  489. lightMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  490. },
  491. bumpmap: {
  492. bumpMap: { value: null },
  493. bumpMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  494. bumpScale: { value: 1 }
  495. },
  496. normalmap: {
  497. normalMap: { value: null },
  498. normalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  499. normalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }
  500. },
  501. displacementmap: {
  502. displacementMap: { value: null },
  503. displacementMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  504. displacementScale: { value: 1 },
  505. displacementBias: { value: 0 }
  506. },
  507. emissivemap: {
  508. emissiveMap: { value: null },
  509. emissiveMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  510. },
  511. metalnessmap: {
  512. metalnessMap: { value: null },
  513. metalnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  514. },
  515. roughnessmap: {
  516. roughnessMap: { value: null },
  517. roughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  518. },
  519. gradientmap: {
  520. gradientMap: { value: null }
  521. },
  522. fog: {
  523. fogDensity: { value: 0.00025 },
  524. fogNear: { value: 1 },
  525. fogFar: { value: 2000 },
  526. fogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) }
  527. },
  528. lights: {
  529. ambientLightColor: { value: [] },
  530. lightProbe: { value: [] },
  531. directionalLights: { value: [], properties: {
  532. direction: {},
  533. color: {}
  534. } },
  535. directionalLightShadows: { value: [], properties: {
  536. shadowIntensity: 1,
  537. shadowBias: {},
  538. shadowNormalBias: {},
  539. shadowRadius: {},
  540. shadowMapSize: {}
  541. } },
  542. directionalShadowMatrix: { value: [] },
  543. spotLights: { value: [], properties: {
  544. color: {},
  545. position: {},
  546. direction: {},
  547. distance: {},
  548. coneCos: {},
  549. penumbraCos: {},
  550. decay: {}
  551. } },
  552. spotLightShadows: { value: [], properties: {
  553. shadowIntensity: 1,
  554. shadowBias: {},
  555. shadowNormalBias: {},
  556. shadowRadius: {},
  557. shadowMapSize: {}
  558. } },
  559. spotLightMap: { value: [] },
  560. spotLightMatrix: { value: [] },
  561. pointLights: { value: [], properties: {
  562. color: {},
  563. position: {},
  564. decay: {},
  565. distance: {}
  566. } },
  567. pointLightShadows: { value: [], properties: {
  568. shadowIntensity: 1,
  569. shadowBias: {},
  570. shadowNormalBias: {},
  571. shadowRadius: {},
  572. shadowMapSize: {},
  573. shadowCameraNear: {},
  574. shadowCameraFar: {}
  575. } },
  576. pointShadowMatrix: { value: [] },
  577. hemisphereLights: { value: [], properties: {
  578. direction: {},
  579. skyColor: {},
  580. groundColor: {}
  581. } },
  582. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  583. rectAreaLights: { value: [], properties: {
  584. color: {},
  585. position: {},
  586. width: {},
  587. height: {}
  588. } },
  589. ltc_1: { value: null },
  590. ltc_2: { value: null }
  591. },
  592. points: {
  593. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  594. opacity: { value: 1.0 },
  595. size: { value: 1.0 },
  596. scale: { value: 1.0 },
  597. map: { value: null },
  598. alphaMap: { value: null },
  599. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  600. alphaTest: { value: 0 },
  601. uvTransform: { value: /*@__PURE__*/ new Matrix3() }
  602. },
  603. sprite: {
  604. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  605. opacity: { value: 1.0 },
  606. center: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) },
  607. rotation: { value: 0.0 },
  608. map: { value: null },
  609. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  610. alphaMap: { value: null },
  611. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  612. alphaTest: { value: 0 }
  613. }
  614. };
  615. const ShaderLib = {
  616. basic: {
  617. uniforms: /*@__PURE__*/ mergeUniforms( [
  618. UniformsLib.common,
  619. UniformsLib.specularmap,
  620. UniformsLib.envmap,
  621. UniformsLib.aomap,
  622. UniformsLib.lightmap,
  623. UniformsLib.fog
  624. ] ),
  625. vertexShader: ShaderChunk.meshbasic_vert,
  626. fragmentShader: ShaderChunk.meshbasic_frag
  627. },
  628. lambert: {
  629. uniforms: /*@__PURE__*/ mergeUniforms( [
  630. UniformsLib.common,
  631. UniformsLib.specularmap,
  632. UniformsLib.envmap,
  633. UniformsLib.aomap,
  634. UniformsLib.lightmap,
  635. UniformsLib.emissivemap,
  636. UniformsLib.bumpmap,
  637. UniformsLib.normalmap,
  638. UniformsLib.displacementmap,
  639. UniformsLib.fog,
  640. UniformsLib.lights,
  641. {
  642. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  643. }
  644. ] ),
  645. vertexShader: ShaderChunk.meshlambert_vert,
  646. fragmentShader: ShaderChunk.meshlambert_frag
  647. },
  648. phong: {
  649. uniforms: /*@__PURE__*/ mergeUniforms( [
  650. UniformsLib.common,
  651. UniformsLib.specularmap,
  652. UniformsLib.envmap,
  653. UniformsLib.aomap,
  654. UniformsLib.lightmap,
  655. UniformsLib.emissivemap,
  656. UniformsLib.bumpmap,
  657. UniformsLib.normalmap,
  658. UniformsLib.displacementmap,
  659. UniformsLib.fog,
  660. UniformsLib.lights,
  661. {
  662. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  663. specular: { value: /*@__PURE__*/ new Color( 0x111111 ) },
  664. shininess: { value: 30 }
  665. }
  666. ] ),
  667. vertexShader: ShaderChunk.meshphong_vert,
  668. fragmentShader: ShaderChunk.meshphong_frag
  669. },
  670. standard: {
  671. uniforms: /*@__PURE__*/ mergeUniforms( [
  672. UniformsLib.common,
  673. UniformsLib.envmap,
  674. UniformsLib.aomap,
  675. UniformsLib.lightmap,
  676. UniformsLib.emissivemap,
  677. UniformsLib.bumpmap,
  678. UniformsLib.normalmap,
  679. UniformsLib.displacementmap,
  680. UniformsLib.roughnessmap,
  681. UniformsLib.metalnessmap,
  682. UniformsLib.fog,
  683. UniformsLib.lights,
  684. {
  685. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  686. roughness: { value: 1.0 },
  687. metalness: { value: 0.0 },
  688. envMapIntensity: { value: 1 }
  689. }
  690. ] ),
  691. vertexShader: ShaderChunk.meshphysical_vert,
  692. fragmentShader: ShaderChunk.meshphysical_frag
  693. },
  694. toon: {
  695. uniforms: /*@__PURE__*/ mergeUniforms( [
  696. UniformsLib.common,
  697. UniformsLib.aomap,
  698. UniformsLib.lightmap,
  699. UniformsLib.emissivemap,
  700. UniformsLib.bumpmap,
  701. UniformsLib.normalmap,
  702. UniformsLib.displacementmap,
  703. UniformsLib.gradientmap,
  704. UniformsLib.fog,
  705. UniformsLib.lights,
  706. {
  707. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  708. }
  709. ] ),
  710. vertexShader: ShaderChunk.meshtoon_vert,
  711. fragmentShader: ShaderChunk.meshtoon_frag
  712. },
  713. matcap: {
  714. uniforms: /*@__PURE__*/ mergeUniforms( [
  715. UniformsLib.common,
  716. UniformsLib.bumpmap,
  717. UniformsLib.normalmap,
  718. UniformsLib.displacementmap,
  719. UniformsLib.fog,
  720. {
  721. matcap: { value: null }
  722. }
  723. ] ),
  724. vertexShader: ShaderChunk.meshmatcap_vert,
  725. fragmentShader: ShaderChunk.meshmatcap_frag
  726. },
  727. points: {
  728. uniforms: /*@__PURE__*/ mergeUniforms( [
  729. UniformsLib.points,
  730. UniformsLib.fog
  731. ] ),
  732. vertexShader: ShaderChunk.points_vert,
  733. fragmentShader: ShaderChunk.points_frag
  734. },
  735. dashed: {
  736. uniforms: /*@__PURE__*/ mergeUniforms( [
  737. UniformsLib.common,
  738. UniformsLib.fog,
  739. {
  740. scale: { value: 1 },
  741. dashSize: { value: 1 },
  742. totalSize: { value: 2 }
  743. }
  744. ] ),
  745. vertexShader: ShaderChunk.linedashed_vert,
  746. fragmentShader: ShaderChunk.linedashed_frag
  747. },
  748. depth: {
  749. uniforms: /*@__PURE__*/ mergeUniforms( [
  750. UniformsLib.common,
  751. UniformsLib.displacementmap
  752. ] ),
  753. vertexShader: ShaderChunk.depth_vert,
  754. fragmentShader: ShaderChunk.depth_frag
  755. },
  756. normal: {
  757. uniforms: /*@__PURE__*/ mergeUniforms( [
  758. UniformsLib.common,
  759. UniformsLib.bumpmap,
  760. UniformsLib.normalmap,
  761. UniformsLib.displacementmap,
  762. {
  763. opacity: { value: 1.0 }
  764. }
  765. ] ),
  766. vertexShader: ShaderChunk.meshnormal_vert,
  767. fragmentShader: ShaderChunk.meshnormal_frag
  768. },
  769. sprite: {
  770. uniforms: /*@__PURE__*/ mergeUniforms( [
  771. UniformsLib.sprite,
  772. UniformsLib.fog
  773. ] ),
  774. vertexShader: ShaderChunk.sprite_vert,
  775. fragmentShader: ShaderChunk.sprite_frag
  776. },
  777. background: {
  778. uniforms: {
  779. uvTransform: { value: /*@__PURE__*/ new Matrix3() },
  780. t2D: { value: null },
  781. backgroundIntensity: { value: 1 }
  782. },
  783. vertexShader: ShaderChunk.background_vert,
  784. fragmentShader: ShaderChunk.background_frag
  785. },
  786. backgroundCube: {
  787. uniforms: {
  788. envMap: { value: null },
  789. flipEnvMap: { value: -1 },
  790. backgroundBlurriness: { value: 0 },
  791. backgroundIntensity: { value: 1 },
  792. backgroundRotation: { value: /*@__PURE__*/ new Matrix3() }
  793. },
  794. vertexShader: ShaderChunk.backgroundCube_vert,
  795. fragmentShader: ShaderChunk.backgroundCube_frag
  796. },
  797. cube: {
  798. uniforms: {
  799. tCube: { value: null },
  800. tFlip: { value: -1 },
  801. opacity: { value: 1.0 }
  802. },
  803. vertexShader: ShaderChunk.cube_vert,
  804. fragmentShader: ShaderChunk.cube_frag
  805. },
  806. equirect: {
  807. uniforms: {
  808. tEquirect: { value: null },
  809. },
  810. vertexShader: ShaderChunk.equirect_vert,
  811. fragmentShader: ShaderChunk.equirect_frag
  812. },
  813. distance: {
  814. uniforms: /*@__PURE__*/ mergeUniforms( [
  815. UniformsLib.common,
  816. UniformsLib.displacementmap,
  817. {
  818. referencePosition: { value: /*@__PURE__*/ new Vector3() },
  819. nearDistance: { value: 1 },
  820. farDistance: { value: 1000 }
  821. }
  822. ] ),
  823. vertexShader: ShaderChunk.distance_vert,
  824. fragmentShader: ShaderChunk.distance_frag
  825. },
  826. shadow: {
  827. uniforms: /*@__PURE__*/ mergeUniforms( [
  828. UniformsLib.lights,
  829. UniformsLib.fog,
  830. {
  831. color: { value: /*@__PURE__*/ new Color( 0x00000 ) },
  832. opacity: { value: 1.0 }
  833. },
  834. ] ),
  835. vertexShader: ShaderChunk.shadow_vert,
  836. fragmentShader: ShaderChunk.shadow_frag
  837. }
  838. };
  839. ShaderLib.physical = {
  840. uniforms: /*@__PURE__*/ mergeUniforms( [
  841. ShaderLib.standard.uniforms,
  842. {
  843. clearcoat: { value: 0 },
  844. clearcoatMap: { value: null },
  845. clearcoatMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  846. clearcoatNormalMap: { value: null },
  847. clearcoatNormalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  848. clearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) },
  849. clearcoatRoughness: { value: 0 },
  850. clearcoatRoughnessMap: { value: null },
  851. clearcoatRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  852. dispersion: { value: 0 },
  853. iridescence: { value: 0 },
  854. iridescenceMap: { value: null },
  855. iridescenceMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  856. iridescenceIOR: { value: 1.3 },
  857. iridescenceThicknessMinimum: { value: 100 },
  858. iridescenceThicknessMaximum: { value: 400 },
  859. iridescenceThicknessMap: { value: null },
  860. iridescenceThicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  861. sheen: { value: 0 },
  862. sheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  863. sheenColorMap: { value: null },
  864. sheenColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  865. sheenRoughness: { value: 1 },
  866. sheenRoughnessMap: { value: null },
  867. sheenRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  868. transmission: { value: 0 },
  869. transmissionMap: { value: null },
  870. transmissionMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  871. transmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() },
  872. transmissionSamplerMap: { value: null },
  873. thickness: { value: 0 },
  874. thicknessMap: { value: null },
  875. thicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  876. attenuationDistance: { value: 0 },
  877. attenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  878. specularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) },
  879. specularColorMap: { value: null },
  880. specularColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  881. specularIntensity: { value: 1 },
  882. specularIntensityMap: { value: null },
  883. specularIntensityMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  884. anisotropyVector: { value: /*@__PURE__*/ new Vector2() },
  885. anisotropyMap: { value: null },
  886. anisotropyMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  887. }
  888. ] ),
  889. vertexShader: ShaderChunk.meshphysical_vert,
  890. fragmentShader: ShaderChunk.meshphysical_frag
  891. };
  892. const _rgb = { r: 0, b: 0, g: 0 };
  893. const _e1$1 = /*@__PURE__*/ new Euler();
  894. const _m1$1 = /*@__PURE__*/ new Matrix4();
  895. function WebGLBackground( renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha ) {
  896. const clearColor = new Color( 0x000000 );
  897. let clearAlpha = alpha === true ? 0 : 1;
  898. let planeMesh;
  899. let boxMesh;
  900. let currentBackground = null;
  901. let currentBackgroundVersion = 0;
  902. let currentTonemapping = null;
  903. function getBackground( scene ) {
  904. let background = scene.isScene === true ? scene.background : null;
  905. if ( background && background.isTexture ) {
  906. const usePMREM = scene.backgroundBlurriness > 0; // use PMREM if the user wants to blur the background
  907. background = ( usePMREM ? cubeuvmaps : cubemaps ).get( background );
  908. }
  909. return background;
  910. }
  911. function render( scene ) {
  912. let forceClear = false;
  913. const background = getBackground( scene );
  914. if ( background === null ) {
  915. setClear( clearColor, clearAlpha );
  916. } else if ( background && background.isColor ) {
  917. setClear( background, 1 );
  918. forceClear = true;
  919. }
  920. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  921. if ( environmentBlendMode === 'additive' ) {
  922. state.buffers.color.setClear( 0, 0, 0, 1, premultipliedAlpha );
  923. } else if ( environmentBlendMode === 'alpha-blend' ) {
  924. state.buffers.color.setClear( 0, 0, 0, 0, premultipliedAlpha );
  925. }
  926. if ( renderer.autoClear || forceClear ) {
  927. // buffers might not be writable which is required to ensure a correct clear
  928. state.buffers.depth.setTest( true );
  929. state.buffers.depth.setMask( true );
  930. state.buffers.color.setMask( true );
  931. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  932. }
  933. }
  934. function addToRenderList( renderList, scene ) {
  935. const background = getBackground( scene );
  936. if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {
  937. if ( boxMesh === undefined ) {
  938. boxMesh = new Mesh(
  939. new BoxGeometry( 1, 1, 1 ),
  940. new ShaderMaterial( {
  941. name: 'BackgroundCubeMaterial',
  942. uniforms: cloneUniforms( ShaderLib.backgroundCube.uniforms ),
  943. vertexShader: ShaderLib.backgroundCube.vertexShader,
  944. fragmentShader: ShaderLib.backgroundCube.fragmentShader,
  945. side: BackSide,
  946. depthTest: false,
  947. depthWrite: false,
  948. fog: false,
  949. allowOverride: false
  950. } )
  951. );
  952. boxMesh.geometry.deleteAttribute( 'normal' );
  953. boxMesh.geometry.deleteAttribute( 'uv' );
  954. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  955. this.matrixWorld.copyPosition( camera.matrixWorld );
  956. };
  957. // add "envMap" material property so the renderer can evaluate it like for built-in materials
  958. Object.defineProperty( boxMesh.material, 'envMap', {
  959. get: function () {
  960. return this.uniforms.envMap.value;
  961. }
  962. } );
  963. objects.update( boxMesh );
  964. }
  965. _e1$1.copy( scene.backgroundRotation );
  966. // accommodate left-handed frame
  967. _e1$1.x *= -1; _e1$1.y *= -1; _e1$1.z *= -1;
  968. if ( background.isCubeTexture && background.isRenderTargetTexture === false ) {
  969. // environment maps which are not cube render targets or PMREMs follow a different convention
  970. _e1$1.y *= -1;
  971. _e1$1.z *= -1;
  972. }
  973. boxMesh.material.uniforms.envMap.value = background;
  974. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? -1 : 1;
  975. boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness;
  976. boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  977. boxMesh.material.uniforms.backgroundRotation.value.setFromMatrix4( _m1$1.makeRotationFromEuler( _e1$1 ) );
  978. boxMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  979. if ( currentBackground !== background ||
  980. currentBackgroundVersion !== background.version ||
  981. currentTonemapping !== renderer.toneMapping ) {
  982. boxMesh.material.needsUpdate = true;
  983. currentBackground = background;
  984. currentBackgroundVersion = background.version;
  985. currentTonemapping = renderer.toneMapping;
  986. }
  987. boxMesh.layers.enableAll();
  988. // push to the pre-sorted opaque render list
  989. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  990. } else if ( background && background.isTexture ) {
  991. if ( planeMesh === undefined ) {
  992. planeMesh = new Mesh(
  993. new PlaneGeometry( 2, 2 ),
  994. new ShaderMaterial( {
  995. name: 'BackgroundMaterial',
  996. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  997. vertexShader: ShaderLib.background.vertexShader,
  998. fragmentShader: ShaderLib.background.fragmentShader,
  999. side: FrontSide,
  1000. depthTest: false,
  1001. depthWrite: false,
  1002. fog: false,
  1003. allowOverride: false
  1004. } )
  1005. );
  1006. planeMesh.geometry.deleteAttribute( 'normal' );
  1007. // add "map" material property so the renderer can evaluate it like for built-in materials
  1008. Object.defineProperty( planeMesh.material, 'map', {
  1009. get: function () {
  1010. return this.uniforms.t2D.value;
  1011. }
  1012. } );
  1013. objects.update( planeMesh );
  1014. }
  1015. planeMesh.material.uniforms.t2D.value = background;
  1016. planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  1017. planeMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  1018. if ( background.matrixAutoUpdate === true ) {
  1019. background.updateMatrix();
  1020. }
  1021. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  1022. if ( currentBackground !== background ||
  1023. currentBackgroundVersion !== background.version ||
  1024. currentTonemapping !== renderer.toneMapping ) {
  1025. planeMesh.material.needsUpdate = true;
  1026. currentBackground = background;
  1027. currentBackgroundVersion = background.version;
  1028. currentTonemapping = renderer.toneMapping;
  1029. }
  1030. planeMesh.layers.enableAll();
  1031. // push to the pre-sorted opaque render list
  1032. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  1033. }
  1034. }
  1035. function setClear( color, alpha ) {
  1036. color.getRGB( _rgb, getUnlitUniformColorSpace( renderer ) );
  1037. state.buffers.color.setClear( _rgb.r, _rgb.g, _rgb.b, alpha, premultipliedAlpha );
  1038. }
  1039. function dispose() {
  1040. if ( boxMesh !== undefined ) {
  1041. boxMesh.geometry.dispose();
  1042. boxMesh.material.dispose();
  1043. boxMesh = undefined;
  1044. }
  1045. if ( planeMesh !== undefined ) {
  1046. planeMesh.geometry.dispose();
  1047. planeMesh.material.dispose();
  1048. planeMesh = undefined;
  1049. }
  1050. }
  1051. return {
  1052. getClearColor: function () {
  1053. return clearColor;
  1054. },
  1055. setClearColor: function ( color, alpha = 1 ) {
  1056. clearColor.set( color );
  1057. clearAlpha = alpha;
  1058. setClear( clearColor, clearAlpha );
  1059. },
  1060. getClearAlpha: function () {
  1061. return clearAlpha;
  1062. },
  1063. setClearAlpha: function ( alpha ) {
  1064. clearAlpha = alpha;
  1065. setClear( clearColor, clearAlpha );
  1066. },
  1067. render: render,
  1068. addToRenderList: addToRenderList,
  1069. dispose: dispose
  1070. };
  1071. }
  1072. function WebGLBindingStates( gl, attributes ) {
  1073. const maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  1074. const bindingStates = {};
  1075. const defaultState = createBindingState( null );
  1076. let currentState = defaultState;
  1077. let forceUpdate = false;
  1078. function setup( object, material, program, geometry, index ) {
  1079. let updateBuffers = false;
  1080. const state = getBindingState( object, geometry, program, material );
  1081. if ( currentState !== state ) {
  1082. currentState = state;
  1083. bindVertexArrayObject( currentState.object );
  1084. }
  1085. updateBuffers = needsUpdate( object, geometry, program, index );
  1086. if ( updateBuffers ) saveCache( object, geometry, program, index );
  1087. if ( index !== null ) {
  1088. attributes.update( index, gl.ELEMENT_ARRAY_BUFFER );
  1089. }
  1090. if ( updateBuffers || forceUpdate ) {
  1091. forceUpdate = false;
  1092. setupVertexAttributes( object, material, program, geometry );
  1093. if ( index !== null ) {
  1094. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, attributes.get( index ).buffer );
  1095. }
  1096. }
  1097. }
  1098. function createVertexArrayObject() {
  1099. return gl.createVertexArray();
  1100. }
  1101. function bindVertexArrayObject( vao ) {
  1102. return gl.bindVertexArray( vao );
  1103. }
  1104. function deleteVertexArrayObject( vao ) {
  1105. return gl.deleteVertexArray( vao );
  1106. }
  1107. function getBindingState( object, geometry, program, material ) {
  1108. const wireframe = ( material.wireframe === true );
  1109. let objectMap = bindingStates[ geometry.id ];
  1110. if ( objectMap === undefined ) {
  1111. objectMap = {};
  1112. bindingStates[ geometry.id ] = objectMap;
  1113. }
  1114. // Each InstancedMesh requires unique binding states because it contains instanced attributes.
  1115. const objectId = ( object.isInstancedMesh === true ) ? object.id : 0;
  1116. let programMap = objectMap[ objectId ];
  1117. if ( programMap === undefined ) {
  1118. programMap = {};
  1119. objectMap[ objectId ] = programMap;
  1120. }
  1121. let stateMap = programMap[ program.id ];
  1122. if ( stateMap === undefined ) {
  1123. stateMap = {};
  1124. programMap[ program.id ] = stateMap;
  1125. }
  1126. let state = stateMap[ wireframe ];
  1127. if ( state === undefined ) {
  1128. state = createBindingState( createVertexArrayObject() );
  1129. stateMap[ wireframe ] = state;
  1130. }
  1131. return state;
  1132. }
  1133. function createBindingState( vao ) {
  1134. const newAttributes = [];
  1135. const enabledAttributes = [];
  1136. const attributeDivisors = [];
  1137. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  1138. newAttributes[ i ] = 0;
  1139. enabledAttributes[ i ] = 0;
  1140. attributeDivisors[ i ] = 0;
  1141. }
  1142. return {
  1143. // for backward compatibility on non-VAO support browser
  1144. geometry: null,
  1145. program: null,
  1146. wireframe: false,
  1147. newAttributes: newAttributes,
  1148. enabledAttributes: enabledAttributes,
  1149. attributeDivisors: attributeDivisors,
  1150. object: vao,
  1151. attributes: {},
  1152. index: null
  1153. };
  1154. }
  1155. function needsUpdate( object, geometry, program, index ) {
  1156. const cachedAttributes = currentState.attributes;
  1157. const geometryAttributes = geometry.attributes;
  1158. let attributesNum = 0;
  1159. const programAttributes = program.getAttributes();
  1160. for ( const name in programAttributes ) {
  1161. const programAttribute = programAttributes[ name ];
  1162. if ( programAttribute.location >= 0 ) {
  1163. const cachedAttribute = cachedAttributes[ name ];
  1164. let geometryAttribute = geometryAttributes[ name ];
  1165. if ( geometryAttribute === undefined ) {
  1166. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  1167. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  1168. }
  1169. if ( cachedAttribute === undefined ) return true;
  1170. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  1171. if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true;
  1172. attributesNum ++;
  1173. }
  1174. }
  1175. if ( currentState.attributesNum !== attributesNum ) return true;
  1176. if ( currentState.index !== index ) return true;
  1177. return false;
  1178. }
  1179. function saveCache( object, geometry, program, index ) {
  1180. const cache = {};
  1181. const attributes = geometry.attributes;
  1182. let attributesNum = 0;
  1183. const programAttributes = program.getAttributes();
  1184. for ( const name in programAttributes ) {
  1185. const programAttribute = programAttributes[ name ];
  1186. if ( programAttribute.location >= 0 ) {
  1187. let attribute = attributes[ name ];
  1188. if ( attribute === undefined ) {
  1189. if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix;
  1190. if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor;
  1191. }
  1192. const data = {};
  1193. data.attribute = attribute;
  1194. if ( attribute && attribute.data ) {
  1195. data.data = attribute.data;
  1196. }
  1197. cache[ name ] = data;
  1198. attributesNum ++;
  1199. }
  1200. }
  1201. currentState.attributes = cache;
  1202. currentState.attributesNum = attributesNum;
  1203. currentState.index = index;
  1204. }
  1205. function initAttributes() {
  1206. const newAttributes = currentState.newAttributes;
  1207. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  1208. newAttributes[ i ] = 0;
  1209. }
  1210. }
  1211. function enableAttribute( attribute ) {
  1212. enableAttributeAndDivisor( attribute, 0 );
  1213. }
  1214. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  1215. const newAttributes = currentState.newAttributes;
  1216. const enabledAttributes = currentState.enabledAttributes;
  1217. const attributeDivisors = currentState.attributeDivisors;
  1218. newAttributes[ attribute ] = 1;
  1219. if ( enabledAttributes[ attribute ] === 0 ) {
  1220. gl.enableVertexAttribArray( attribute );
  1221. enabledAttributes[ attribute ] = 1;
  1222. }
  1223. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  1224. gl.vertexAttribDivisor( attribute, meshPerAttribute );
  1225. attributeDivisors[ attribute ] = meshPerAttribute;
  1226. }
  1227. }
  1228. function disableUnusedAttributes() {
  1229. const newAttributes = currentState.newAttributes;
  1230. const enabledAttributes = currentState.enabledAttributes;
  1231. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  1232. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  1233. gl.disableVertexAttribArray( i );
  1234. enabledAttributes[ i ] = 0;
  1235. }
  1236. }
  1237. }
  1238. function vertexAttribPointer( index, size, type, normalized, stride, offset, integer ) {
  1239. if ( integer === true ) {
  1240. gl.vertexAttribIPointer( index, size, type, stride, offset );
  1241. } else {
  1242. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  1243. }
  1244. }
  1245. function setupVertexAttributes( object, material, program, geometry ) {
  1246. initAttributes();
  1247. const geometryAttributes = geometry.attributes;
  1248. const programAttributes = program.getAttributes();
  1249. const materialDefaultAttributeValues = material.defaultAttributeValues;
  1250. for ( const name in programAttributes ) {
  1251. const programAttribute = programAttributes[ name ];
  1252. if ( programAttribute.location >= 0 ) {
  1253. let geometryAttribute = geometryAttributes[ name ];
  1254. if ( geometryAttribute === undefined ) {
  1255. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  1256. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  1257. }
  1258. if ( geometryAttribute !== undefined ) {
  1259. const normalized = geometryAttribute.normalized;
  1260. const size = geometryAttribute.itemSize;
  1261. const attribute = attributes.get( geometryAttribute );
  1262. // TODO Attribute may not be available on context restore
  1263. if ( attribute === undefined ) continue;
  1264. const buffer = attribute.buffer;
  1265. const type = attribute.type;
  1266. const bytesPerElement = attribute.bytesPerElement;
  1267. // check for integer attributes
  1268. const integer = ( type === gl.INT || type === gl.UNSIGNED_INT || geometryAttribute.gpuType === IntType );
  1269. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  1270. const data = geometryAttribute.data;
  1271. const stride = data.stride;
  1272. const offset = geometryAttribute.offset;
  1273. if ( data.isInstancedInterleavedBuffer ) {
  1274. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  1275. enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute );
  1276. }
  1277. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  1278. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  1279. }
  1280. } else {
  1281. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  1282. enableAttribute( programAttribute.location + i );
  1283. }
  1284. }
  1285. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  1286. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  1287. vertexAttribPointer(
  1288. programAttribute.location + i,
  1289. size / programAttribute.locationSize,
  1290. type,
  1291. normalized,
  1292. stride * bytesPerElement,
  1293. ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement,
  1294. integer
  1295. );
  1296. }
  1297. } else {
  1298. if ( geometryAttribute.isInstancedBufferAttribute ) {
  1299. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  1300. enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute );
  1301. }
  1302. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  1303. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  1304. }
  1305. } else {
  1306. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  1307. enableAttribute( programAttribute.location + i );
  1308. }
  1309. }
  1310. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  1311. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  1312. vertexAttribPointer(
  1313. programAttribute.location + i,
  1314. size / programAttribute.locationSize,
  1315. type,
  1316. normalized,
  1317. size * bytesPerElement,
  1318. ( size / programAttribute.locationSize ) * i * bytesPerElement,
  1319. integer
  1320. );
  1321. }
  1322. }
  1323. } else if ( materialDefaultAttributeValues !== undefined ) {
  1324. const value = materialDefaultAttributeValues[ name ];
  1325. if ( value !== undefined ) {
  1326. switch ( value.length ) {
  1327. case 2:
  1328. gl.vertexAttrib2fv( programAttribute.location, value );
  1329. break;
  1330. case 3:
  1331. gl.vertexAttrib3fv( programAttribute.location, value );
  1332. break;
  1333. case 4:
  1334. gl.vertexAttrib4fv( programAttribute.location, value );
  1335. break;
  1336. default:
  1337. gl.vertexAttrib1fv( programAttribute.location, value );
  1338. }
  1339. }
  1340. }
  1341. }
  1342. }
  1343. disableUnusedAttributes();
  1344. }
  1345. function dispose() {
  1346. reset();
  1347. for ( const geometryId in bindingStates ) {
  1348. const objectMap = bindingStates[ geometryId ];
  1349. for ( const objectId in objectMap ) {
  1350. const programMap = objectMap[ objectId ];
  1351. for ( const programId in programMap ) {
  1352. const stateMap = programMap[ programId ];
  1353. for ( const wireframe in stateMap ) {
  1354. deleteVertexArrayObject( stateMap[ wireframe ].object );
  1355. delete stateMap[ wireframe ];
  1356. }
  1357. delete programMap[ programId ];
  1358. }
  1359. }
  1360. delete bindingStates[ geometryId ];
  1361. }
  1362. }
  1363. function releaseStatesOfGeometry( geometry ) {
  1364. if ( bindingStates[ geometry.id ] === undefined ) return;
  1365. const objectMap = bindingStates[ geometry.id ];
  1366. for ( const objectId in objectMap ) {
  1367. const programMap = objectMap[ objectId ];
  1368. for ( const programId in programMap ) {
  1369. const stateMap = programMap[ programId ];
  1370. for ( const wireframe in stateMap ) {
  1371. deleteVertexArrayObject( stateMap[ wireframe ].object );
  1372. delete stateMap[ wireframe ];
  1373. }
  1374. delete programMap[ programId ];
  1375. }
  1376. }
  1377. delete bindingStates[ geometry.id ];
  1378. }
  1379. function releaseStatesOfProgram( program ) {
  1380. for ( const geometryId in bindingStates ) {
  1381. const objectMap = bindingStates[ geometryId ];
  1382. for ( const objectId in objectMap ) {
  1383. const programMap = objectMap[ objectId ];
  1384. if ( programMap[ program.id ] === undefined ) continue;
  1385. const stateMap = programMap[ program.id ];
  1386. for ( const wireframe in stateMap ) {
  1387. deleteVertexArrayObject( stateMap[ wireframe ].object );
  1388. delete stateMap[ wireframe ];
  1389. }
  1390. delete programMap[ program.id ];
  1391. }
  1392. }
  1393. }
  1394. function releaseStatesOfObject( object ) {
  1395. for ( const geometryId in bindingStates ) {
  1396. const objectMap = bindingStates[ geometryId ];
  1397. const objectId = ( object.isInstancedMesh === true ) ? object.id : 0;
  1398. const programMap = objectMap[ objectId ];
  1399. if ( programMap === undefined ) continue;
  1400. for ( const programId in programMap ) {
  1401. const stateMap = programMap[ programId ];
  1402. for ( const wireframe in stateMap ) {
  1403. deleteVertexArrayObject( stateMap[ wireframe ].object );
  1404. delete stateMap[ wireframe ];
  1405. }
  1406. delete programMap[ programId ];
  1407. }
  1408. delete objectMap[ objectId ];
  1409. if ( Object.keys( objectMap ).length === 0 ) {
  1410. delete bindingStates[ geometryId ];
  1411. }
  1412. }
  1413. }
  1414. function reset() {
  1415. resetDefaultState();
  1416. forceUpdate = true;
  1417. if ( currentState === defaultState ) return;
  1418. currentState = defaultState;
  1419. bindVertexArrayObject( currentState.object );
  1420. }
  1421. // for backward-compatibility
  1422. function resetDefaultState() {
  1423. defaultState.geometry = null;
  1424. defaultState.program = null;
  1425. defaultState.wireframe = false;
  1426. }
  1427. return {
  1428. setup: setup,
  1429. reset: reset,
  1430. resetDefaultState: resetDefaultState,
  1431. dispose: dispose,
  1432. releaseStatesOfGeometry: releaseStatesOfGeometry,
  1433. releaseStatesOfObject: releaseStatesOfObject,
  1434. releaseStatesOfProgram: releaseStatesOfProgram,
  1435. initAttributes: initAttributes,
  1436. enableAttribute: enableAttribute,
  1437. disableUnusedAttributes: disableUnusedAttributes
  1438. };
  1439. }
  1440. function WebGLBufferRenderer( gl, extensions, info ) {
  1441. let mode;
  1442. function setMode( value ) {
  1443. mode = value;
  1444. }
  1445. function render( start, count ) {
  1446. gl.drawArrays( mode, start, count );
  1447. info.update( count, mode, 1 );
  1448. }
  1449. function renderInstances( start, count, primcount ) {
  1450. if ( primcount === 0 ) return;
  1451. gl.drawArraysInstanced( mode, start, count, primcount );
  1452. info.update( count, mode, primcount );
  1453. }
  1454. function renderMultiDraw( starts, counts, drawCount ) {
  1455. if ( drawCount === 0 ) return;
  1456. const extension = extensions.get( 'WEBGL_multi_draw' );
  1457. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  1458. let elementCount = 0;
  1459. for ( let i = 0; i < drawCount; i ++ ) {
  1460. elementCount += counts[ i ];
  1461. }
  1462. info.update( elementCount, mode, 1 );
  1463. }
  1464. function renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  1465. if ( drawCount === 0 ) return;
  1466. const extension = extensions.get( 'WEBGL_multi_draw' );
  1467. if ( extension === null ) {
  1468. for ( let i = 0; i < starts.length; i ++ ) {
  1469. renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  1470. }
  1471. } else {
  1472. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  1473. let elementCount = 0;
  1474. for ( let i = 0; i < drawCount; i ++ ) {
  1475. elementCount += counts[ i ] * primcount[ i ];
  1476. }
  1477. info.update( elementCount, mode, 1 );
  1478. }
  1479. }
  1480. //
  1481. this.setMode = setMode;
  1482. this.render = render;
  1483. this.renderInstances = renderInstances;
  1484. this.renderMultiDraw = renderMultiDraw;
  1485. this.renderMultiDrawInstances = renderMultiDrawInstances;
  1486. }
  1487. function WebGLCapabilities( gl, extensions, parameters, utils ) {
  1488. let maxAnisotropy;
  1489. function getMaxAnisotropy() {
  1490. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  1491. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  1492. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  1493. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  1494. } else {
  1495. maxAnisotropy = 0;
  1496. }
  1497. return maxAnisotropy;
  1498. }
  1499. function textureFormatReadable( textureFormat ) {
  1500. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  1501. return false;
  1502. }
  1503. return true;
  1504. }
  1505. function textureTypeReadable( textureType ) {
  1506. const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' ) );
  1507. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // Edge and Chrome Mac < 52 (#9513)
  1508. textureType !== FloatType && ! halfFloatSupportedByExt ) {
  1509. return false;
  1510. }
  1511. return true;
  1512. }
  1513. function getMaxPrecision( precision ) {
  1514. if ( precision === 'highp' ) {
  1515. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  1516. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  1517. return 'highp';
  1518. }
  1519. precision = 'mediump';
  1520. }
  1521. if ( precision === 'mediump' ) {
  1522. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  1523. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  1524. return 'mediump';
  1525. }
  1526. }
  1527. return 'lowp';
  1528. }
  1529. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  1530. const maxPrecision = getMaxPrecision( precision );
  1531. if ( maxPrecision !== precision ) {
  1532. warn( 'WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  1533. precision = maxPrecision;
  1534. }
  1535. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  1536. const reversedDepthBuffer = parameters.reversedDepthBuffer === true && extensions.has( 'EXT_clip_control' );
  1537. const maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  1538. const maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  1539. const maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  1540. const maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  1541. const maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  1542. const maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  1543. const maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  1544. const maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  1545. const maxSamples = gl.getParameter( gl.MAX_SAMPLES );
  1546. const samples = gl.getParameter( gl.SAMPLES );
  1547. return {
  1548. isWebGL2: true, // keeping this for backwards compatibility
  1549. getMaxAnisotropy: getMaxAnisotropy,
  1550. getMaxPrecision: getMaxPrecision,
  1551. textureFormatReadable: textureFormatReadable,
  1552. textureTypeReadable: textureTypeReadable,
  1553. precision: precision,
  1554. logarithmicDepthBuffer: logarithmicDepthBuffer,
  1555. reversedDepthBuffer: reversedDepthBuffer,
  1556. maxTextures: maxTextures,
  1557. maxVertexTextures: maxVertexTextures,
  1558. maxTextureSize: maxTextureSize,
  1559. maxCubemapSize: maxCubemapSize,
  1560. maxAttributes: maxAttributes,
  1561. maxVertexUniforms: maxVertexUniforms,
  1562. maxVaryings: maxVaryings,
  1563. maxFragmentUniforms: maxFragmentUniforms,
  1564. maxSamples: maxSamples,
  1565. samples: samples
  1566. };
  1567. }
  1568. function WebGLClipping( properties ) {
  1569. const scope = this;
  1570. let globalState = null,
  1571. numGlobalPlanes = 0,
  1572. localClippingEnabled = false,
  1573. renderingShadows = false;
  1574. const plane = new Plane(),
  1575. viewNormalMatrix = new Matrix3(),
  1576. uniform = { value: null, needsUpdate: false };
  1577. this.uniform = uniform;
  1578. this.numPlanes = 0;
  1579. this.numIntersection = 0;
  1580. this.init = function ( planes, enableLocalClipping ) {
  1581. const enabled =
  1582. planes.length !== 0 ||
  1583. enableLocalClipping ||
  1584. // enable state of previous frame - the clipping code has to
  1585. // run another frame in order to reset the state:
  1586. numGlobalPlanes !== 0 ||
  1587. localClippingEnabled;
  1588. localClippingEnabled = enableLocalClipping;
  1589. numGlobalPlanes = planes.length;
  1590. return enabled;
  1591. };
  1592. this.beginShadows = function () {
  1593. renderingShadows = true;
  1594. projectPlanes( null );
  1595. };
  1596. this.endShadows = function () {
  1597. renderingShadows = false;
  1598. };
  1599. this.setGlobalState = function ( planes, camera ) {
  1600. globalState = projectPlanes( planes, camera, 0 );
  1601. };
  1602. this.setState = function ( material, camera, useCache ) {
  1603. const planes = material.clippingPlanes,
  1604. clipIntersection = material.clipIntersection,
  1605. clipShadows = material.clipShadows;
  1606. const materialProperties = properties.get( material );
  1607. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  1608. // there's no local clipping
  1609. if ( renderingShadows ) {
  1610. // there's no global clipping
  1611. projectPlanes( null );
  1612. } else {
  1613. resetGlobalState();
  1614. }
  1615. } else {
  1616. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  1617. lGlobal = nGlobal * 4;
  1618. let dstArray = materialProperties.clippingState || null;
  1619. uniform.value = dstArray; // ensure unique state
  1620. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  1621. for ( let i = 0; i !== lGlobal; ++ i ) {
  1622. dstArray[ i ] = globalState[ i ];
  1623. }
  1624. materialProperties.clippingState = dstArray;
  1625. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  1626. this.numPlanes += nGlobal;
  1627. }
  1628. };
  1629. function resetGlobalState() {
  1630. if ( uniform.value !== globalState ) {
  1631. uniform.value = globalState;
  1632. uniform.needsUpdate = numGlobalPlanes > 0;
  1633. }
  1634. scope.numPlanes = numGlobalPlanes;
  1635. scope.numIntersection = 0;
  1636. }
  1637. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  1638. const nPlanes = planes !== null ? planes.length : 0;
  1639. let dstArray = null;
  1640. if ( nPlanes !== 0 ) {
  1641. dstArray = uniform.value;
  1642. if ( skipTransform !== true || dstArray === null ) {
  1643. const flatSize = dstOffset + nPlanes * 4,
  1644. viewMatrix = camera.matrixWorldInverse;
  1645. viewNormalMatrix.getNormalMatrix( viewMatrix );
  1646. if ( dstArray === null || dstArray.length < flatSize ) {
  1647. dstArray = new Float32Array( flatSize );
  1648. }
  1649. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  1650. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  1651. plane.normal.toArray( dstArray, i4 );
  1652. dstArray[ i4 + 3 ] = plane.constant;
  1653. }
  1654. }
  1655. uniform.value = dstArray;
  1656. uniform.needsUpdate = true;
  1657. }
  1658. scope.numPlanes = nPlanes;
  1659. scope.numIntersection = 0;
  1660. return dstArray;
  1661. }
  1662. }
  1663. function WebGLCubeMaps( renderer ) {
  1664. let cubemaps = new WeakMap();
  1665. function mapTextureMapping( texture, mapping ) {
  1666. if ( mapping === EquirectangularReflectionMapping ) {
  1667. texture.mapping = CubeReflectionMapping;
  1668. } else if ( mapping === EquirectangularRefractionMapping ) {
  1669. texture.mapping = CubeRefractionMapping;
  1670. }
  1671. return texture;
  1672. }
  1673. function get( texture ) {
  1674. if ( texture && texture.isTexture ) {
  1675. const mapping = texture.mapping;
  1676. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  1677. if ( cubemaps.has( texture ) ) {
  1678. const cubemap = cubemaps.get( texture ).texture;
  1679. return mapTextureMapping( cubemap, texture.mapping );
  1680. } else {
  1681. const image = texture.image;
  1682. if ( image && image.height > 0 ) {
  1683. const renderTarget = new WebGLCubeRenderTarget( image.height );
  1684. renderTarget.fromEquirectangularTexture( renderer, texture );
  1685. cubemaps.set( texture, renderTarget );
  1686. texture.addEventListener( 'dispose', onTextureDispose );
  1687. return mapTextureMapping( renderTarget.texture, texture.mapping );
  1688. } else {
  1689. // image not yet ready. try the conversion next frame
  1690. return null;
  1691. }
  1692. }
  1693. }
  1694. }
  1695. return texture;
  1696. }
  1697. function onTextureDispose( event ) {
  1698. const texture = event.target;
  1699. texture.removeEventListener( 'dispose', onTextureDispose );
  1700. const cubemap = cubemaps.get( texture );
  1701. if ( cubemap !== undefined ) {
  1702. cubemaps.delete( texture );
  1703. cubemap.dispose();
  1704. }
  1705. }
  1706. function dispose() {
  1707. cubemaps = new WeakMap();
  1708. }
  1709. return {
  1710. get: get,
  1711. dispose: dispose
  1712. };
  1713. }
  1714. const LOD_MIN = 4;
  1715. // The standard deviations (radians) associated with the extra mips.
  1716. // Used for scene blur in fromScene() method.
  1717. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  1718. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  1719. // samples and exit early, but not recompile the shader.
  1720. // Used for scene blur in fromScene() method.
  1721. const MAX_SAMPLES = 20;
  1722. // GGX VNDF importance sampling configuration
  1723. const GGX_SAMPLES = 256;
  1724. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  1725. const _clearColor = /*@__PURE__*/ new Color();
  1726. let _oldTarget = null;
  1727. let _oldActiveCubeFace = 0;
  1728. let _oldActiveMipmapLevel = 0;
  1729. let _oldXrEnabled = false;
  1730. const _origin = /*@__PURE__*/ new Vector3();
  1731. /**
  1732. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  1733. * (PMREM) from a cubeMap environment texture. This allows different levels of
  1734. * blur to be quickly accessed based on material roughness. It is packed into a
  1735. * special CubeUV format that allows us to perform custom interpolation so that
  1736. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  1737. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  1738. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  1739. * higher roughness levels. In this way we maintain resolution to smoothly
  1740. * interpolate diffuse lighting while limiting sampling computation.
  1741. *
  1742. * The prefiltering uses GGX VNDF (Visible Normal Distribution Function)
  1743. * importance sampling based on "Sampling the GGX Distribution of Visible Normals"
  1744. * (Heitz, 2018) to generate environment maps that accurately match the GGX BRDF
  1745. * used in material rendering for physically-based image-based lighting.
  1746. */
  1747. class PMREMGenerator {
  1748. /**
  1749. * Constructs a new PMREM generator.
  1750. *
  1751. * @param {WebGLRenderer} renderer - The renderer.
  1752. */
  1753. constructor( renderer ) {
  1754. this._renderer = renderer;
  1755. this._pingPongRenderTarget = null;
  1756. this._lodMax = 0;
  1757. this._cubeSize = 0;
  1758. this._sizeLods = [];
  1759. this._sigmas = [];
  1760. this._lodMeshes = [];
  1761. this._backgroundBox = null;
  1762. this._cubemapMaterial = null;
  1763. this._equirectMaterial = null;
  1764. this._blurMaterial = null;
  1765. this._ggxMaterial = null;
  1766. }
  1767. /**
  1768. * Generates a PMREM from a supplied Scene, which can be faster than using an
  1769. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  1770. * in radians to be applied to the scene before PMREM generation. Optional near
  1771. * and far planes ensure the scene is rendered in its entirety.
  1772. *
  1773. * @param {Scene} scene - The scene to be captured.
  1774. * @param {number} [sigma=0] - The blur radius in radians.
  1775. * @param {number} [near=0.1] - The near plane distance.
  1776. * @param {number} [far=100] - The far plane distance.
  1777. * @param {Object} [options={}] - The configuration options.
  1778. * @param {number} [options.size=256] - The texture size of the PMREM.
  1779. * @param {Vector3} [options.position=origin] - The position of the internal cube camera that renders the scene.
  1780. * @return {WebGLRenderTarget} The resulting PMREM.
  1781. */
  1782. fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  1783. const {
  1784. size = 256,
  1785. position = _origin,
  1786. } = options;
  1787. _oldTarget = this._renderer.getRenderTarget();
  1788. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  1789. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  1790. _oldXrEnabled = this._renderer.xr.enabled;
  1791. this._renderer.xr.enabled = false;
  1792. this._setSize( size );
  1793. const cubeUVRenderTarget = this._allocateTargets();
  1794. cubeUVRenderTarget.depthBuffer = true;
  1795. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position );
  1796. if ( sigma > 0 ) {
  1797. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  1798. }
  1799. this._applyPMREM( cubeUVRenderTarget );
  1800. this._cleanup( cubeUVRenderTarget );
  1801. return cubeUVRenderTarget;
  1802. }
  1803. /**
  1804. * Generates a PMREM from an equirectangular texture, which can be either LDR
  1805. * or HDR. The ideal input image size is 1k (1024 x 512),
  1806. * as this matches best with the 256 x 256 cubemap output.
  1807. *
  1808. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  1809. * @param {?WebGLRenderTarget} [renderTarget=null] - The render target to use.
  1810. * @return {WebGLRenderTarget} The resulting PMREM.
  1811. */
  1812. fromEquirectangular( equirectangular, renderTarget = null ) {
  1813. return this._fromTexture( equirectangular, renderTarget );
  1814. }
  1815. /**
  1816. * Generates a PMREM from an cubemap texture, which can be either LDR
  1817. * or HDR. The ideal input cube size is 256 x 256,
  1818. * as this matches best with the 256 x 256 cubemap output.
  1819. *
  1820. * @param {Texture} cubemap - The cubemap texture to be converted.
  1821. * @param {?WebGLRenderTarget} [renderTarget=null] - The render target to use.
  1822. * @return {WebGLRenderTarget} The resulting PMREM.
  1823. */
  1824. fromCubemap( cubemap, renderTarget = null ) {
  1825. return this._fromTexture( cubemap, renderTarget );
  1826. }
  1827. /**
  1828. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  1829. * your texture's network fetch for increased concurrency.
  1830. */
  1831. compileCubemapShader() {
  1832. if ( this._cubemapMaterial === null ) {
  1833. this._cubemapMaterial = _getCubemapMaterial();
  1834. this._compileMaterial( this._cubemapMaterial );
  1835. }
  1836. }
  1837. /**
  1838. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  1839. * your texture's network fetch for increased concurrency.
  1840. */
  1841. compileEquirectangularShader() {
  1842. if ( this._equirectMaterial === null ) {
  1843. this._equirectMaterial = _getEquirectMaterial();
  1844. this._compileMaterial( this._equirectMaterial );
  1845. }
  1846. }
  1847. /**
  1848. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  1849. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  1850. * one of them will cause any others to also become unusable.
  1851. */
  1852. dispose() {
  1853. this._dispose();
  1854. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  1855. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  1856. if ( this._backgroundBox !== null ) {
  1857. this._backgroundBox.geometry.dispose();
  1858. this._backgroundBox.material.dispose();
  1859. }
  1860. }
  1861. // private interface
  1862. _setSize( cubeSize ) {
  1863. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  1864. this._cubeSize = Math.pow( 2, this._lodMax );
  1865. }
  1866. _dispose() {
  1867. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  1868. if ( this._ggxMaterial !== null ) this._ggxMaterial.dispose();
  1869. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  1870. for ( let i = 0; i < this._lodMeshes.length; i ++ ) {
  1871. this._lodMeshes[ i ].geometry.dispose();
  1872. }
  1873. }
  1874. _cleanup( outputTarget ) {
  1875. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  1876. this._renderer.xr.enabled = _oldXrEnabled;
  1877. outputTarget.scissorTest = false;
  1878. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  1879. }
  1880. _fromTexture( texture, renderTarget ) {
  1881. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  1882. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  1883. } else { // Equirectangular
  1884. this._setSize( texture.image.width / 4 );
  1885. }
  1886. _oldTarget = this._renderer.getRenderTarget();
  1887. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  1888. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  1889. _oldXrEnabled = this._renderer.xr.enabled;
  1890. this._renderer.xr.enabled = false;
  1891. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  1892. this._textureToCubeUV( texture, cubeUVRenderTarget );
  1893. this._applyPMREM( cubeUVRenderTarget );
  1894. this._cleanup( cubeUVRenderTarget );
  1895. return cubeUVRenderTarget;
  1896. }
  1897. _allocateTargets() {
  1898. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  1899. const height = 4 * this._cubeSize;
  1900. const params = {
  1901. magFilter: LinearFilter,
  1902. minFilter: LinearFilter,
  1903. generateMipmaps: false,
  1904. type: HalfFloatType,
  1905. format: RGBAFormat,
  1906. colorSpace: LinearSRGBColorSpace,
  1907. depthBuffer: false
  1908. };
  1909. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  1910. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  1911. if ( this._pingPongRenderTarget !== null ) {
  1912. this._dispose();
  1913. }
  1914. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  1915. const { _lodMax } = this;
  1916. ( { lodMeshes: this._lodMeshes, sizeLods: this._sizeLods, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  1917. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  1918. this._ggxMaterial = _getGGXShader( _lodMax, width, height );
  1919. }
  1920. return cubeUVRenderTarget;
  1921. }
  1922. _compileMaterial( material ) {
  1923. const mesh = new Mesh( new BufferGeometry(), material );
  1924. this._renderer.compile( mesh, _flatCamera );
  1925. }
  1926. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) {
  1927. const fov = 90;
  1928. const aspect = 1;
  1929. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  1930. const upSign = [ 1, -1, 1, 1, 1, 1 ];
  1931. const forwardSign = [ 1, 1, 1, -1, -1, -1 ];
  1932. const renderer = this._renderer;
  1933. const originalAutoClear = renderer.autoClear;
  1934. const toneMapping = renderer.toneMapping;
  1935. renderer.getClearColor( _clearColor );
  1936. renderer.toneMapping = NoToneMapping;
  1937. renderer.autoClear = false;
  1938. // https://github.com/mrdoob/three.js/issues/31413#issuecomment-3095966812
  1939. const reversedDepthBuffer = renderer.state.buffers.depth.getReversed();
  1940. if ( reversedDepthBuffer ) {
  1941. renderer.setRenderTarget( cubeUVRenderTarget );
  1942. renderer.clearDepth();
  1943. renderer.setRenderTarget( null );
  1944. }
  1945. if ( this._backgroundBox === null ) {
  1946. this._backgroundBox = new Mesh(
  1947. new BoxGeometry(),
  1948. new MeshBasicMaterial( {
  1949. name: 'PMREM.Background',
  1950. side: BackSide,
  1951. depthWrite: false,
  1952. depthTest: false,
  1953. } )
  1954. );
  1955. }
  1956. const backgroundBox = this._backgroundBox;
  1957. const backgroundMaterial = backgroundBox.material;
  1958. let useSolidColor = false;
  1959. const background = scene.background;
  1960. if ( background ) {
  1961. if ( background.isColor ) {
  1962. backgroundMaterial.color.copy( background );
  1963. scene.background = null;
  1964. useSolidColor = true;
  1965. }
  1966. } else {
  1967. backgroundMaterial.color.copy( _clearColor );
  1968. useSolidColor = true;
  1969. }
  1970. for ( let i = 0; i < 6; i ++ ) {
  1971. const col = i % 3;
  1972. if ( col === 0 ) {
  1973. cubeCamera.up.set( 0, upSign[ i ], 0 );
  1974. cubeCamera.position.set( position.x, position.y, position.z );
  1975. cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z );
  1976. } else if ( col === 1 ) {
  1977. cubeCamera.up.set( 0, 0, upSign[ i ] );
  1978. cubeCamera.position.set( position.x, position.y, position.z );
  1979. cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z );
  1980. } else {
  1981. cubeCamera.up.set( 0, upSign[ i ], 0 );
  1982. cubeCamera.position.set( position.x, position.y, position.z );
  1983. cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] );
  1984. }
  1985. const size = this._cubeSize;
  1986. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  1987. renderer.setRenderTarget( cubeUVRenderTarget );
  1988. if ( useSolidColor ) {
  1989. renderer.render( backgroundBox, cubeCamera );
  1990. }
  1991. renderer.render( scene, cubeCamera );
  1992. }
  1993. renderer.toneMapping = toneMapping;
  1994. renderer.autoClear = originalAutoClear;
  1995. scene.background = background;
  1996. }
  1997. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  1998. const renderer = this._renderer;
  1999. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  2000. if ( isCubeTexture ) {
  2001. if ( this._cubemapMaterial === null ) {
  2002. this._cubemapMaterial = _getCubemapMaterial();
  2003. }
  2004. this._cubemapMaterial.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? -1 : 1;
  2005. } else {
  2006. if ( this._equirectMaterial === null ) {
  2007. this._equirectMaterial = _getEquirectMaterial();
  2008. }
  2009. }
  2010. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  2011. const mesh = this._lodMeshes[ 0 ];
  2012. mesh.material = material;
  2013. const uniforms = material.uniforms;
  2014. uniforms[ 'envMap' ].value = texture;
  2015. const size = this._cubeSize;
  2016. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  2017. renderer.setRenderTarget( cubeUVRenderTarget );
  2018. renderer.render( mesh, _flatCamera );
  2019. }
  2020. _applyPMREM( cubeUVRenderTarget ) {
  2021. const renderer = this._renderer;
  2022. const autoClear = renderer.autoClear;
  2023. renderer.autoClear = false;
  2024. const n = this._lodMeshes.length;
  2025. // Use GGX VNDF importance sampling
  2026. for ( let i = 1; i < n; i ++ ) {
  2027. this._applyGGXFilter( cubeUVRenderTarget, i - 1, i );
  2028. }
  2029. renderer.autoClear = autoClear;
  2030. }
  2031. /**
  2032. * Applies GGX VNDF importance sampling filter to generate a prefiltered environment map.
  2033. * Uses Monte Carlo integration with VNDF importance sampling to accurately represent the
  2034. * GGX BRDF for physically-based rendering. Reads from the previous LOD level and
  2035. * applies incremental roughness filtering to avoid over-blurring.
  2036. *
  2037. * @private
  2038. * @param {WebGLRenderTarget} cubeUVRenderTarget
  2039. * @param {number} lodIn - Source LOD level to read from
  2040. * @param {number} lodOut - Target LOD level to write to
  2041. */
  2042. _applyGGXFilter( cubeUVRenderTarget, lodIn, lodOut ) {
  2043. const renderer = this._renderer;
  2044. const pingPongRenderTarget = this._pingPongRenderTarget;
  2045. const ggxMaterial = this._ggxMaterial;
  2046. const ggxMesh = this._lodMeshes[ lodOut ];
  2047. ggxMesh.material = ggxMaterial;
  2048. const ggxUniforms = ggxMaterial.uniforms;
  2049. // Calculate incremental roughness between LOD levels
  2050. const targetRoughness = lodOut / ( this._lodMeshes.length - 1 );
  2051. const sourceRoughness = lodIn / ( this._lodMeshes.length - 1 );
  2052. const incrementalRoughness = Math.sqrt( targetRoughness * targetRoughness - sourceRoughness * sourceRoughness );
  2053. // Apply blur strength mapping for better quality across the roughness range
  2054. const blurStrength = 0.0 + targetRoughness * 1.25;
  2055. const adjustedRoughness = incrementalRoughness * blurStrength;
  2056. // Calculate viewport position based on output LOD level
  2057. const { _lodMax } = this;
  2058. const outputSize = this._sizeLods[ lodOut ];
  2059. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  2060. const y = 4 * ( this._cubeSize - outputSize );
  2061. // Read from previous LOD with incremental roughness
  2062. ggxUniforms[ 'envMap' ].value = cubeUVRenderTarget.texture;
  2063. ggxUniforms[ 'roughness' ].value = adjustedRoughness;
  2064. ggxUniforms[ 'mipInt' ].value = _lodMax - lodIn; // Sample from input LOD
  2065. _setViewport( pingPongRenderTarget, x, y, 3 * outputSize, 2 * outputSize );
  2066. renderer.setRenderTarget( pingPongRenderTarget );
  2067. renderer.render( ggxMesh, _flatCamera );
  2068. // Copy from pingPong back to cubeUV (simple direct copy)
  2069. ggxUniforms[ 'envMap' ].value = pingPongRenderTarget.texture;
  2070. ggxUniforms[ 'roughness' ].value = 0.0; // Direct copy
  2071. ggxUniforms[ 'mipInt' ].value = _lodMax - lodOut; // Read from the level we just wrote
  2072. _setViewport( cubeUVRenderTarget, x, y, 3 * outputSize, 2 * outputSize );
  2073. renderer.setRenderTarget( cubeUVRenderTarget );
  2074. renderer.render( ggxMesh, _flatCamera );
  2075. }
  2076. /**
  2077. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  2078. * vertically and horizontally, but this breaks down on a cube. Here we apply
  2079. * the blur latitudinally (around the poles), and then longitudinally (towards
  2080. * the poles) to approximate the orthogonally-separable blur. It is least
  2081. * accurate at the poles, but still does a decent job.
  2082. *
  2083. * Used for initial scene blur in fromScene() method when sigma > 0.
  2084. *
  2085. * @private
  2086. * @param {WebGLRenderTarget} cubeUVRenderTarget
  2087. * @param {number} lodIn
  2088. * @param {number} lodOut
  2089. * @param {number} sigma
  2090. * @param {Vector3} [poleAxis]
  2091. */
  2092. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  2093. const pingPongRenderTarget = this._pingPongRenderTarget;
  2094. this._halfBlur(
  2095. cubeUVRenderTarget,
  2096. pingPongRenderTarget,
  2097. lodIn,
  2098. lodOut,
  2099. sigma,
  2100. 'latitudinal',
  2101. poleAxis );
  2102. this._halfBlur(
  2103. pingPongRenderTarget,
  2104. cubeUVRenderTarget,
  2105. lodOut,
  2106. lodOut,
  2107. sigma,
  2108. 'longitudinal',
  2109. poleAxis );
  2110. }
  2111. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  2112. const renderer = this._renderer;
  2113. const blurMaterial = this._blurMaterial;
  2114. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  2115. error(
  2116. 'blur direction must be either latitudinal or longitudinal!' );
  2117. }
  2118. // Number of standard deviations at which to cut off the discrete approximation.
  2119. const STANDARD_DEVIATIONS = 3;
  2120. const blurMesh = this._lodMeshes[ lodOut ];
  2121. blurMesh.material = blurMaterial;
  2122. const blurUniforms = blurMaterial.uniforms;
  2123. const pixels = this._sizeLods[ lodIn ] - 1;
  2124. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  2125. const sigmaPixels = sigmaRadians / radiansPerPixel;
  2126. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  2127. if ( samples > MAX_SAMPLES ) {
  2128. warn( `sigmaRadians, ${
  2129. sigmaRadians}, is too large and will clip, as it requested ${
  2130. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  2131. }
  2132. const weights = [];
  2133. let sum = 0;
  2134. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  2135. const x = i / sigmaPixels;
  2136. const weight = Math.exp( - x * x / 2 );
  2137. weights.push( weight );
  2138. if ( i === 0 ) {
  2139. sum += weight;
  2140. } else if ( i < samples ) {
  2141. sum += 2 * weight;
  2142. }
  2143. }
  2144. for ( let i = 0; i < weights.length; i ++ ) {
  2145. weights[ i ] = weights[ i ] / sum;
  2146. }
  2147. blurUniforms[ 'envMap' ].value = targetIn.texture;
  2148. blurUniforms[ 'samples' ].value = samples;
  2149. blurUniforms[ 'weights' ].value = weights;
  2150. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  2151. if ( poleAxis ) {
  2152. blurUniforms[ 'poleAxis' ].value = poleAxis;
  2153. }
  2154. const { _lodMax } = this;
  2155. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  2156. blurUniforms[ 'mipInt' ].value = _lodMax - lodIn;
  2157. const outputSize = this._sizeLods[ lodOut ];
  2158. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  2159. const y = 4 * ( this._cubeSize - outputSize );
  2160. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  2161. renderer.setRenderTarget( targetOut );
  2162. renderer.render( blurMesh, _flatCamera );
  2163. }
  2164. }
  2165. function _createPlanes( lodMax ) {
  2166. const sizeLods = [];
  2167. const sigmas = [];
  2168. const lodMeshes = [];
  2169. let lod = lodMax;
  2170. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  2171. for ( let i = 0; i < totalLods; i ++ ) {
  2172. const sizeLod = Math.pow( 2, lod );
  2173. sizeLods.push( sizeLod );
  2174. let sigma = 1.0 / sizeLod;
  2175. if ( i > lodMax - LOD_MIN ) {
  2176. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  2177. } else if ( i === 0 ) {
  2178. sigma = 0;
  2179. }
  2180. sigmas.push( sigma );
  2181. const texelSize = 1.0 / ( sizeLod - 2 );
  2182. const min = - texelSize;
  2183. const max = 1 + texelSize;
  2184. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  2185. const cubeFaces = 6;
  2186. const vertices = 6;
  2187. const positionSize = 3;
  2188. const uvSize = 2;
  2189. const faceIndexSize = 1;
  2190. const position = new Float32Array( positionSize * vertices * cubeFaces );
  2191. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  2192. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  2193. for ( let face = 0; face < cubeFaces; face ++ ) {
  2194. const x = ( face % 3 ) * 2 / 3 - 1;
  2195. const y = face > 2 ? 0 : -1;
  2196. const coordinates = [
  2197. x, y, 0,
  2198. x + 2 / 3, y, 0,
  2199. x + 2 / 3, y + 1, 0,
  2200. x, y, 0,
  2201. x + 2 / 3, y + 1, 0,
  2202. x, y + 1, 0
  2203. ];
  2204. position.set( coordinates, positionSize * vertices * face );
  2205. uv.set( uv1, uvSize * vertices * face );
  2206. const fill = [ face, face, face, face, face, face ];
  2207. faceIndex.set( fill, faceIndexSize * vertices * face );
  2208. }
  2209. const planes = new BufferGeometry();
  2210. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  2211. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  2212. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  2213. lodMeshes.push( new Mesh( planes, null ) );
  2214. if ( lod > LOD_MIN ) {
  2215. lod --;
  2216. }
  2217. }
  2218. return { lodMeshes, sizeLods, sigmas };
  2219. }
  2220. function _createRenderTarget( width, height, params ) {
  2221. const cubeUVRenderTarget = new WebGLRenderTarget( width, height, params );
  2222. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  2223. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  2224. cubeUVRenderTarget.scissorTest = true;
  2225. return cubeUVRenderTarget;
  2226. }
  2227. function _setViewport( target, x, y, width, height ) {
  2228. target.viewport.set( x, y, width, height );
  2229. target.scissor.set( x, y, width, height );
  2230. }
  2231. function _getGGXShader( lodMax, width, height ) {
  2232. const shaderMaterial = new ShaderMaterial( {
  2233. name: 'PMREMGGXConvolution',
  2234. defines: {
  2235. 'GGX_SAMPLES': GGX_SAMPLES,
  2236. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  2237. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  2238. 'CUBEUV_MAX_MIP': `${lodMax}.0`,
  2239. },
  2240. uniforms: {
  2241. 'envMap': { value: null },
  2242. 'roughness': { value: 0.0 },
  2243. 'mipInt': { value: 0 }
  2244. },
  2245. vertexShader: _getCommonVertexShader(),
  2246. fragmentShader: /* glsl */`
  2247. precision highp float;
  2248. precision highp int;
  2249. varying vec3 vOutputDirection;
  2250. uniform sampler2D envMap;
  2251. uniform float roughness;
  2252. uniform float mipInt;
  2253. #define ENVMAP_TYPE_CUBE_UV
  2254. #include <cube_uv_reflection_fragment>
  2255. #define PI 3.14159265359
  2256. // Van der Corput radical inverse
  2257. float radicalInverse_VdC(uint bits) {
  2258. bits = (bits << 16u) | (bits >> 16u);
  2259. bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u);
  2260. bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u);
  2261. bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u);
  2262. bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u);
  2263. return float(bits) * 2.3283064365386963e-10; // / 0x100000000
  2264. }
  2265. // Hammersley sequence
  2266. vec2 hammersley(uint i, uint N) {
  2267. return vec2(float(i) / float(N), radicalInverse_VdC(i));
  2268. }
  2269. // GGX VNDF importance sampling (Eric Heitz 2018)
  2270. // "Sampling the GGX Distribution of Visible Normals"
  2271. // https://jcgt.org/published/0007/04/01/
  2272. vec3 importanceSampleGGX_VNDF(vec2 Xi, vec3 V, float roughness) {
  2273. float alpha = roughness * roughness;
  2274. // Section 3.2: Transform view direction to hemisphere configuration
  2275. vec3 Vh = normalize(vec3(alpha * V.x, alpha * V.y, V.z));
  2276. // Section 4.1: Orthonormal basis
  2277. float lensq = Vh.x * Vh.x + Vh.y * Vh.y;
  2278. vec3 T1 = lensq > 0.0 ? vec3(-Vh.y, Vh.x, 0.0) / sqrt(lensq) : vec3(1.0, 0.0, 0.0);
  2279. vec3 T2 = cross(Vh, T1);
  2280. // Section 4.2: Parameterization of projected area
  2281. float r = sqrt(Xi.x);
  2282. float phi = 2.0 * PI * Xi.y;
  2283. float t1 = r * cos(phi);
  2284. float t2 = r * sin(phi);
  2285. float s = 0.5 * (1.0 + Vh.z);
  2286. t2 = (1.0 - s) * sqrt(1.0 - t1 * t1) + s * t2;
  2287. // Section 4.3: Reprojection onto hemisphere
  2288. vec3 Nh = t1 * T1 + t2 * T2 + sqrt(max(0.0, 1.0 - t1 * t1 - t2 * t2)) * Vh;
  2289. // Section 3.4: Transform back to ellipsoid configuration
  2290. return normalize(vec3(alpha * Nh.x, alpha * Nh.y, max(0.0, Nh.z)));
  2291. }
  2292. void main() {
  2293. vec3 N = normalize(vOutputDirection);
  2294. vec3 V = N; // Assume view direction equals normal for pre-filtering
  2295. vec3 prefilteredColor = vec3(0.0);
  2296. float totalWeight = 0.0;
  2297. // For very low roughness, just sample the environment directly
  2298. if (roughness < 0.001) {
  2299. gl_FragColor = vec4(bilinearCubeUV(envMap, N, mipInt), 1.0);
  2300. return;
  2301. }
  2302. // Tangent space basis for VNDF sampling
  2303. vec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0);
  2304. vec3 tangent = normalize(cross(up, N));
  2305. vec3 bitangent = cross(N, tangent);
  2306. for(uint i = 0u; i < uint(GGX_SAMPLES); i++) {
  2307. vec2 Xi = hammersley(i, uint(GGX_SAMPLES));
  2308. // For PMREM, V = N, so in tangent space V is always (0, 0, 1)
  2309. vec3 H_tangent = importanceSampleGGX_VNDF(Xi, vec3(0.0, 0.0, 1.0), roughness);
  2310. // Transform H back to world space
  2311. vec3 H = normalize(tangent * H_tangent.x + bitangent * H_tangent.y + N * H_tangent.z);
  2312. vec3 L = normalize(2.0 * dot(V, H) * H - V);
  2313. float NdotL = max(dot(N, L), 0.0);
  2314. if(NdotL > 0.0) {
  2315. // Sample environment at fixed mip level
  2316. // VNDF importance sampling handles the distribution filtering
  2317. vec3 sampleColor = bilinearCubeUV(envMap, L, mipInt);
  2318. // Weight by NdotL for the split-sum approximation
  2319. // VNDF PDF naturally accounts for the visible microfacet distribution
  2320. prefilteredColor += sampleColor * NdotL;
  2321. totalWeight += NdotL;
  2322. }
  2323. }
  2324. if (totalWeight > 0.0) {
  2325. prefilteredColor = prefilteredColor / totalWeight;
  2326. }
  2327. gl_FragColor = vec4(prefilteredColor, 1.0);
  2328. }
  2329. `,
  2330. blending: NoBlending,
  2331. depthTest: false,
  2332. depthWrite: false
  2333. } );
  2334. return shaderMaterial;
  2335. }
  2336. function _getBlurShader( lodMax, width, height ) {
  2337. const weights = new Float32Array( MAX_SAMPLES );
  2338. const poleAxis = new Vector3( 0, 1, 0 );
  2339. const shaderMaterial = new ShaderMaterial( {
  2340. name: 'SphericalGaussianBlur',
  2341. defines: {
  2342. 'n': MAX_SAMPLES,
  2343. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  2344. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  2345. 'CUBEUV_MAX_MIP': `${lodMax}.0`,
  2346. },
  2347. uniforms: {
  2348. 'envMap': { value: null },
  2349. 'samples': { value: 1 },
  2350. 'weights': { value: weights },
  2351. 'latitudinal': { value: false },
  2352. 'dTheta': { value: 0 },
  2353. 'mipInt': { value: 0 },
  2354. 'poleAxis': { value: poleAxis }
  2355. },
  2356. vertexShader: _getCommonVertexShader(),
  2357. fragmentShader: /* glsl */`
  2358. precision mediump float;
  2359. precision mediump int;
  2360. varying vec3 vOutputDirection;
  2361. uniform sampler2D envMap;
  2362. uniform int samples;
  2363. uniform float weights[ n ];
  2364. uniform bool latitudinal;
  2365. uniform float dTheta;
  2366. uniform float mipInt;
  2367. uniform vec3 poleAxis;
  2368. #define ENVMAP_TYPE_CUBE_UV
  2369. #include <cube_uv_reflection_fragment>
  2370. vec3 getSample( float theta, vec3 axis ) {
  2371. float cosTheta = cos( theta );
  2372. // Rodrigues' axis-angle rotation
  2373. vec3 sampleDirection = vOutputDirection * cosTheta
  2374. + cross( axis, vOutputDirection ) * sin( theta )
  2375. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  2376. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  2377. }
  2378. void main() {
  2379. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  2380. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  2381. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  2382. }
  2383. axis = normalize( axis );
  2384. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  2385. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  2386. for ( int i = 1; i < n; i++ ) {
  2387. if ( i >= samples ) {
  2388. break;
  2389. }
  2390. float theta = dTheta * float( i );
  2391. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  2392. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  2393. }
  2394. }
  2395. `,
  2396. blending: NoBlending,
  2397. depthTest: false,
  2398. depthWrite: false
  2399. } );
  2400. return shaderMaterial;
  2401. }
  2402. function _getEquirectMaterial() {
  2403. return new ShaderMaterial( {
  2404. name: 'EquirectangularToCubeUV',
  2405. uniforms: {
  2406. 'envMap': { value: null }
  2407. },
  2408. vertexShader: _getCommonVertexShader(),
  2409. fragmentShader: /* glsl */`
  2410. precision mediump float;
  2411. precision mediump int;
  2412. varying vec3 vOutputDirection;
  2413. uniform sampler2D envMap;
  2414. #include <common>
  2415. void main() {
  2416. vec3 outputDirection = normalize( vOutputDirection );
  2417. vec2 uv = equirectUv( outputDirection );
  2418. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  2419. }
  2420. `,
  2421. blending: NoBlending,
  2422. depthTest: false,
  2423. depthWrite: false
  2424. } );
  2425. }
  2426. function _getCubemapMaterial() {
  2427. return new ShaderMaterial( {
  2428. name: 'CubemapToCubeUV',
  2429. uniforms: {
  2430. 'envMap': { value: null },
  2431. 'flipEnvMap': { value: -1 }
  2432. },
  2433. vertexShader: _getCommonVertexShader(),
  2434. fragmentShader: /* glsl */`
  2435. precision mediump float;
  2436. precision mediump int;
  2437. uniform float flipEnvMap;
  2438. varying vec3 vOutputDirection;
  2439. uniform samplerCube envMap;
  2440. void main() {
  2441. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  2442. }
  2443. `,
  2444. blending: NoBlending,
  2445. depthTest: false,
  2446. depthWrite: false
  2447. } );
  2448. }
  2449. function _getCommonVertexShader() {
  2450. return /* glsl */`
  2451. precision mediump float;
  2452. precision mediump int;
  2453. attribute float faceIndex;
  2454. varying vec3 vOutputDirection;
  2455. // RH coordinate system; PMREM face-indexing convention
  2456. vec3 getDirection( vec2 uv, float face ) {
  2457. uv = 2.0 * uv - 1.0;
  2458. vec3 direction = vec3( uv, 1.0 );
  2459. if ( face == 0.0 ) {
  2460. direction = direction.zyx; // ( 1, v, u ) pos x
  2461. } else if ( face == 1.0 ) {
  2462. direction = direction.xzy;
  2463. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  2464. } else if ( face == 2.0 ) {
  2465. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  2466. } else if ( face == 3.0 ) {
  2467. direction = direction.zyx;
  2468. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  2469. } else if ( face == 4.0 ) {
  2470. direction = direction.xzy;
  2471. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  2472. } else if ( face == 5.0 ) {
  2473. direction.z *= -1.0; // ( u, v, -1 ) neg z
  2474. }
  2475. return direction;
  2476. }
  2477. void main() {
  2478. vOutputDirection = getDirection( uv, faceIndex );
  2479. gl_Position = vec4( position, 1.0 );
  2480. }
  2481. `;
  2482. }
  2483. function WebGLCubeUVMaps( renderer ) {
  2484. let cubeUVmaps = new WeakMap();
  2485. let pmremGenerator = null;
  2486. function get( texture ) {
  2487. if ( texture && texture.isTexture ) {
  2488. const mapping = texture.mapping;
  2489. const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );
  2490. const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  2491. // equirect/cube map to cubeUV conversion
  2492. if ( isEquirectMap || isCubeMap ) {
  2493. let renderTarget = cubeUVmaps.get( texture );
  2494. const currentPMREMVersion = renderTarget !== undefined ? renderTarget.texture.pmremVersion : 0;
  2495. if ( texture.isRenderTargetTexture && texture.pmremVersion !== currentPMREMVersion ) {
  2496. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  2497. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget );
  2498. renderTarget.texture.pmremVersion = texture.pmremVersion;
  2499. cubeUVmaps.set( texture, renderTarget );
  2500. return renderTarget.texture;
  2501. } else {
  2502. if ( renderTarget !== undefined ) {
  2503. return renderTarget.texture;
  2504. } else {
  2505. const image = texture.image;
  2506. if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {
  2507. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  2508. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );
  2509. renderTarget.texture.pmremVersion = texture.pmremVersion;
  2510. cubeUVmaps.set( texture, renderTarget );
  2511. texture.addEventListener( 'dispose', onTextureDispose );
  2512. return renderTarget.texture;
  2513. } else {
  2514. // image not yet ready. try the conversion next frame
  2515. return null;
  2516. }
  2517. }
  2518. }
  2519. }
  2520. }
  2521. return texture;
  2522. }
  2523. function isCubeTextureComplete( image ) {
  2524. let count = 0;
  2525. const length = 6;
  2526. for ( let i = 0; i < length; i ++ ) {
  2527. if ( image[ i ] !== undefined ) count ++;
  2528. }
  2529. return count === length;
  2530. }
  2531. function onTextureDispose( event ) {
  2532. const texture = event.target;
  2533. texture.removeEventListener( 'dispose', onTextureDispose );
  2534. const cubemapUV = cubeUVmaps.get( texture );
  2535. if ( cubemapUV !== undefined ) {
  2536. cubeUVmaps.delete( texture );
  2537. cubemapUV.dispose();
  2538. }
  2539. }
  2540. function dispose() {
  2541. cubeUVmaps = new WeakMap();
  2542. if ( pmremGenerator !== null ) {
  2543. pmremGenerator.dispose();
  2544. pmremGenerator = null;
  2545. }
  2546. }
  2547. return {
  2548. get: get,
  2549. dispose: dispose
  2550. };
  2551. }
  2552. function WebGLExtensions( gl ) {
  2553. const extensions = {};
  2554. function getExtension( name ) {
  2555. if ( extensions[ name ] !== undefined ) {
  2556. return extensions[ name ];
  2557. }
  2558. const extension = gl.getExtension( name );
  2559. extensions[ name ] = extension;
  2560. return extension;
  2561. }
  2562. return {
  2563. has: function ( name ) {
  2564. return getExtension( name ) !== null;
  2565. },
  2566. init: function () {
  2567. getExtension( 'EXT_color_buffer_float' );
  2568. getExtension( 'WEBGL_clip_cull_distance' );
  2569. getExtension( 'OES_texture_float_linear' );
  2570. getExtension( 'EXT_color_buffer_half_float' );
  2571. getExtension( 'WEBGL_multisampled_render_to_texture' );
  2572. getExtension( 'WEBGL_render_shared_exponent' );
  2573. },
  2574. get: function ( name ) {
  2575. const extension = getExtension( name );
  2576. if ( extension === null ) {
  2577. warnOnce( 'WebGLRenderer: ' + name + ' extension not supported.' );
  2578. }
  2579. return extension;
  2580. }
  2581. };
  2582. }
  2583. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  2584. const geometries = {};
  2585. const wireframeAttributes = new WeakMap();
  2586. function onGeometryDispose( event ) {
  2587. const geometry = event.target;
  2588. if ( geometry.index !== null ) {
  2589. attributes.remove( geometry.index );
  2590. }
  2591. for ( const name in geometry.attributes ) {
  2592. attributes.remove( geometry.attributes[ name ] );
  2593. }
  2594. geometry.removeEventListener( 'dispose', onGeometryDispose );
  2595. delete geometries[ geometry.id ];
  2596. const attribute = wireframeAttributes.get( geometry );
  2597. if ( attribute ) {
  2598. attributes.remove( attribute );
  2599. wireframeAttributes.delete( geometry );
  2600. }
  2601. bindingStates.releaseStatesOfGeometry( geometry );
  2602. if ( geometry.isInstancedBufferGeometry === true ) {
  2603. delete geometry._maxInstanceCount;
  2604. }
  2605. //
  2606. info.memory.geometries --;
  2607. }
  2608. function get( object, geometry ) {
  2609. if ( geometries[ geometry.id ] === true ) return geometry;
  2610. geometry.addEventListener( 'dispose', onGeometryDispose );
  2611. geometries[ geometry.id ] = true;
  2612. info.memory.geometries ++;
  2613. return geometry;
  2614. }
  2615. function update( geometry ) {
  2616. const geometryAttributes = geometry.attributes;
  2617. // Updating index buffer in VAO now. See WebGLBindingStates.
  2618. for ( const name in geometryAttributes ) {
  2619. attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER );
  2620. }
  2621. }
  2622. function updateWireframeAttribute( geometry ) {
  2623. const indices = [];
  2624. const geometryIndex = geometry.index;
  2625. const geometryPosition = geometry.attributes.position;
  2626. let version = 0;
  2627. if ( geometryIndex !== null ) {
  2628. const array = geometryIndex.array;
  2629. version = geometryIndex.version;
  2630. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  2631. const a = array[ i + 0 ];
  2632. const b = array[ i + 1 ];
  2633. const c = array[ i + 2 ];
  2634. indices.push( a, b, b, c, c, a );
  2635. }
  2636. } else if ( geometryPosition !== undefined ) {
  2637. const array = geometryPosition.array;
  2638. version = geometryPosition.version;
  2639. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  2640. const a = i + 0;
  2641. const b = i + 1;
  2642. const c = i + 2;
  2643. indices.push( a, b, b, c, c, a );
  2644. }
  2645. } else {
  2646. return;
  2647. }
  2648. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  2649. attribute.version = version;
  2650. // Updating index buffer in VAO now. See WebGLBindingStates
  2651. //
  2652. const previousAttribute = wireframeAttributes.get( geometry );
  2653. if ( previousAttribute ) attributes.remove( previousAttribute );
  2654. //
  2655. wireframeAttributes.set( geometry, attribute );
  2656. }
  2657. function getWireframeAttribute( geometry ) {
  2658. const currentAttribute = wireframeAttributes.get( geometry );
  2659. if ( currentAttribute ) {
  2660. const geometryIndex = geometry.index;
  2661. if ( geometryIndex !== null ) {
  2662. // if the attribute is obsolete, create a new one
  2663. if ( currentAttribute.version < geometryIndex.version ) {
  2664. updateWireframeAttribute( geometry );
  2665. }
  2666. }
  2667. } else {
  2668. updateWireframeAttribute( geometry );
  2669. }
  2670. return wireframeAttributes.get( geometry );
  2671. }
  2672. return {
  2673. get: get,
  2674. update: update,
  2675. getWireframeAttribute: getWireframeAttribute
  2676. };
  2677. }
  2678. function WebGLIndexedBufferRenderer( gl, extensions, info ) {
  2679. let mode;
  2680. function setMode( value ) {
  2681. mode = value;
  2682. }
  2683. let type, bytesPerElement;
  2684. function setIndex( value ) {
  2685. type = value.type;
  2686. bytesPerElement = value.bytesPerElement;
  2687. }
  2688. function render( start, count ) {
  2689. gl.drawElements( mode, count, type, start * bytesPerElement );
  2690. info.update( count, mode, 1 );
  2691. }
  2692. function renderInstances( start, count, primcount ) {
  2693. if ( primcount === 0 ) return;
  2694. gl.drawElementsInstanced( mode, count, type, start * bytesPerElement, primcount );
  2695. info.update( count, mode, primcount );
  2696. }
  2697. function renderMultiDraw( starts, counts, drawCount ) {
  2698. if ( drawCount === 0 ) return;
  2699. const extension = extensions.get( 'WEBGL_multi_draw' );
  2700. extension.multiDrawElementsWEBGL( mode, counts, 0, type, starts, 0, drawCount );
  2701. let elementCount = 0;
  2702. for ( let i = 0; i < drawCount; i ++ ) {
  2703. elementCount += counts[ i ];
  2704. }
  2705. info.update( elementCount, mode, 1 );
  2706. }
  2707. function renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  2708. if ( drawCount === 0 ) return;
  2709. const extension = extensions.get( 'WEBGL_multi_draw' );
  2710. if ( extension === null ) {
  2711. for ( let i = 0; i < starts.length; i ++ ) {
  2712. renderInstances( starts[ i ] / bytesPerElement, counts[ i ], primcount[ i ] );
  2713. }
  2714. } else {
  2715. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, type, starts, 0, primcount, 0, drawCount );
  2716. let elementCount = 0;
  2717. for ( let i = 0; i < drawCount; i ++ ) {
  2718. elementCount += counts[ i ] * primcount[ i ];
  2719. }
  2720. info.update( elementCount, mode, 1 );
  2721. }
  2722. }
  2723. //
  2724. this.setMode = setMode;
  2725. this.setIndex = setIndex;
  2726. this.render = render;
  2727. this.renderInstances = renderInstances;
  2728. this.renderMultiDraw = renderMultiDraw;
  2729. this.renderMultiDrawInstances = renderMultiDrawInstances;
  2730. }
  2731. function WebGLInfo( gl ) {
  2732. const memory = {
  2733. geometries: 0,
  2734. textures: 0
  2735. };
  2736. const render = {
  2737. frame: 0,
  2738. calls: 0,
  2739. triangles: 0,
  2740. points: 0,
  2741. lines: 0
  2742. };
  2743. function update( count, mode, instanceCount ) {
  2744. render.calls ++;
  2745. switch ( mode ) {
  2746. case gl.TRIANGLES:
  2747. render.triangles += instanceCount * ( count / 3 );
  2748. break;
  2749. case gl.LINES:
  2750. render.lines += instanceCount * ( count / 2 );
  2751. break;
  2752. case gl.LINE_STRIP:
  2753. render.lines += instanceCount * ( count - 1 );
  2754. break;
  2755. case gl.LINE_LOOP:
  2756. render.lines += instanceCount * count;
  2757. break;
  2758. case gl.POINTS:
  2759. render.points += instanceCount * count;
  2760. break;
  2761. default:
  2762. error( 'WebGLInfo: Unknown draw mode:', mode );
  2763. break;
  2764. }
  2765. }
  2766. function reset() {
  2767. render.calls = 0;
  2768. render.triangles = 0;
  2769. render.points = 0;
  2770. render.lines = 0;
  2771. }
  2772. return {
  2773. memory: memory,
  2774. render: render,
  2775. programs: null,
  2776. autoReset: true,
  2777. reset: reset,
  2778. update: update
  2779. };
  2780. }
  2781. function WebGLMorphtargets( gl, capabilities, textures ) {
  2782. const morphTextures = new WeakMap();
  2783. const morph = new Vector4();
  2784. function update( object, geometry, program ) {
  2785. const objectInfluences = object.morphTargetInfluences;
  2786. // the following encodes morph targets into an array of data textures. Each layer represents a single morph target.
  2787. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  2788. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  2789. let entry = morphTextures.get( geometry );
  2790. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  2791. if ( entry !== undefined ) entry.texture.dispose();
  2792. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  2793. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  2794. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  2795. const morphTargets = geometry.morphAttributes.position || [];
  2796. const morphNormals = geometry.morphAttributes.normal || [];
  2797. const morphColors = geometry.morphAttributes.color || [];
  2798. let vertexDataCount = 0;
  2799. if ( hasMorphPosition === true ) vertexDataCount = 1;
  2800. if ( hasMorphNormals === true ) vertexDataCount = 2;
  2801. if ( hasMorphColors === true ) vertexDataCount = 3;
  2802. let width = geometry.attributes.position.count * vertexDataCount;
  2803. let height = 1;
  2804. if ( width > capabilities.maxTextureSize ) {
  2805. height = Math.ceil( width / capabilities.maxTextureSize );
  2806. width = capabilities.maxTextureSize;
  2807. }
  2808. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  2809. const texture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  2810. texture.type = FloatType;
  2811. texture.needsUpdate = true;
  2812. // fill buffer
  2813. const vertexDataStride = vertexDataCount * 4;
  2814. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  2815. const morphTarget = morphTargets[ i ];
  2816. const morphNormal = morphNormals[ i ];
  2817. const morphColor = morphColors[ i ];
  2818. const offset = width * height * 4 * i;
  2819. for ( let j = 0; j < morphTarget.count; j ++ ) {
  2820. const stride = j * vertexDataStride;
  2821. if ( hasMorphPosition === true ) {
  2822. morph.fromBufferAttribute( morphTarget, j );
  2823. buffer[ offset + stride + 0 ] = morph.x;
  2824. buffer[ offset + stride + 1 ] = morph.y;
  2825. buffer[ offset + stride + 2 ] = morph.z;
  2826. buffer[ offset + stride + 3 ] = 0;
  2827. }
  2828. if ( hasMorphNormals === true ) {
  2829. morph.fromBufferAttribute( morphNormal, j );
  2830. buffer[ offset + stride + 4 ] = morph.x;
  2831. buffer[ offset + stride + 5 ] = morph.y;
  2832. buffer[ offset + stride + 6 ] = morph.z;
  2833. buffer[ offset + stride + 7 ] = 0;
  2834. }
  2835. if ( hasMorphColors === true ) {
  2836. morph.fromBufferAttribute( morphColor, j );
  2837. buffer[ offset + stride + 8 ] = morph.x;
  2838. buffer[ offset + stride + 9 ] = morph.y;
  2839. buffer[ offset + stride + 10 ] = morph.z;
  2840. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morph.w : 1;
  2841. }
  2842. }
  2843. }
  2844. entry = {
  2845. count: morphTargetsCount,
  2846. texture: texture,
  2847. size: new Vector2( width, height )
  2848. };
  2849. morphTextures.set( geometry, entry );
  2850. function disposeTexture() {
  2851. texture.dispose();
  2852. morphTextures.delete( geometry );
  2853. geometry.removeEventListener( 'dispose', disposeTexture );
  2854. }
  2855. geometry.addEventListener( 'dispose', disposeTexture );
  2856. }
  2857. //
  2858. if ( object.isInstancedMesh === true && object.morphTexture !== null ) {
  2859. program.getUniforms().setValue( gl, 'morphTexture', object.morphTexture, textures );
  2860. } else {
  2861. let morphInfluencesSum = 0;
  2862. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  2863. morphInfluencesSum += objectInfluences[ i ];
  2864. }
  2865. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  2866. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  2867. program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences );
  2868. }
  2869. program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures );
  2870. program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size );
  2871. }
  2872. return {
  2873. update: update
  2874. };
  2875. }
  2876. function WebGLObjects( gl, geometries, attributes, bindingStates, info ) {
  2877. let updateMap = new WeakMap();
  2878. function update( object ) {
  2879. const frame = info.render.frame;
  2880. const geometry = object.geometry;
  2881. const buffergeometry = geometries.get( object, geometry );
  2882. // Update once per frame
  2883. if ( updateMap.get( buffergeometry ) !== frame ) {
  2884. geometries.update( buffergeometry );
  2885. updateMap.set( buffergeometry, frame );
  2886. }
  2887. if ( object.isInstancedMesh ) {
  2888. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  2889. object.addEventListener( 'dispose', onInstancedMeshDispose );
  2890. }
  2891. if ( updateMap.get( object ) !== frame ) {
  2892. attributes.update( object.instanceMatrix, gl.ARRAY_BUFFER );
  2893. if ( object.instanceColor !== null ) {
  2894. attributes.update( object.instanceColor, gl.ARRAY_BUFFER );
  2895. }
  2896. updateMap.set( object, frame );
  2897. }
  2898. }
  2899. if ( object.isSkinnedMesh ) {
  2900. const skeleton = object.skeleton;
  2901. if ( updateMap.get( skeleton ) !== frame ) {
  2902. skeleton.update();
  2903. updateMap.set( skeleton, frame );
  2904. }
  2905. }
  2906. return buffergeometry;
  2907. }
  2908. function dispose() {
  2909. updateMap = new WeakMap();
  2910. }
  2911. function onInstancedMeshDispose( event ) {
  2912. const instancedMesh = event.target;
  2913. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  2914. bindingStates.releaseStatesOfObject( instancedMesh );
  2915. attributes.remove( instancedMesh.instanceMatrix );
  2916. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  2917. }
  2918. return {
  2919. update: update,
  2920. dispose: dispose
  2921. };
  2922. }
  2923. const toneMappingMap = {
  2924. [ LinearToneMapping ]: 'LINEAR_TONE_MAPPING',
  2925. [ ReinhardToneMapping ]: 'REINHARD_TONE_MAPPING',
  2926. [ CineonToneMapping ]: 'CINEON_TONE_MAPPING',
  2927. [ ACESFilmicToneMapping ]: 'ACES_FILMIC_TONE_MAPPING',
  2928. [ AgXToneMapping ]: 'AGX_TONE_MAPPING',
  2929. [ NeutralToneMapping ]: 'NEUTRAL_TONE_MAPPING',
  2930. [ CustomToneMapping ]: 'CUSTOM_TONE_MAPPING'
  2931. };
  2932. function WebGLOutput( type, width, height, depth, stencil ) {
  2933. // render targets for scene and post-processing
  2934. const targetA = new WebGLRenderTarget( width, height, {
  2935. type: type,
  2936. depthBuffer: depth,
  2937. stencilBuffer: stencil
  2938. } );
  2939. const targetB = new WebGLRenderTarget( width, height, {
  2940. type: HalfFloatType,
  2941. depthBuffer: false,
  2942. stencilBuffer: false
  2943. } );
  2944. // create fullscreen triangle geometry
  2945. const geometry = new BufferGeometry();
  2946. geometry.setAttribute( 'position', new Float32BufferAttribute( [ -1, 3, 0, -1, -1, 0, 3, -1, 0 ], 3 ) );
  2947. geometry.setAttribute( 'uv', new Float32BufferAttribute( [ 0, 2, 0, 0, 2, 0 ], 2 ) );
  2948. // create output material with tone mapping support
  2949. const material = new RawShaderMaterial( {
  2950. uniforms: {
  2951. tDiffuse: { value: null }
  2952. },
  2953. vertexShader: /* glsl */`
  2954. precision highp float;
  2955. uniform mat4 modelViewMatrix;
  2956. uniform mat4 projectionMatrix;
  2957. attribute vec3 position;
  2958. attribute vec2 uv;
  2959. varying vec2 vUv;
  2960. void main() {
  2961. vUv = uv;
  2962. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  2963. }`,
  2964. fragmentShader: /* glsl */`
  2965. precision highp float;
  2966. uniform sampler2D tDiffuse;
  2967. varying vec2 vUv;
  2968. #include <tonemapping_pars_fragment>
  2969. #include <colorspace_pars_fragment>
  2970. void main() {
  2971. gl_FragColor = texture2D( tDiffuse, vUv );
  2972. #ifdef LINEAR_TONE_MAPPING
  2973. gl_FragColor.rgb = LinearToneMapping( gl_FragColor.rgb );
  2974. #elif defined( REINHARD_TONE_MAPPING )
  2975. gl_FragColor.rgb = ReinhardToneMapping( gl_FragColor.rgb );
  2976. #elif defined( CINEON_TONE_MAPPING )
  2977. gl_FragColor.rgb = CineonToneMapping( gl_FragColor.rgb );
  2978. #elif defined( ACES_FILMIC_TONE_MAPPING )
  2979. gl_FragColor.rgb = ACESFilmicToneMapping( gl_FragColor.rgb );
  2980. #elif defined( AGX_TONE_MAPPING )
  2981. gl_FragColor.rgb = AgXToneMapping( gl_FragColor.rgb );
  2982. #elif defined( NEUTRAL_TONE_MAPPING )
  2983. gl_FragColor.rgb = NeutralToneMapping( gl_FragColor.rgb );
  2984. #elif defined( CUSTOM_TONE_MAPPING )
  2985. gl_FragColor.rgb = CustomToneMapping( gl_FragColor.rgb );
  2986. #endif
  2987. #ifdef SRGB_TRANSFER
  2988. gl_FragColor = sRGBTransferOETF( gl_FragColor );
  2989. #endif
  2990. }`,
  2991. depthTest: false,
  2992. depthWrite: false
  2993. } );
  2994. const mesh = new Mesh( geometry, material );
  2995. const camera = new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  2996. let _outputColorSpace = null;
  2997. let _outputToneMapping = null;
  2998. let _isCompositing = false;
  2999. let _savedToneMapping;
  3000. let _savedRenderTarget = null;
  3001. let _effects = [];
  3002. let _hasRenderPass = false;
  3003. this.setSize = function ( width, height ) {
  3004. targetA.setSize( width, height );
  3005. targetB.setSize( width, height );
  3006. for ( let i = 0; i < _effects.length; i ++ ) {
  3007. const effect = _effects[ i ];
  3008. if ( effect.setSize ) effect.setSize( width, height );
  3009. }
  3010. };
  3011. this.setEffects = function ( effects ) {
  3012. _effects = effects;
  3013. _hasRenderPass = _effects.length > 0 && _effects[ 0 ].isRenderPass === true;
  3014. const width = targetA.width;
  3015. const height = targetA.height;
  3016. for ( let i = 0; i < _effects.length; i ++ ) {
  3017. const effect = _effects[ i ];
  3018. if ( effect.setSize ) effect.setSize( width, height );
  3019. }
  3020. };
  3021. this.begin = function ( renderer, renderTarget ) {
  3022. // Don't begin during compositing phase (post-processing effects call render())
  3023. if ( _isCompositing ) return false;
  3024. if ( renderer.toneMapping === NoToneMapping && _effects.length === 0 ) return false;
  3025. _savedRenderTarget = renderTarget;
  3026. // resize internal buffers to match render target (e.g. XR resolution)
  3027. if ( renderTarget !== null ) {
  3028. const width = renderTarget.width;
  3029. const height = renderTarget.height;
  3030. if ( targetA.width !== width || targetA.height !== height ) {
  3031. this.setSize( width, height );
  3032. }
  3033. }
  3034. // if first effect is a RenderPass, it will set its own render target
  3035. if ( _hasRenderPass === false ) {
  3036. renderer.setRenderTarget( targetA );
  3037. }
  3038. // disable tone mapping during render - it will be applied in end()
  3039. _savedToneMapping = renderer.toneMapping;
  3040. renderer.toneMapping = NoToneMapping;
  3041. return true;
  3042. };
  3043. this.hasRenderPass = function () {
  3044. return _hasRenderPass;
  3045. };
  3046. this.end = function ( renderer, deltaTime ) {
  3047. // restore tone mapping
  3048. renderer.toneMapping = _savedToneMapping;
  3049. _isCompositing = true;
  3050. // run post-processing effects
  3051. let readBuffer = targetA;
  3052. let writeBuffer = targetB;
  3053. for ( let i = 0; i < _effects.length; i ++ ) {
  3054. const effect = _effects[ i ];
  3055. if ( effect.enabled === false ) continue;
  3056. effect.render( renderer, writeBuffer, readBuffer, deltaTime );
  3057. if ( effect.needsSwap !== false ) {
  3058. const temp = readBuffer;
  3059. readBuffer = writeBuffer;
  3060. writeBuffer = temp;
  3061. }
  3062. }
  3063. // update output material defines if settings changed
  3064. if ( _outputColorSpace !== renderer.outputColorSpace || _outputToneMapping !== renderer.toneMapping ) {
  3065. _outputColorSpace = renderer.outputColorSpace;
  3066. _outputToneMapping = renderer.toneMapping;
  3067. material.defines = {};
  3068. if ( ColorManagement.getTransfer( _outputColorSpace ) === SRGBTransfer ) material.defines.SRGB_TRANSFER = '';
  3069. const toneMapping = toneMappingMap[ _outputToneMapping ];
  3070. if ( toneMapping ) material.defines[ toneMapping ] = '';
  3071. material.needsUpdate = true;
  3072. }
  3073. // final output to canvas (or XR render target)
  3074. material.uniforms.tDiffuse.value = readBuffer.texture;
  3075. renderer.setRenderTarget( _savedRenderTarget );
  3076. renderer.render( mesh, camera );
  3077. _savedRenderTarget = null;
  3078. _isCompositing = false;
  3079. };
  3080. this.isCompositing = function () {
  3081. return _isCompositing;
  3082. };
  3083. this.dispose = function () {
  3084. targetA.dispose();
  3085. targetB.dispose();
  3086. geometry.dispose();
  3087. material.dispose();
  3088. };
  3089. }
  3090. /**
  3091. * Uniforms of a program.
  3092. * Those form a tree structure with a special top-level container for the root,
  3093. * which you get by calling 'new WebGLUniforms( gl, program )'.
  3094. *
  3095. *
  3096. * Properties of inner nodes including the top-level container:
  3097. *
  3098. * .seq - array of nested uniforms
  3099. * .map - nested uniforms by name
  3100. *
  3101. *
  3102. * Methods of all nodes except the top-level container:
  3103. *
  3104. * .setValue( gl, value, [textures] )
  3105. *
  3106. * uploads a uniform value(s)
  3107. * the 'textures' parameter is needed for sampler uniforms
  3108. *
  3109. *
  3110. * Static methods of the top-level container (textures factorizations):
  3111. *
  3112. * .upload( gl, seq, values, textures )
  3113. *
  3114. * sets uniforms in 'seq' to 'values[id].value'
  3115. *
  3116. * .seqWithValue( seq, values ) : filteredSeq
  3117. *
  3118. * filters 'seq' entries with corresponding entry in values
  3119. *
  3120. *
  3121. * Methods of the top-level container (textures factorizations):
  3122. *
  3123. * .setValue( gl, name, value, textures )
  3124. *
  3125. * sets uniform with name 'name' to 'value'
  3126. *
  3127. * .setOptional( gl, obj, prop )
  3128. *
  3129. * like .set for an optional property of the object
  3130. *
  3131. */
  3132. const emptyTexture = /*@__PURE__*/ new Texture();
  3133. const emptyShadowTexture = /*@__PURE__*/ new DepthTexture( 1, 1 );
  3134. const emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture();
  3135. const empty3dTexture = /*@__PURE__*/ new Data3DTexture();
  3136. const emptyCubeTexture = /*@__PURE__*/ new CubeTexture();
  3137. // --- Utilities ---
  3138. // Array Caches (provide typed arrays for temporary by size)
  3139. const arrayCacheF32 = [];
  3140. const arrayCacheI32 = [];
  3141. // Float32Array caches used for uploading Matrix uniforms
  3142. const mat4array = new Float32Array( 16 );
  3143. const mat3array = new Float32Array( 9 );
  3144. const mat2array = new Float32Array( 4 );
  3145. // Flattening for arrays of vectors and matrices
  3146. function flatten( array, nBlocks, blockSize ) {
  3147. const firstElem = array[ 0 ];
  3148. if ( firstElem <= 0 || firstElem > 0 ) return array;
  3149. // unoptimized: ! isNaN( firstElem )
  3150. // see http://jacksondunstan.com/articles/983
  3151. const n = nBlocks * blockSize;
  3152. let r = arrayCacheF32[ n ];
  3153. if ( r === undefined ) {
  3154. r = new Float32Array( n );
  3155. arrayCacheF32[ n ] = r;
  3156. }
  3157. if ( nBlocks !== 0 ) {
  3158. firstElem.toArray( r, 0 );
  3159. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  3160. offset += blockSize;
  3161. array[ i ].toArray( r, offset );
  3162. }
  3163. }
  3164. return r;
  3165. }
  3166. function arraysEqual( a, b ) {
  3167. if ( a.length !== b.length ) return false;
  3168. for ( let i = 0, l = a.length; i < l; i ++ ) {
  3169. if ( a[ i ] !== b[ i ] ) return false;
  3170. }
  3171. return true;
  3172. }
  3173. function copyArray( a, b ) {
  3174. for ( let i = 0, l = b.length; i < l; i ++ ) {
  3175. a[ i ] = b[ i ];
  3176. }
  3177. }
  3178. // Texture unit allocation
  3179. function allocTexUnits( textures, n ) {
  3180. let r = arrayCacheI32[ n ];
  3181. if ( r === undefined ) {
  3182. r = new Int32Array( n );
  3183. arrayCacheI32[ n ] = r;
  3184. }
  3185. for ( let i = 0; i !== n; ++ i ) {
  3186. r[ i ] = textures.allocateTextureUnit();
  3187. }
  3188. return r;
  3189. }
  3190. // --- Setters ---
  3191. // Note: Defining these methods externally, because they come in a bunch
  3192. // and this way their names minify.
  3193. // Single scalar
  3194. function setValueV1f( gl, v ) {
  3195. const cache = this.cache;
  3196. if ( cache[ 0 ] === v ) return;
  3197. gl.uniform1f( this.addr, v );
  3198. cache[ 0 ] = v;
  3199. }
  3200. // Single float vector (from flat array or THREE.VectorN)
  3201. function setValueV2f( gl, v ) {
  3202. const cache = this.cache;
  3203. if ( v.x !== undefined ) {
  3204. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  3205. gl.uniform2f( this.addr, v.x, v.y );
  3206. cache[ 0 ] = v.x;
  3207. cache[ 1 ] = v.y;
  3208. }
  3209. } else {
  3210. if ( arraysEqual( cache, v ) ) return;
  3211. gl.uniform2fv( this.addr, v );
  3212. copyArray( cache, v );
  3213. }
  3214. }
  3215. function setValueV3f( gl, v ) {
  3216. const cache = this.cache;
  3217. if ( v.x !== undefined ) {
  3218. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  3219. gl.uniform3f( this.addr, v.x, v.y, v.z );
  3220. cache[ 0 ] = v.x;
  3221. cache[ 1 ] = v.y;
  3222. cache[ 2 ] = v.z;
  3223. }
  3224. } else if ( v.r !== undefined ) {
  3225. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  3226. gl.uniform3f( this.addr, v.r, v.g, v.b );
  3227. cache[ 0 ] = v.r;
  3228. cache[ 1 ] = v.g;
  3229. cache[ 2 ] = v.b;
  3230. }
  3231. } else {
  3232. if ( arraysEqual( cache, v ) ) return;
  3233. gl.uniform3fv( this.addr, v );
  3234. copyArray( cache, v );
  3235. }
  3236. }
  3237. function setValueV4f( gl, v ) {
  3238. const cache = this.cache;
  3239. if ( v.x !== undefined ) {
  3240. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  3241. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  3242. cache[ 0 ] = v.x;
  3243. cache[ 1 ] = v.y;
  3244. cache[ 2 ] = v.z;
  3245. cache[ 3 ] = v.w;
  3246. }
  3247. } else {
  3248. if ( arraysEqual( cache, v ) ) return;
  3249. gl.uniform4fv( this.addr, v );
  3250. copyArray( cache, v );
  3251. }
  3252. }
  3253. // Single matrix (from flat array or THREE.MatrixN)
  3254. function setValueM2( gl, v ) {
  3255. const cache = this.cache;
  3256. const elements = v.elements;
  3257. if ( elements === undefined ) {
  3258. if ( arraysEqual( cache, v ) ) return;
  3259. gl.uniformMatrix2fv( this.addr, false, v );
  3260. copyArray( cache, v );
  3261. } else {
  3262. if ( arraysEqual( cache, elements ) ) return;
  3263. mat2array.set( elements );
  3264. gl.uniformMatrix2fv( this.addr, false, mat2array );
  3265. copyArray( cache, elements );
  3266. }
  3267. }
  3268. function setValueM3( gl, v ) {
  3269. const cache = this.cache;
  3270. const elements = v.elements;
  3271. if ( elements === undefined ) {
  3272. if ( arraysEqual( cache, v ) ) return;
  3273. gl.uniformMatrix3fv( this.addr, false, v );
  3274. copyArray( cache, v );
  3275. } else {
  3276. if ( arraysEqual( cache, elements ) ) return;
  3277. mat3array.set( elements );
  3278. gl.uniformMatrix3fv( this.addr, false, mat3array );
  3279. copyArray( cache, elements );
  3280. }
  3281. }
  3282. function setValueM4( gl, v ) {
  3283. const cache = this.cache;
  3284. const elements = v.elements;
  3285. if ( elements === undefined ) {
  3286. if ( arraysEqual( cache, v ) ) return;
  3287. gl.uniformMatrix4fv( this.addr, false, v );
  3288. copyArray( cache, v );
  3289. } else {
  3290. if ( arraysEqual( cache, elements ) ) return;
  3291. mat4array.set( elements );
  3292. gl.uniformMatrix4fv( this.addr, false, mat4array );
  3293. copyArray( cache, elements );
  3294. }
  3295. }
  3296. // Single integer / boolean
  3297. function setValueV1i( gl, v ) {
  3298. const cache = this.cache;
  3299. if ( cache[ 0 ] === v ) return;
  3300. gl.uniform1i( this.addr, v );
  3301. cache[ 0 ] = v;
  3302. }
  3303. // Single integer / boolean vector (from flat array or THREE.VectorN)
  3304. function setValueV2i( gl, v ) {
  3305. const cache = this.cache;
  3306. if ( v.x !== undefined ) {
  3307. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  3308. gl.uniform2i( this.addr, v.x, v.y );
  3309. cache[ 0 ] = v.x;
  3310. cache[ 1 ] = v.y;
  3311. }
  3312. } else {
  3313. if ( arraysEqual( cache, v ) ) return;
  3314. gl.uniform2iv( this.addr, v );
  3315. copyArray( cache, v );
  3316. }
  3317. }
  3318. function setValueV3i( gl, v ) {
  3319. const cache = this.cache;
  3320. if ( v.x !== undefined ) {
  3321. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  3322. gl.uniform3i( this.addr, v.x, v.y, v.z );
  3323. cache[ 0 ] = v.x;
  3324. cache[ 1 ] = v.y;
  3325. cache[ 2 ] = v.z;
  3326. }
  3327. } else {
  3328. if ( arraysEqual( cache, v ) ) return;
  3329. gl.uniform3iv( this.addr, v );
  3330. copyArray( cache, v );
  3331. }
  3332. }
  3333. function setValueV4i( gl, v ) {
  3334. const cache = this.cache;
  3335. if ( v.x !== undefined ) {
  3336. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  3337. gl.uniform4i( this.addr, v.x, v.y, v.z, v.w );
  3338. cache[ 0 ] = v.x;
  3339. cache[ 1 ] = v.y;
  3340. cache[ 2 ] = v.z;
  3341. cache[ 3 ] = v.w;
  3342. }
  3343. } else {
  3344. if ( arraysEqual( cache, v ) ) return;
  3345. gl.uniform4iv( this.addr, v );
  3346. copyArray( cache, v );
  3347. }
  3348. }
  3349. // Single unsigned integer
  3350. function setValueV1ui( gl, v ) {
  3351. const cache = this.cache;
  3352. if ( cache[ 0 ] === v ) return;
  3353. gl.uniform1ui( this.addr, v );
  3354. cache[ 0 ] = v;
  3355. }
  3356. // Single unsigned integer vector (from flat array or THREE.VectorN)
  3357. function setValueV2ui( gl, v ) {
  3358. const cache = this.cache;
  3359. if ( v.x !== undefined ) {
  3360. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  3361. gl.uniform2ui( this.addr, v.x, v.y );
  3362. cache[ 0 ] = v.x;
  3363. cache[ 1 ] = v.y;
  3364. }
  3365. } else {
  3366. if ( arraysEqual( cache, v ) ) return;
  3367. gl.uniform2uiv( this.addr, v );
  3368. copyArray( cache, v );
  3369. }
  3370. }
  3371. function setValueV3ui( gl, v ) {
  3372. const cache = this.cache;
  3373. if ( v.x !== undefined ) {
  3374. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  3375. gl.uniform3ui( this.addr, v.x, v.y, v.z );
  3376. cache[ 0 ] = v.x;
  3377. cache[ 1 ] = v.y;
  3378. cache[ 2 ] = v.z;
  3379. }
  3380. } else {
  3381. if ( arraysEqual( cache, v ) ) return;
  3382. gl.uniform3uiv( this.addr, v );
  3383. copyArray( cache, v );
  3384. }
  3385. }
  3386. function setValueV4ui( gl, v ) {
  3387. const cache = this.cache;
  3388. if ( v.x !== undefined ) {
  3389. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  3390. gl.uniform4ui( this.addr, v.x, v.y, v.z, v.w );
  3391. cache[ 0 ] = v.x;
  3392. cache[ 1 ] = v.y;
  3393. cache[ 2 ] = v.z;
  3394. cache[ 3 ] = v.w;
  3395. }
  3396. } else {
  3397. if ( arraysEqual( cache, v ) ) return;
  3398. gl.uniform4uiv( this.addr, v );
  3399. copyArray( cache, v );
  3400. }
  3401. }
  3402. // Single texture (2D / Cube)
  3403. function setValueT1( gl, v, textures ) {
  3404. const cache = this.cache;
  3405. const unit = textures.allocateTextureUnit();
  3406. if ( cache[ 0 ] !== unit ) {
  3407. gl.uniform1i( this.addr, unit );
  3408. cache[ 0 ] = unit;
  3409. }
  3410. let emptyTexture2D;
  3411. if ( this.type === gl.SAMPLER_2D_SHADOW ) {
  3412. emptyShadowTexture.compareFunction = textures.isReversedDepthBuffer() ? GreaterEqualCompare : LessEqualCompare;
  3413. emptyTexture2D = emptyShadowTexture;
  3414. } else {
  3415. emptyTexture2D = emptyTexture;
  3416. }
  3417. textures.setTexture2D( v || emptyTexture2D, unit );
  3418. }
  3419. function setValueT3D1( gl, v, textures ) {
  3420. const cache = this.cache;
  3421. const unit = textures.allocateTextureUnit();
  3422. if ( cache[ 0 ] !== unit ) {
  3423. gl.uniform1i( this.addr, unit );
  3424. cache[ 0 ] = unit;
  3425. }
  3426. textures.setTexture3D( v || empty3dTexture, unit );
  3427. }
  3428. function setValueT6( gl, v, textures ) {
  3429. const cache = this.cache;
  3430. const unit = textures.allocateTextureUnit();
  3431. if ( cache[ 0 ] !== unit ) {
  3432. gl.uniform1i( this.addr, unit );
  3433. cache[ 0 ] = unit;
  3434. }
  3435. textures.setTextureCube( v || emptyCubeTexture, unit );
  3436. }
  3437. function setValueT2DArray1( gl, v, textures ) {
  3438. const cache = this.cache;
  3439. const unit = textures.allocateTextureUnit();
  3440. if ( cache[ 0 ] !== unit ) {
  3441. gl.uniform1i( this.addr, unit );
  3442. cache[ 0 ] = unit;
  3443. }
  3444. textures.setTexture2DArray( v || emptyArrayTexture, unit );
  3445. }
  3446. // Helper to pick the right setter for the singular case
  3447. function getSingularSetter( type ) {
  3448. switch ( type ) {
  3449. case 0x1406: return setValueV1f; // FLOAT
  3450. case 0x8b50: return setValueV2f; // _VEC2
  3451. case 0x8b51: return setValueV3f; // _VEC3
  3452. case 0x8b52: return setValueV4f; // _VEC4
  3453. case 0x8b5a: return setValueM2; // _MAT2
  3454. case 0x8b5b: return setValueM3; // _MAT3
  3455. case 0x8b5c: return setValueM4; // _MAT4
  3456. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  3457. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  3458. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  3459. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  3460. case 0x1405: return setValueV1ui; // UINT
  3461. case 0x8dc6: return setValueV2ui; // _VEC2
  3462. case 0x8dc7: return setValueV3ui; // _VEC3
  3463. case 0x8dc8: return setValueV4ui; // _VEC4
  3464. case 0x8b5e: // SAMPLER_2D
  3465. case 0x8d66: // SAMPLER_EXTERNAL_OES
  3466. case 0x8dca: // INT_SAMPLER_2D
  3467. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  3468. case 0x8b62: // SAMPLER_2D_SHADOW
  3469. return setValueT1;
  3470. case 0x8b5f: // SAMPLER_3D
  3471. case 0x8dcb: // INT_SAMPLER_3D
  3472. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  3473. return setValueT3D1;
  3474. case 0x8b60: // SAMPLER_CUBE
  3475. case 0x8dcc: // INT_SAMPLER_CUBE
  3476. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  3477. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  3478. return setValueT6;
  3479. case 0x8dc1: // SAMPLER_2D_ARRAY
  3480. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  3481. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  3482. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  3483. return setValueT2DArray1;
  3484. }
  3485. }
  3486. // Array of scalars
  3487. function setValueV1fArray( gl, v ) {
  3488. gl.uniform1fv( this.addr, v );
  3489. }
  3490. // Array of vectors (from flat array or array of THREE.VectorN)
  3491. function setValueV2fArray( gl, v ) {
  3492. const data = flatten( v, this.size, 2 );
  3493. gl.uniform2fv( this.addr, data );
  3494. }
  3495. function setValueV3fArray( gl, v ) {
  3496. const data = flatten( v, this.size, 3 );
  3497. gl.uniform3fv( this.addr, data );
  3498. }
  3499. function setValueV4fArray( gl, v ) {
  3500. const data = flatten( v, this.size, 4 );
  3501. gl.uniform4fv( this.addr, data );
  3502. }
  3503. // Array of matrices (from flat array or array of THREE.MatrixN)
  3504. function setValueM2Array( gl, v ) {
  3505. const data = flatten( v, this.size, 4 );
  3506. gl.uniformMatrix2fv( this.addr, false, data );
  3507. }
  3508. function setValueM3Array( gl, v ) {
  3509. const data = flatten( v, this.size, 9 );
  3510. gl.uniformMatrix3fv( this.addr, false, data );
  3511. }
  3512. function setValueM4Array( gl, v ) {
  3513. const data = flatten( v, this.size, 16 );
  3514. gl.uniformMatrix4fv( this.addr, false, data );
  3515. }
  3516. // Array of integer / boolean
  3517. function setValueV1iArray( gl, v ) {
  3518. gl.uniform1iv( this.addr, v );
  3519. }
  3520. // Array of integer / boolean vectors (from flat array)
  3521. function setValueV2iArray( gl, v ) {
  3522. gl.uniform2iv( this.addr, v );
  3523. }
  3524. function setValueV3iArray( gl, v ) {
  3525. gl.uniform3iv( this.addr, v );
  3526. }
  3527. function setValueV4iArray( gl, v ) {
  3528. gl.uniform4iv( this.addr, v );
  3529. }
  3530. // Array of unsigned integer
  3531. function setValueV1uiArray( gl, v ) {
  3532. gl.uniform1uiv( this.addr, v );
  3533. }
  3534. // Array of unsigned integer vectors (from flat array)
  3535. function setValueV2uiArray( gl, v ) {
  3536. gl.uniform2uiv( this.addr, v );
  3537. }
  3538. function setValueV3uiArray( gl, v ) {
  3539. gl.uniform3uiv( this.addr, v );
  3540. }
  3541. function setValueV4uiArray( gl, v ) {
  3542. gl.uniform4uiv( this.addr, v );
  3543. }
  3544. // Array of textures (2D / 3D / Cube / 2DArray)
  3545. function setValueT1Array( gl, v, textures ) {
  3546. const cache = this.cache;
  3547. const n = v.length;
  3548. const units = allocTexUnits( textures, n );
  3549. if ( ! arraysEqual( cache, units ) ) {
  3550. gl.uniform1iv( this.addr, units );
  3551. copyArray( cache, units );
  3552. }
  3553. let emptyTexture2D;
  3554. if ( this.type === gl.SAMPLER_2D_SHADOW ) {
  3555. emptyTexture2D = emptyShadowTexture;
  3556. } else {
  3557. emptyTexture2D = emptyTexture;
  3558. }
  3559. for ( let i = 0; i !== n; ++ i ) {
  3560. textures.setTexture2D( v[ i ] || emptyTexture2D, units[ i ] );
  3561. }
  3562. }
  3563. function setValueT3DArray( gl, v, textures ) {
  3564. const cache = this.cache;
  3565. const n = v.length;
  3566. const units = allocTexUnits( textures, n );
  3567. if ( ! arraysEqual( cache, units ) ) {
  3568. gl.uniform1iv( this.addr, units );
  3569. copyArray( cache, units );
  3570. }
  3571. for ( let i = 0; i !== n; ++ i ) {
  3572. textures.setTexture3D( v[ i ] || empty3dTexture, units[ i ] );
  3573. }
  3574. }
  3575. function setValueT6Array( gl, v, textures ) {
  3576. const cache = this.cache;
  3577. const n = v.length;
  3578. const units = allocTexUnits( textures, n );
  3579. if ( ! arraysEqual( cache, units ) ) {
  3580. gl.uniform1iv( this.addr, units );
  3581. copyArray( cache, units );
  3582. }
  3583. for ( let i = 0; i !== n; ++ i ) {
  3584. textures.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  3585. }
  3586. }
  3587. function setValueT2DArrayArray( gl, v, textures ) {
  3588. const cache = this.cache;
  3589. const n = v.length;
  3590. const units = allocTexUnits( textures, n );
  3591. if ( ! arraysEqual( cache, units ) ) {
  3592. gl.uniform1iv( this.addr, units );
  3593. copyArray( cache, units );
  3594. }
  3595. for ( let i = 0; i !== n; ++ i ) {
  3596. textures.setTexture2DArray( v[ i ] || emptyArrayTexture, units[ i ] );
  3597. }
  3598. }
  3599. // Helper to pick the right setter for a pure (bottom-level) array
  3600. function getPureArraySetter( type ) {
  3601. switch ( type ) {
  3602. case 0x1406: return setValueV1fArray; // FLOAT
  3603. case 0x8b50: return setValueV2fArray; // _VEC2
  3604. case 0x8b51: return setValueV3fArray; // _VEC3
  3605. case 0x8b52: return setValueV4fArray; // _VEC4
  3606. case 0x8b5a: return setValueM2Array; // _MAT2
  3607. case 0x8b5b: return setValueM3Array; // _MAT3
  3608. case 0x8b5c: return setValueM4Array; // _MAT4
  3609. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  3610. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  3611. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  3612. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  3613. case 0x1405: return setValueV1uiArray; // UINT
  3614. case 0x8dc6: return setValueV2uiArray; // _VEC2
  3615. case 0x8dc7: return setValueV3uiArray; // _VEC3
  3616. case 0x8dc8: return setValueV4uiArray; // _VEC4
  3617. case 0x8b5e: // SAMPLER_2D
  3618. case 0x8d66: // SAMPLER_EXTERNAL_OES
  3619. case 0x8dca: // INT_SAMPLER_2D
  3620. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  3621. case 0x8b62: // SAMPLER_2D_SHADOW
  3622. return setValueT1Array;
  3623. case 0x8b5f: // SAMPLER_3D
  3624. case 0x8dcb: // INT_SAMPLER_3D
  3625. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  3626. return setValueT3DArray;
  3627. case 0x8b60: // SAMPLER_CUBE
  3628. case 0x8dcc: // INT_SAMPLER_CUBE
  3629. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  3630. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  3631. return setValueT6Array;
  3632. case 0x8dc1: // SAMPLER_2D_ARRAY
  3633. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  3634. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  3635. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  3636. return setValueT2DArrayArray;
  3637. }
  3638. }
  3639. // --- Uniform Classes ---
  3640. class SingleUniform {
  3641. constructor( id, activeInfo, addr ) {
  3642. this.id = id;
  3643. this.addr = addr;
  3644. this.cache = [];
  3645. this.type = activeInfo.type;
  3646. this.setValue = getSingularSetter( activeInfo.type );
  3647. // this.path = activeInfo.name; // DEBUG
  3648. }
  3649. }
  3650. class PureArrayUniform {
  3651. constructor( id, activeInfo, addr ) {
  3652. this.id = id;
  3653. this.addr = addr;
  3654. this.cache = [];
  3655. this.type = activeInfo.type;
  3656. this.size = activeInfo.size;
  3657. this.setValue = getPureArraySetter( activeInfo.type );
  3658. // this.path = activeInfo.name; // DEBUG
  3659. }
  3660. }
  3661. class StructuredUniform {
  3662. constructor( id ) {
  3663. this.id = id;
  3664. this.seq = [];
  3665. this.map = {};
  3666. }
  3667. setValue( gl, value, textures ) {
  3668. const seq = this.seq;
  3669. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  3670. const u = seq[ i ];
  3671. u.setValue( gl, value[ u.id ], textures );
  3672. }
  3673. }
  3674. }
  3675. // --- Top-level ---
  3676. // Parser - builds up the property tree from the path strings
  3677. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  3678. // extracts
  3679. // - the identifier (member name or array index)
  3680. // - followed by an optional right bracket (found when array index)
  3681. // - followed by an optional left bracket or dot (type of subscript)
  3682. //
  3683. // Note: These portions can be read in a non-overlapping fashion and
  3684. // allow straightforward parsing of the hierarchy that WebGL encodes
  3685. // in the uniform names.
  3686. function addUniform( container, uniformObject ) {
  3687. container.seq.push( uniformObject );
  3688. container.map[ uniformObject.id ] = uniformObject;
  3689. }
  3690. function parseUniform( activeInfo, addr, container ) {
  3691. const path = activeInfo.name,
  3692. pathLength = path.length;
  3693. // reset RegExp object, because of the early exit of a previous run
  3694. RePathPart.lastIndex = 0;
  3695. while ( true ) {
  3696. const match = RePathPart.exec( path ),
  3697. matchEnd = RePathPart.lastIndex;
  3698. let id = match[ 1 ];
  3699. const idIsIndex = match[ 2 ] === ']',
  3700. subscript = match[ 3 ];
  3701. if ( idIsIndex ) id = id | 0; // convert to integer
  3702. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  3703. // bare name or "pure" bottom-level array "[0]" suffix
  3704. addUniform( container, subscript === undefined ?
  3705. new SingleUniform( id, activeInfo, addr ) :
  3706. new PureArrayUniform( id, activeInfo, addr ) );
  3707. break;
  3708. } else {
  3709. // step into inner node / create it in case it doesn't exist
  3710. const map = container.map;
  3711. let next = map[ id ];
  3712. if ( next === undefined ) {
  3713. next = new StructuredUniform( id );
  3714. addUniform( container, next );
  3715. }
  3716. container = next;
  3717. }
  3718. }
  3719. }
  3720. // Root Container
  3721. class WebGLUniforms {
  3722. constructor( gl, program ) {
  3723. this.seq = [];
  3724. this.map = {};
  3725. const n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  3726. for ( let i = 0; i < n; ++ i ) {
  3727. const info = gl.getActiveUniform( program, i ),
  3728. addr = gl.getUniformLocation( program, info.name );
  3729. parseUniform( info, addr, this );
  3730. }
  3731. // Sort uniforms to prioritize shadow samplers first (for optimal texture unit allocation)
  3732. const shadowSamplers = [];
  3733. const otherUniforms = [];
  3734. for ( const u of this.seq ) {
  3735. if ( u.type === gl.SAMPLER_2D_SHADOW || u.type === gl.SAMPLER_CUBE_SHADOW || u.type === gl.SAMPLER_2D_ARRAY_SHADOW ) {
  3736. shadowSamplers.push( u );
  3737. } else {
  3738. otherUniforms.push( u );
  3739. }
  3740. }
  3741. if ( shadowSamplers.length > 0 ) {
  3742. this.seq = shadowSamplers.concat( otherUniforms );
  3743. }
  3744. }
  3745. setValue( gl, name, value, textures ) {
  3746. const u = this.map[ name ];
  3747. if ( u !== undefined ) u.setValue( gl, value, textures );
  3748. }
  3749. setOptional( gl, object, name ) {
  3750. const v = object[ name ];
  3751. if ( v !== undefined ) this.setValue( gl, name, v );
  3752. }
  3753. static upload( gl, seq, values, textures ) {
  3754. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  3755. const u = seq[ i ],
  3756. v = values[ u.id ];
  3757. if ( v.needsUpdate !== false ) {
  3758. // note: always updating when .needsUpdate is undefined
  3759. u.setValue( gl, v.value, textures );
  3760. }
  3761. }
  3762. }
  3763. static seqWithValue( seq, values ) {
  3764. const r = [];
  3765. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  3766. const u = seq[ i ];
  3767. if ( u.id in values ) r.push( u );
  3768. }
  3769. return r;
  3770. }
  3771. }
  3772. function WebGLShader( gl, type, string ) {
  3773. const shader = gl.createShader( type );
  3774. gl.shaderSource( shader, string );
  3775. gl.compileShader( shader );
  3776. return shader;
  3777. }
  3778. // From https://www.khronos.org/registry/webgl/extensions/KHR_parallel_shader_compile/
  3779. const COMPLETION_STATUS_KHR = 0x91B1;
  3780. let programIdCount = 0;
  3781. function handleSource( string, errorLine ) {
  3782. const lines = string.split( '\n' );
  3783. const lines2 = [];
  3784. const from = Math.max( errorLine - 6, 0 );
  3785. const to = Math.min( errorLine + 6, lines.length );
  3786. for ( let i = from; i < to; i ++ ) {
  3787. const line = i + 1;
  3788. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  3789. }
  3790. return lines2.join( '\n' );
  3791. }
  3792. const _m0 = /*@__PURE__*/ new Matrix3();
  3793. function getEncodingComponents( colorSpace ) {
  3794. ColorManagement._getMatrix( _m0, ColorManagement.workingColorSpace, colorSpace );
  3795. const encodingMatrix = `mat3( ${ _m0.elements.map( ( v ) => v.toFixed( 4 ) ) } )`;
  3796. switch ( ColorManagement.getTransfer( colorSpace ) ) {
  3797. case LinearTransfer:
  3798. return [ encodingMatrix, 'LinearTransferOETF' ];
  3799. case SRGBTransfer:
  3800. return [ encodingMatrix, 'sRGBTransferOETF' ];
  3801. default:
  3802. warn( 'WebGLProgram: Unsupported color space: ', colorSpace );
  3803. return [ encodingMatrix, 'LinearTransferOETF' ];
  3804. }
  3805. }
  3806. function getShaderErrors( gl, shader, type ) {
  3807. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  3808. const shaderInfoLog = gl.getShaderInfoLog( shader ) || '';
  3809. const errors = shaderInfoLog.trim();
  3810. if ( status && errors === '' ) return '';
  3811. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  3812. if ( errorMatches ) {
  3813. // --enable-privileged-webgl-extension
  3814. // log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  3815. const errorLine = parseInt( errorMatches[ 1 ] );
  3816. return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine );
  3817. } else {
  3818. return errors;
  3819. }
  3820. }
  3821. function getTexelEncodingFunction( functionName, colorSpace ) {
  3822. const components = getEncodingComponents( colorSpace );
  3823. return [
  3824. `vec4 ${functionName}( vec4 value ) {`,
  3825. ` return ${components[ 1 ]}( vec4( value.rgb * ${components[ 0 ]}, value.a ) );`,
  3826. '}',
  3827. ].join( '\n' );
  3828. }
  3829. const toneMappingFunctions = {
  3830. [ LinearToneMapping ]: 'Linear',
  3831. [ ReinhardToneMapping ]: 'Reinhard',
  3832. [ CineonToneMapping ]: 'Cineon',
  3833. [ ACESFilmicToneMapping ]: 'ACESFilmic',
  3834. [ AgXToneMapping ]: 'AgX',
  3835. [ NeutralToneMapping ]: 'Neutral',
  3836. [ CustomToneMapping ]: 'Custom'
  3837. };
  3838. function getToneMappingFunction( functionName, toneMapping ) {
  3839. const toneMappingName = toneMappingFunctions[ toneMapping ];
  3840. if ( toneMappingName === undefined ) {
  3841. warn( 'WebGLProgram: Unsupported toneMapping:', toneMapping );
  3842. return 'vec3 ' + functionName + '( vec3 color ) { return LinearToneMapping( color ); }';
  3843. }
  3844. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  3845. }
  3846. const _v0 = /*@__PURE__*/ new Vector3();
  3847. function getLuminanceFunction() {
  3848. ColorManagement.getLuminanceCoefficients( _v0 );
  3849. const r = _v0.x.toFixed( 4 );
  3850. const g = _v0.y.toFixed( 4 );
  3851. const b = _v0.z.toFixed( 4 );
  3852. return [
  3853. 'float luminance( const in vec3 rgb ) {',
  3854. ` const vec3 weights = vec3( ${ r }, ${ g }, ${ b } );`,
  3855. ' return dot( weights, rgb );',
  3856. '}'
  3857. ].join( '\n' );
  3858. }
  3859. function generateVertexExtensions( parameters ) {
  3860. const chunks = [
  3861. parameters.extensionClipCullDistance ? '#extension GL_ANGLE_clip_cull_distance : require' : '',
  3862. parameters.extensionMultiDraw ? '#extension GL_ANGLE_multi_draw : require' : '',
  3863. ];
  3864. return chunks.filter( filterEmptyLine ).join( '\n' );
  3865. }
  3866. function generateDefines( defines ) {
  3867. const chunks = [];
  3868. for ( const name in defines ) {
  3869. const value = defines[ name ];
  3870. if ( value === false ) continue;
  3871. chunks.push( '#define ' + name + ' ' + value );
  3872. }
  3873. return chunks.join( '\n' );
  3874. }
  3875. function fetchAttributeLocations( gl, program ) {
  3876. const attributes = {};
  3877. const n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  3878. for ( let i = 0; i < n; i ++ ) {
  3879. const info = gl.getActiveAttrib( program, i );
  3880. const name = info.name;
  3881. let locationSize = 1;
  3882. if ( info.type === gl.FLOAT_MAT2 ) locationSize = 2;
  3883. if ( info.type === gl.FLOAT_MAT3 ) locationSize = 3;
  3884. if ( info.type === gl.FLOAT_MAT4 ) locationSize = 4;
  3885. // log( 'WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  3886. attributes[ name ] = {
  3887. type: info.type,
  3888. location: gl.getAttribLocation( program, name ),
  3889. locationSize: locationSize
  3890. };
  3891. }
  3892. return attributes;
  3893. }
  3894. function filterEmptyLine( string ) {
  3895. return string !== '';
  3896. }
  3897. function replaceLightNums( string, parameters ) {
  3898. const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps;
  3899. return string
  3900. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  3901. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  3902. .replace( /NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps )
  3903. .replace( /NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords )
  3904. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  3905. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  3906. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  3907. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  3908. .replace( /NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps )
  3909. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  3910. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  3911. }
  3912. function replaceClippingPlaneNums( string, parameters ) {
  3913. return string
  3914. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  3915. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  3916. }
  3917. // Resolve Includes
  3918. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  3919. function resolveIncludes( string ) {
  3920. return string.replace( includePattern, includeReplacer );
  3921. }
  3922. const shaderChunkMap = new Map();
  3923. function includeReplacer( match, include ) {
  3924. let string = ShaderChunk[ include ];
  3925. if ( string === undefined ) {
  3926. const newInclude = shaderChunkMap.get( include );
  3927. if ( newInclude !== undefined ) {
  3928. string = ShaderChunk[ newInclude ];
  3929. warn( 'WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.', include, newInclude );
  3930. } else {
  3931. throw new Error( 'Can not resolve #include <' + include + '>' );
  3932. }
  3933. }
  3934. return resolveIncludes( string );
  3935. }
  3936. // Unroll Loops
  3937. const unrollLoopPattern = /#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;
  3938. function unrollLoops( string ) {
  3939. return string.replace( unrollLoopPattern, loopReplacer );
  3940. }
  3941. function loopReplacer( match, start, end, snippet ) {
  3942. let string = '';
  3943. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  3944. string += snippet
  3945. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  3946. .replace( /UNROLLED_LOOP_INDEX/g, i );
  3947. }
  3948. return string;
  3949. }
  3950. //
  3951. function generatePrecision( parameters ) {
  3952. let precisionstring = `precision ${parameters.precision} float;
  3953. precision ${parameters.precision} int;
  3954. precision ${parameters.precision} sampler2D;
  3955. precision ${parameters.precision} samplerCube;
  3956. precision ${parameters.precision} sampler3D;
  3957. precision ${parameters.precision} sampler2DArray;
  3958. precision ${parameters.precision} sampler2DShadow;
  3959. precision ${parameters.precision} samplerCubeShadow;
  3960. precision ${parameters.precision} sampler2DArrayShadow;
  3961. precision ${parameters.precision} isampler2D;
  3962. precision ${parameters.precision} isampler3D;
  3963. precision ${parameters.precision} isamplerCube;
  3964. precision ${parameters.precision} isampler2DArray;
  3965. precision ${parameters.precision} usampler2D;
  3966. precision ${parameters.precision} usampler3D;
  3967. precision ${parameters.precision} usamplerCube;
  3968. precision ${parameters.precision} usampler2DArray;
  3969. `;
  3970. if ( parameters.precision === 'highp' ) {
  3971. precisionstring += '\n#define HIGH_PRECISION';
  3972. } else if ( parameters.precision === 'mediump' ) {
  3973. precisionstring += '\n#define MEDIUM_PRECISION';
  3974. } else if ( parameters.precision === 'lowp' ) {
  3975. precisionstring += '\n#define LOW_PRECISION';
  3976. }
  3977. return precisionstring;
  3978. }
  3979. const shadowMapTypeDefines = {
  3980. [ PCFShadowMap ]: 'SHADOWMAP_TYPE_PCF',
  3981. [ VSMShadowMap ]: 'SHADOWMAP_TYPE_VSM'
  3982. };
  3983. function generateShadowMapTypeDefine( parameters ) {
  3984. return shadowMapTypeDefines[ parameters.shadowMapType ] || 'SHADOWMAP_TYPE_BASIC';
  3985. }
  3986. const envMapTypeDefines = {
  3987. [ CubeReflectionMapping ]: 'ENVMAP_TYPE_CUBE',
  3988. [ CubeRefractionMapping ]: 'ENVMAP_TYPE_CUBE',
  3989. [ CubeUVReflectionMapping ]: 'ENVMAP_TYPE_CUBE_UV'
  3990. };
  3991. function generateEnvMapTypeDefine( parameters ) {
  3992. if ( parameters.envMap === false ) return 'ENVMAP_TYPE_CUBE';
  3993. return envMapTypeDefines[ parameters.envMapMode ] || 'ENVMAP_TYPE_CUBE';
  3994. }
  3995. const envMapModeDefines = {
  3996. [ CubeRefractionMapping ]: 'ENVMAP_MODE_REFRACTION'
  3997. };
  3998. function generateEnvMapModeDefine( parameters ) {
  3999. if ( parameters.envMap === false ) return 'ENVMAP_MODE_REFLECTION';
  4000. return envMapModeDefines[ parameters.envMapMode ] || 'ENVMAP_MODE_REFLECTION';
  4001. }
  4002. const envMapBlendingDefines = {
  4003. [ MultiplyOperation ]: 'ENVMAP_BLENDING_MULTIPLY',
  4004. [ MixOperation ]: 'ENVMAP_BLENDING_MIX',
  4005. [ AddOperation ]: 'ENVMAP_BLENDING_ADD'
  4006. };
  4007. function generateEnvMapBlendingDefine( parameters ) {
  4008. if ( parameters.envMap === false ) return 'ENVMAP_BLENDING_NONE';
  4009. return envMapBlendingDefines[ parameters.combine ] || 'ENVMAP_BLENDING_NONE';
  4010. }
  4011. function generateCubeUVSize( parameters ) {
  4012. const imageHeight = parameters.envMapCubeUVHeight;
  4013. if ( imageHeight === null ) return null;
  4014. const maxMip = Math.log2( imageHeight ) - 2;
  4015. const texelHeight = 1.0 / imageHeight;
  4016. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  4017. return { texelWidth, texelHeight, maxMip };
  4018. }
  4019. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  4020. // TODO Send this event to Three.js DevTools
  4021. // log( 'WebGLProgram', cacheKey );
  4022. const gl = renderer.getContext();
  4023. const defines = parameters.defines;
  4024. let vertexShader = parameters.vertexShader;
  4025. let fragmentShader = parameters.fragmentShader;
  4026. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  4027. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  4028. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  4029. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  4030. const envMapCubeUVSize = generateCubeUVSize( parameters );
  4031. const customVertexExtensions = generateVertexExtensions( parameters );
  4032. const customDefines = generateDefines( defines );
  4033. const program = gl.createProgram();
  4034. let prefixVertex, prefixFragment;
  4035. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  4036. if ( parameters.isRawShaderMaterial ) {
  4037. prefixVertex = [
  4038. '#define SHADER_TYPE ' + parameters.shaderType,
  4039. '#define SHADER_NAME ' + parameters.shaderName,
  4040. customDefines
  4041. ].filter( filterEmptyLine ).join( '\n' );
  4042. if ( prefixVertex.length > 0 ) {
  4043. prefixVertex += '\n';
  4044. }
  4045. prefixFragment = [
  4046. '#define SHADER_TYPE ' + parameters.shaderType,
  4047. '#define SHADER_NAME ' + parameters.shaderName,
  4048. customDefines
  4049. ].filter( filterEmptyLine ).join( '\n' );
  4050. if ( prefixFragment.length > 0 ) {
  4051. prefixFragment += '\n';
  4052. }
  4053. } else {
  4054. prefixVertex = [
  4055. generatePrecision( parameters ),
  4056. '#define SHADER_TYPE ' + parameters.shaderType,
  4057. '#define SHADER_NAME ' + parameters.shaderName,
  4058. customDefines,
  4059. parameters.extensionClipCullDistance ? '#define USE_CLIP_DISTANCE' : '',
  4060. parameters.batching ? '#define USE_BATCHING' : '',
  4061. parameters.batchingColor ? '#define USE_BATCHING_COLOR' : '',
  4062. parameters.instancing ? '#define USE_INSTANCING' : '',
  4063. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  4064. parameters.instancingMorph ? '#define USE_INSTANCING_MORPH' : '',
  4065. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  4066. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  4067. parameters.map ? '#define USE_MAP' : '',
  4068. parameters.envMap ? '#define USE_ENVMAP' : '',
  4069. parameters.envMap ? '#define ' + envMapModeDefine : '',
  4070. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  4071. parameters.aoMap ? '#define USE_AOMAP' : '',
  4072. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  4073. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  4074. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  4075. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  4076. parameters.displacementMap ? '#define USE_DISPLACEMENTMAP' : '',
  4077. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  4078. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  4079. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  4080. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  4081. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  4082. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  4083. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  4084. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  4085. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  4086. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  4087. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  4088. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  4089. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  4090. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  4091. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  4092. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  4093. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  4094. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  4095. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  4096. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  4097. //
  4098. parameters.mapUv ? '#define MAP_UV ' + parameters.mapUv : '',
  4099. parameters.alphaMapUv ? '#define ALPHAMAP_UV ' + parameters.alphaMapUv : '',
  4100. parameters.lightMapUv ? '#define LIGHTMAP_UV ' + parameters.lightMapUv : '',
  4101. parameters.aoMapUv ? '#define AOMAP_UV ' + parameters.aoMapUv : '',
  4102. parameters.emissiveMapUv ? '#define EMISSIVEMAP_UV ' + parameters.emissiveMapUv : '',
  4103. parameters.bumpMapUv ? '#define BUMPMAP_UV ' + parameters.bumpMapUv : '',
  4104. parameters.normalMapUv ? '#define NORMALMAP_UV ' + parameters.normalMapUv : '',
  4105. parameters.displacementMapUv ? '#define DISPLACEMENTMAP_UV ' + parameters.displacementMapUv : '',
  4106. parameters.metalnessMapUv ? '#define METALNESSMAP_UV ' + parameters.metalnessMapUv : '',
  4107. parameters.roughnessMapUv ? '#define ROUGHNESSMAP_UV ' + parameters.roughnessMapUv : '',
  4108. parameters.anisotropyMapUv ? '#define ANISOTROPYMAP_UV ' + parameters.anisotropyMapUv : '',
  4109. parameters.clearcoatMapUv ? '#define CLEARCOATMAP_UV ' + parameters.clearcoatMapUv : '',
  4110. parameters.clearcoatNormalMapUv ? '#define CLEARCOAT_NORMALMAP_UV ' + parameters.clearcoatNormalMapUv : '',
  4111. parameters.clearcoatRoughnessMapUv ? '#define CLEARCOAT_ROUGHNESSMAP_UV ' + parameters.clearcoatRoughnessMapUv : '',
  4112. parameters.iridescenceMapUv ? '#define IRIDESCENCEMAP_UV ' + parameters.iridescenceMapUv : '',
  4113. parameters.iridescenceThicknessMapUv ? '#define IRIDESCENCE_THICKNESSMAP_UV ' + parameters.iridescenceThicknessMapUv : '',
  4114. parameters.sheenColorMapUv ? '#define SHEEN_COLORMAP_UV ' + parameters.sheenColorMapUv : '',
  4115. parameters.sheenRoughnessMapUv ? '#define SHEEN_ROUGHNESSMAP_UV ' + parameters.sheenRoughnessMapUv : '',
  4116. parameters.specularMapUv ? '#define SPECULARMAP_UV ' + parameters.specularMapUv : '',
  4117. parameters.specularColorMapUv ? '#define SPECULAR_COLORMAP_UV ' + parameters.specularColorMapUv : '',
  4118. parameters.specularIntensityMapUv ? '#define SPECULAR_INTENSITYMAP_UV ' + parameters.specularIntensityMapUv : '',
  4119. parameters.transmissionMapUv ? '#define TRANSMISSIONMAP_UV ' + parameters.transmissionMapUv : '',
  4120. parameters.thicknessMapUv ? '#define THICKNESSMAP_UV ' + parameters.thicknessMapUv : '',
  4121. //
  4122. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  4123. parameters.vertexColors ? '#define USE_COLOR' : '',
  4124. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  4125. parameters.vertexUv1s ? '#define USE_UV1' : '',
  4126. parameters.vertexUv2s ? '#define USE_UV2' : '',
  4127. parameters.vertexUv3s ? '#define USE_UV3' : '',
  4128. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  4129. parameters.flatShading ? '#define FLAT_SHADED' : '',
  4130. parameters.skinning ? '#define USE_SKINNING' : '',
  4131. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  4132. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  4133. ( parameters.morphColors ) ? '#define USE_MORPHCOLORS' : '',
  4134. ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '',
  4135. ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '',
  4136. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  4137. parameters.flipSided ? '#define FLIP_SIDED' : '',
  4138. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  4139. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  4140. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  4141. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  4142. parameters.logarithmicDepthBuffer ? '#define USE_LOGARITHMIC_DEPTH_BUFFER' : '',
  4143. parameters.reversedDepthBuffer ? '#define USE_REVERSED_DEPTH_BUFFER' : '',
  4144. 'uniform mat4 modelMatrix;',
  4145. 'uniform mat4 modelViewMatrix;',
  4146. 'uniform mat4 projectionMatrix;',
  4147. 'uniform mat4 viewMatrix;',
  4148. 'uniform mat3 normalMatrix;',
  4149. 'uniform vec3 cameraPosition;',
  4150. 'uniform bool isOrthographic;',
  4151. '#ifdef USE_INSTANCING',
  4152. ' attribute mat4 instanceMatrix;',
  4153. '#endif',
  4154. '#ifdef USE_INSTANCING_COLOR',
  4155. ' attribute vec3 instanceColor;',
  4156. '#endif',
  4157. '#ifdef USE_INSTANCING_MORPH',
  4158. ' uniform sampler2D morphTexture;',
  4159. '#endif',
  4160. 'attribute vec3 position;',
  4161. 'attribute vec3 normal;',
  4162. 'attribute vec2 uv;',
  4163. '#ifdef USE_UV1',
  4164. ' attribute vec2 uv1;',
  4165. '#endif',
  4166. '#ifdef USE_UV2',
  4167. ' attribute vec2 uv2;',
  4168. '#endif',
  4169. '#ifdef USE_UV3',
  4170. ' attribute vec2 uv3;',
  4171. '#endif',
  4172. '#ifdef USE_TANGENT',
  4173. ' attribute vec4 tangent;',
  4174. '#endif',
  4175. '#if defined( USE_COLOR_ALPHA )',
  4176. ' attribute vec4 color;',
  4177. '#elif defined( USE_COLOR )',
  4178. ' attribute vec3 color;',
  4179. '#endif',
  4180. '#ifdef USE_SKINNING',
  4181. ' attribute vec4 skinIndex;',
  4182. ' attribute vec4 skinWeight;',
  4183. '#endif',
  4184. '\n'
  4185. ].filter( filterEmptyLine ).join( '\n' );
  4186. prefixFragment = [
  4187. generatePrecision( parameters ),
  4188. '#define SHADER_TYPE ' + parameters.shaderType,
  4189. '#define SHADER_NAME ' + parameters.shaderName,
  4190. customDefines,
  4191. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  4192. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  4193. parameters.alphaToCoverage ? '#define ALPHA_TO_COVERAGE' : '',
  4194. parameters.map ? '#define USE_MAP' : '',
  4195. parameters.matcap ? '#define USE_MATCAP' : '',
  4196. parameters.envMap ? '#define USE_ENVMAP' : '',
  4197. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  4198. parameters.envMap ? '#define ' + envMapModeDefine : '',
  4199. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  4200. envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '',
  4201. envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '',
  4202. envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '',
  4203. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  4204. parameters.aoMap ? '#define USE_AOMAP' : '',
  4205. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  4206. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  4207. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  4208. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  4209. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  4210. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  4211. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  4212. parameters.clearcoat ? '#define USE_CLEARCOAT' : '',
  4213. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  4214. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  4215. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  4216. parameters.dispersion ? '#define USE_DISPERSION' : '',
  4217. parameters.iridescence ? '#define USE_IRIDESCENCE' : '',
  4218. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  4219. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  4220. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  4221. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  4222. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  4223. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  4224. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  4225. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  4226. parameters.alphaTest ? '#define USE_ALPHATEST' : '',
  4227. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  4228. parameters.sheen ? '#define USE_SHEEN' : '',
  4229. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  4230. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  4231. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  4232. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  4233. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  4234. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  4235. parameters.vertexColors || parameters.instancingColor || parameters.batchingColor ? '#define USE_COLOR' : '',
  4236. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  4237. parameters.vertexUv1s ? '#define USE_UV1' : '',
  4238. parameters.vertexUv2s ? '#define USE_UV2' : '',
  4239. parameters.vertexUv3s ? '#define USE_UV3' : '',
  4240. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  4241. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  4242. parameters.flatShading ? '#define FLAT_SHADED' : '',
  4243. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  4244. parameters.flipSided ? '#define FLIP_SIDED' : '',
  4245. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  4246. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  4247. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  4248. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  4249. parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '',
  4250. parameters.decodeVideoTextureEmissive ? '#define DECODE_VIDEO_TEXTURE_EMISSIVE' : '',
  4251. parameters.logarithmicDepthBuffer ? '#define USE_LOGARITHMIC_DEPTH_BUFFER' : '',
  4252. parameters.reversedDepthBuffer ? '#define USE_REVERSED_DEPTH_BUFFER' : '',
  4253. 'uniform mat4 viewMatrix;',
  4254. 'uniform vec3 cameraPosition;',
  4255. 'uniform bool isOrthographic;',
  4256. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  4257. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  4258. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  4259. parameters.dithering ? '#define DITHERING' : '',
  4260. parameters.opaque ? '#define OPAQUE' : '',
  4261. ShaderChunk[ 'colorspace_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  4262. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputColorSpace ),
  4263. getLuminanceFunction(),
  4264. parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  4265. '\n'
  4266. ].filter( filterEmptyLine ).join( '\n' );
  4267. }
  4268. vertexShader = resolveIncludes( vertexShader );
  4269. vertexShader = replaceLightNums( vertexShader, parameters );
  4270. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  4271. fragmentShader = resolveIncludes( fragmentShader );
  4272. fragmentShader = replaceLightNums( fragmentShader, parameters );
  4273. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  4274. vertexShader = unrollLoops( vertexShader );
  4275. fragmentShader = unrollLoops( fragmentShader );
  4276. if ( parameters.isRawShaderMaterial !== true ) {
  4277. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  4278. versionString = '#version 300 es\n';
  4279. prefixVertex = [
  4280. customVertexExtensions,
  4281. '#define attribute in',
  4282. '#define varying out',
  4283. '#define texture2D texture'
  4284. ].join( '\n' ) + '\n' + prefixVertex;
  4285. prefixFragment = [
  4286. '#define varying in',
  4287. ( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;',
  4288. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  4289. '#define gl_FragDepthEXT gl_FragDepth',
  4290. '#define texture2D texture',
  4291. '#define textureCube texture',
  4292. '#define texture2DProj textureProj',
  4293. '#define texture2DLodEXT textureLod',
  4294. '#define texture2DProjLodEXT textureProjLod',
  4295. '#define textureCubeLodEXT textureLod',
  4296. '#define texture2DGradEXT textureGrad',
  4297. '#define texture2DProjGradEXT textureProjGrad',
  4298. '#define textureCubeGradEXT textureGrad'
  4299. ].join( '\n' ) + '\n' + prefixFragment;
  4300. }
  4301. const vertexGlsl = versionString + prefixVertex + vertexShader;
  4302. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  4303. // log( '*VERTEX*', vertexGlsl );
  4304. // log( '*FRAGMENT*', fragmentGlsl );
  4305. const glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  4306. const glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  4307. gl.attachShader( program, glVertexShader );
  4308. gl.attachShader( program, glFragmentShader );
  4309. // Force a particular attribute to index 0.
  4310. if ( parameters.index0AttributeName !== undefined ) {
  4311. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  4312. } else if ( parameters.morphTargets === true ) {
  4313. // programs with morphTargets displace position out of attribute 0
  4314. gl.bindAttribLocation( program, 0, 'position' );
  4315. }
  4316. gl.linkProgram( program );
  4317. function onFirstUse( self ) {
  4318. // check for link errors
  4319. if ( renderer.debug.checkShaderErrors ) {
  4320. const programInfoLog = gl.getProgramInfoLog( program ) || '';
  4321. const vertexShaderInfoLog = gl.getShaderInfoLog( glVertexShader ) || '';
  4322. const fragmentShaderInfoLog = gl.getShaderInfoLog( glFragmentShader ) || '';
  4323. const programLog = programInfoLog.trim();
  4324. const vertexLog = vertexShaderInfoLog.trim();
  4325. const fragmentLog = fragmentShaderInfoLog.trim();
  4326. let runnable = true;
  4327. let haveDiagnostics = true;
  4328. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  4329. runnable = false;
  4330. if ( typeof renderer.debug.onShaderError === 'function' ) {
  4331. renderer.debug.onShaderError( gl, program, glVertexShader, glFragmentShader );
  4332. } else {
  4333. // default error reporting
  4334. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  4335. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  4336. error(
  4337. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  4338. 'VALIDATE_STATUS ' + gl.getProgramParameter( program, gl.VALIDATE_STATUS ) + '\n\n' +
  4339. 'Material Name: ' + self.name + '\n' +
  4340. 'Material Type: ' + self.type + '\n\n' +
  4341. 'Program Info Log: ' + programLog + '\n' +
  4342. vertexErrors + '\n' +
  4343. fragmentErrors
  4344. );
  4345. }
  4346. } else if ( programLog !== '' ) {
  4347. warn( 'WebGLProgram: Program Info Log:', programLog );
  4348. } else if ( vertexLog === '' || fragmentLog === '' ) {
  4349. haveDiagnostics = false;
  4350. }
  4351. if ( haveDiagnostics ) {
  4352. self.diagnostics = {
  4353. runnable: runnable,
  4354. programLog: programLog,
  4355. vertexShader: {
  4356. log: vertexLog,
  4357. prefix: prefixVertex
  4358. },
  4359. fragmentShader: {
  4360. log: fragmentLog,
  4361. prefix: prefixFragment
  4362. }
  4363. };
  4364. }
  4365. }
  4366. // Clean up
  4367. // Crashes in iOS9 and iOS10. #18402
  4368. // gl.detachShader( program, glVertexShader );
  4369. // gl.detachShader( program, glFragmentShader );
  4370. gl.deleteShader( glVertexShader );
  4371. gl.deleteShader( glFragmentShader );
  4372. cachedUniforms = new WebGLUniforms( gl, program );
  4373. cachedAttributes = fetchAttributeLocations( gl, program );
  4374. }
  4375. // set up caching for uniform locations
  4376. let cachedUniforms;
  4377. this.getUniforms = function () {
  4378. if ( cachedUniforms === undefined ) {
  4379. // Populates cachedUniforms and cachedAttributes
  4380. onFirstUse( this );
  4381. }
  4382. return cachedUniforms;
  4383. };
  4384. // set up caching for attribute locations
  4385. let cachedAttributes;
  4386. this.getAttributes = function () {
  4387. if ( cachedAttributes === undefined ) {
  4388. // Populates cachedAttributes and cachedUniforms
  4389. onFirstUse( this );
  4390. }
  4391. return cachedAttributes;
  4392. };
  4393. // indicate when the program is ready to be used. if the KHR_parallel_shader_compile extension isn't supported,
  4394. // flag the program as ready immediately. It may cause a stall when it's first used.
  4395. let programReady = ( parameters.rendererExtensionParallelShaderCompile === false );
  4396. this.isReady = function () {
  4397. if ( programReady === false ) {
  4398. programReady = gl.getProgramParameter( program, COMPLETION_STATUS_KHR );
  4399. }
  4400. return programReady;
  4401. };
  4402. // free resource
  4403. this.destroy = function () {
  4404. bindingStates.releaseStatesOfProgram( this );
  4405. gl.deleteProgram( program );
  4406. this.program = undefined;
  4407. };
  4408. //
  4409. this.type = parameters.shaderType;
  4410. this.name = parameters.shaderName;
  4411. this.id = programIdCount ++;
  4412. this.cacheKey = cacheKey;
  4413. this.usedTimes = 1;
  4414. this.program = program;
  4415. this.vertexShader = glVertexShader;
  4416. this.fragmentShader = glFragmentShader;
  4417. return this;
  4418. }
  4419. let _id = 0;
  4420. class WebGLShaderCache {
  4421. constructor() {
  4422. this.shaderCache = new Map();
  4423. this.materialCache = new Map();
  4424. }
  4425. update( material ) {
  4426. const vertexShader = material.vertexShader;
  4427. const fragmentShader = material.fragmentShader;
  4428. const vertexShaderStage = this._getShaderStage( vertexShader );
  4429. const fragmentShaderStage = this._getShaderStage( fragmentShader );
  4430. const materialShaders = this._getShaderCacheForMaterial( material );
  4431. if ( materialShaders.has( vertexShaderStage ) === false ) {
  4432. materialShaders.add( vertexShaderStage );
  4433. vertexShaderStage.usedTimes ++;
  4434. }
  4435. if ( materialShaders.has( fragmentShaderStage ) === false ) {
  4436. materialShaders.add( fragmentShaderStage );
  4437. fragmentShaderStage.usedTimes ++;
  4438. }
  4439. return this;
  4440. }
  4441. remove( material ) {
  4442. const materialShaders = this.materialCache.get( material );
  4443. for ( const shaderStage of materialShaders ) {
  4444. shaderStage.usedTimes --;
  4445. if ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage.code );
  4446. }
  4447. this.materialCache.delete( material );
  4448. return this;
  4449. }
  4450. getVertexShaderID( material ) {
  4451. return this._getShaderStage( material.vertexShader ).id;
  4452. }
  4453. getFragmentShaderID( material ) {
  4454. return this._getShaderStage( material.fragmentShader ).id;
  4455. }
  4456. dispose() {
  4457. this.shaderCache.clear();
  4458. this.materialCache.clear();
  4459. }
  4460. _getShaderCacheForMaterial( material ) {
  4461. const cache = this.materialCache;
  4462. let set = cache.get( material );
  4463. if ( set === undefined ) {
  4464. set = new Set();
  4465. cache.set( material, set );
  4466. }
  4467. return set;
  4468. }
  4469. _getShaderStage( code ) {
  4470. const cache = this.shaderCache;
  4471. let stage = cache.get( code );
  4472. if ( stage === undefined ) {
  4473. stage = new WebGLShaderStage( code );
  4474. cache.set( code, stage );
  4475. }
  4476. return stage;
  4477. }
  4478. }
  4479. class WebGLShaderStage {
  4480. constructor( code ) {
  4481. this.id = _id ++;
  4482. this.code = code;
  4483. this.usedTimes = 0;
  4484. }
  4485. }
  4486. function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) {
  4487. const _programLayers = new Layers();
  4488. const _customShaders = new WebGLShaderCache();
  4489. const _activeChannels = new Set();
  4490. const programs = [];
  4491. const programsMap = new Map();
  4492. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  4493. let precision = capabilities.precision;
  4494. const shaderIDs = {
  4495. MeshDepthMaterial: 'depth',
  4496. MeshDistanceMaterial: 'distance',
  4497. MeshNormalMaterial: 'normal',
  4498. MeshBasicMaterial: 'basic',
  4499. MeshLambertMaterial: 'lambert',
  4500. MeshPhongMaterial: 'phong',
  4501. MeshToonMaterial: 'toon',
  4502. MeshStandardMaterial: 'physical',
  4503. MeshPhysicalMaterial: 'physical',
  4504. MeshMatcapMaterial: 'matcap',
  4505. LineBasicMaterial: 'basic',
  4506. LineDashedMaterial: 'dashed',
  4507. PointsMaterial: 'points',
  4508. ShadowMaterial: 'shadow',
  4509. SpriteMaterial: 'sprite'
  4510. };
  4511. function getChannel( value ) {
  4512. _activeChannels.add( value );
  4513. if ( value === 0 ) return 'uv';
  4514. return `uv${ value }`;
  4515. }
  4516. function getParameters( material, lights, shadows, scene, object ) {
  4517. const fog = scene.fog;
  4518. const geometry = object.geometry;
  4519. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  4520. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  4521. const envMapCubeUVHeight = ( !! envMap ) && ( envMap.mapping === CubeUVReflectionMapping ) ? envMap.image.height : null;
  4522. const shaderID = shaderIDs[ material.type ];
  4523. // heuristics to create shader parameters according to lights in the scene
  4524. // (not to blow over maxLights budget)
  4525. if ( material.precision !== null ) {
  4526. precision = capabilities.getMaxPrecision( material.precision );
  4527. if ( precision !== material.precision ) {
  4528. warn( 'WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  4529. }
  4530. }
  4531. //
  4532. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  4533. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  4534. let morphTextureStride = 0;
  4535. if ( geometry.morphAttributes.position !== undefined ) morphTextureStride = 1;
  4536. if ( geometry.morphAttributes.normal !== undefined ) morphTextureStride = 2;
  4537. if ( geometry.morphAttributes.color !== undefined ) morphTextureStride = 3;
  4538. //
  4539. let vertexShader, fragmentShader;
  4540. let customVertexShaderID, customFragmentShaderID;
  4541. if ( shaderID ) {
  4542. const shader = ShaderLib[ shaderID ];
  4543. vertexShader = shader.vertexShader;
  4544. fragmentShader = shader.fragmentShader;
  4545. } else {
  4546. vertexShader = material.vertexShader;
  4547. fragmentShader = material.fragmentShader;
  4548. _customShaders.update( material );
  4549. customVertexShaderID = _customShaders.getVertexShaderID( material );
  4550. customFragmentShaderID = _customShaders.getFragmentShaderID( material );
  4551. }
  4552. const currentRenderTarget = renderer.getRenderTarget();
  4553. const reversedDepthBuffer = renderer.state.buffers.depth.getReversed();
  4554. const IS_INSTANCEDMESH = object.isInstancedMesh === true;
  4555. const IS_BATCHEDMESH = object.isBatchedMesh === true;
  4556. const HAS_MAP = !! material.map;
  4557. const HAS_MATCAP = !! material.matcap;
  4558. const HAS_ENVMAP = !! envMap;
  4559. const HAS_AOMAP = !! material.aoMap;
  4560. const HAS_LIGHTMAP = !! material.lightMap;
  4561. const HAS_BUMPMAP = !! material.bumpMap;
  4562. const HAS_NORMALMAP = !! material.normalMap;
  4563. const HAS_DISPLACEMENTMAP = !! material.displacementMap;
  4564. const HAS_EMISSIVEMAP = !! material.emissiveMap;
  4565. const HAS_METALNESSMAP = !! material.metalnessMap;
  4566. const HAS_ROUGHNESSMAP = !! material.roughnessMap;
  4567. const HAS_ANISOTROPY = material.anisotropy > 0;
  4568. const HAS_CLEARCOAT = material.clearcoat > 0;
  4569. const HAS_DISPERSION = material.dispersion > 0;
  4570. const HAS_IRIDESCENCE = material.iridescence > 0;
  4571. const HAS_SHEEN = material.sheen > 0;
  4572. const HAS_TRANSMISSION = material.transmission > 0;
  4573. const HAS_ANISOTROPYMAP = HAS_ANISOTROPY && !! material.anisotropyMap;
  4574. const HAS_CLEARCOATMAP = HAS_CLEARCOAT && !! material.clearcoatMap;
  4575. const HAS_CLEARCOAT_NORMALMAP = HAS_CLEARCOAT && !! material.clearcoatNormalMap;
  4576. const HAS_CLEARCOAT_ROUGHNESSMAP = HAS_CLEARCOAT && !! material.clearcoatRoughnessMap;
  4577. const HAS_IRIDESCENCEMAP = HAS_IRIDESCENCE && !! material.iridescenceMap;
  4578. const HAS_IRIDESCENCE_THICKNESSMAP = HAS_IRIDESCENCE && !! material.iridescenceThicknessMap;
  4579. const HAS_SHEEN_COLORMAP = HAS_SHEEN && !! material.sheenColorMap;
  4580. const HAS_SHEEN_ROUGHNESSMAP = HAS_SHEEN && !! material.sheenRoughnessMap;
  4581. const HAS_SPECULARMAP = !! material.specularMap;
  4582. const HAS_SPECULAR_COLORMAP = !! material.specularColorMap;
  4583. const HAS_SPECULAR_INTENSITYMAP = !! material.specularIntensityMap;
  4584. const HAS_TRANSMISSIONMAP = HAS_TRANSMISSION && !! material.transmissionMap;
  4585. const HAS_THICKNESSMAP = HAS_TRANSMISSION && !! material.thicknessMap;
  4586. const HAS_GRADIENTMAP = !! material.gradientMap;
  4587. const HAS_ALPHAMAP = !! material.alphaMap;
  4588. const HAS_ALPHATEST = material.alphaTest > 0;
  4589. const HAS_ALPHAHASH = !! material.alphaHash;
  4590. const HAS_EXTENSIONS = !! material.extensions;
  4591. let toneMapping = NoToneMapping;
  4592. if ( material.toneMapped ) {
  4593. if ( currentRenderTarget === null || currentRenderTarget.isXRRenderTarget === true ) {
  4594. toneMapping = renderer.toneMapping;
  4595. }
  4596. }
  4597. const parameters = {
  4598. shaderID: shaderID,
  4599. shaderType: material.type,
  4600. shaderName: material.name,
  4601. vertexShader: vertexShader,
  4602. fragmentShader: fragmentShader,
  4603. defines: material.defines,
  4604. customVertexShaderID: customVertexShaderID,
  4605. customFragmentShaderID: customFragmentShaderID,
  4606. isRawShaderMaterial: material.isRawShaderMaterial === true,
  4607. glslVersion: material.glslVersion,
  4608. precision: precision,
  4609. batching: IS_BATCHEDMESH,
  4610. batchingColor: IS_BATCHEDMESH && object._colorsTexture !== null,
  4611. instancing: IS_INSTANCEDMESH,
  4612. instancingColor: IS_INSTANCEDMESH && object.instanceColor !== null,
  4613. instancingMorph: IS_INSTANCEDMESH && object.morphTexture !== null,
  4614. outputColorSpace: ( currentRenderTarget === null ) ? renderer.outputColorSpace : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace ),
  4615. alphaToCoverage: !! material.alphaToCoverage,
  4616. map: HAS_MAP,
  4617. matcap: HAS_MATCAP,
  4618. envMap: HAS_ENVMAP,
  4619. envMapMode: HAS_ENVMAP && envMap.mapping,
  4620. envMapCubeUVHeight: envMapCubeUVHeight,
  4621. aoMap: HAS_AOMAP,
  4622. lightMap: HAS_LIGHTMAP,
  4623. bumpMap: HAS_BUMPMAP,
  4624. normalMap: HAS_NORMALMAP,
  4625. displacementMap: HAS_DISPLACEMENTMAP,
  4626. emissiveMap: HAS_EMISSIVEMAP,
  4627. normalMapObjectSpace: HAS_NORMALMAP && material.normalMapType === ObjectSpaceNormalMap,
  4628. normalMapTangentSpace: HAS_NORMALMAP && material.normalMapType === TangentSpaceNormalMap,
  4629. metalnessMap: HAS_METALNESSMAP,
  4630. roughnessMap: HAS_ROUGHNESSMAP,
  4631. anisotropy: HAS_ANISOTROPY,
  4632. anisotropyMap: HAS_ANISOTROPYMAP,
  4633. clearcoat: HAS_CLEARCOAT,
  4634. clearcoatMap: HAS_CLEARCOATMAP,
  4635. clearcoatNormalMap: HAS_CLEARCOAT_NORMALMAP,
  4636. clearcoatRoughnessMap: HAS_CLEARCOAT_ROUGHNESSMAP,
  4637. dispersion: HAS_DISPERSION,
  4638. iridescence: HAS_IRIDESCENCE,
  4639. iridescenceMap: HAS_IRIDESCENCEMAP,
  4640. iridescenceThicknessMap: HAS_IRIDESCENCE_THICKNESSMAP,
  4641. sheen: HAS_SHEEN,
  4642. sheenColorMap: HAS_SHEEN_COLORMAP,
  4643. sheenRoughnessMap: HAS_SHEEN_ROUGHNESSMAP,
  4644. specularMap: HAS_SPECULARMAP,
  4645. specularColorMap: HAS_SPECULAR_COLORMAP,
  4646. specularIntensityMap: HAS_SPECULAR_INTENSITYMAP,
  4647. transmission: HAS_TRANSMISSION,
  4648. transmissionMap: HAS_TRANSMISSIONMAP,
  4649. thicknessMap: HAS_THICKNESSMAP,
  4650. gradientMap: HAS_GRADIENTMAP,
  4651. opaque: material.transparent === false && material.blending === NormalBlending && material.alphaToCoverage === false,
  4652. alphaMap: HAS_ALPHAMAP,
  4653. alphaTest: HAS_ALPHATEST,
  4654. alphaHash: HAS_ALPHAHASH,
  4655. combine: material.combine,
  4656. //
  4657. mapUv: HAS_MAP && getChannel( material.map.channel ),
  4658. aoMapUv: HAS_AOMAP && getChannel( material.aoMap.channel ),
  4659. lightMapUv: HAS_LIGHTMAP && getChannel( material.lightMap.channel ),
  4660. bumpMapUv: HAS_BUMPMAP && getChannel( material.bumpMap.channel ),
  4661. normalMapUv: HAS_NORMALMAP && getChannel( material.normalMap.channel ),
  4662. displacementMapUv: HAS_DISPLACEMENTMAP && getChannel( material.displacementMap.channel ),
  4663. emissiveMapUv: HAS_EMISSIVEMAP && getChannel( material.emissiveMap.channel ),
  4664. metalnessMapUv: HAS_METALNESSMAP && getChannel( material.metalnessMap.channel ),
  4665. roughnessMapUv: HAS_ROUGHNESSMAP && getChannel( material.roughnessMap.channel ),
  4666. anisotropyMapUv: HAS_ANISOTROPYMAP && getChannel( material.anisotropyMap.channel ),
  4667. clearcoatMapUv: HAS_CLEARCOATMAP && getChannel( material.clearcoatMap.channel ),
  4668. clearcoatNormalMapUv: HAS_CLEARCOAT_NORMALMAP && getChannel( material.clearcoatNormalMap.channel ),
  4669. clearcoatRoughnessMapUv: HAS_CLEARCOAT_ROUGHNESSMAP && getChannel( material.clearcoatRoughnessMap.channel ),
  4670. iridescenceMapUv: HAS_IRIDESCENCEMAP && getChannel( material.iridescenceMap.channel ),
  4671. iridescenceThicknessMapUv: HAS_IRIDESCENCE_THICKNESSMAP && getChannel( material.iridescenceThicknessMap.channel ),
  4672. sheenColorMapUv: HAS_SHEEN_COLORMAP && getChannel( material.sheenColorMap.channel ),
  4673. sheenRoughnessMapUv: HAS_SHEEN_ROUGHNESSMAP && getChannel( material.sheenRoughnessMap.channel ),
  4674. specularMapUv: HAS_SPECULARMAP && getChannel( material.specularMap.channel ),
  4675. specularColorMapUv: HAS_SPECULAR_COLORMAP && getChannel( material.specularColorMap.channel ),
  4676. specularIntensityMapUv: HAS_SPECULAR_INTENSITYMAP && getChannel( material.specularIntensityMap.channel ),
  4677. transmissionMapUv: HAS_TRANSMISSIONMAP && getChannel( material.transmissionMap.channel ),
  4678. thicknessMapUv: HAS_THICKNESSMAP && getChannel( material.thicknessMap.channel ),
  4679. alphaMapUv: HAS_ALPHAMAP && getChannel( material.alphaMap.channel ),
  4680. //
  4681. vertexTangents: !! geometry.attributes.tangent && ( HAS_NORMALMAP || HAS_ANISOTROPY ),
  4682. vertexColors: material.vertexColors,
  4683. vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4,
  4684. pointsUvs: object.isPoints === true && !! geometry.attributes.uv && ( HAS_MAP || HAS_ALPHAMAP ),
  4685. fog: !! fog,
  4686. useFog: material.fog === true,
  4687. fogExp2: ( !! fog && fog.isFogExp2 ),
  4688. flatShading: ( material.flatShading === true && material.wireframe === false ),
  4689. sizeAttenuation: material.sizeAttenuation === true,
  4690. logarithmicDepthBuffer: logarithmicDepthBuffer,
  4691. reversedDepthBuffer: reversedDepthBuffer,
  4692. skinning: object.isSkinnedMesh === true,
  4693. morphTargets: geometry.morphAttributes.position !== undefined,
  4694. morphNormals: geometry.morphAttributes.normal !== undefined,
  4695. morphColors: geometry.morphAttributes.color !== undefined,
  4696. morphTargetsCount: morphTargetsCount,
  4697. morphTextureStride: morphTextureStride,
  4698. numDirLights: lights.directional.length,
  4699. numPointLights: lights.point.length,
  4700. numSpotLights: lights.spot.length,
  4701. numSpotLightMaps: lights.spotLightMap.length,
  4702. numRectAreaLights: lights.rectArea.length,
  4703. numHemiLights: lights.hemi.length,
  4704. numDirLightShadows: lights.directionalShadowMap.length,
  4705. numPointLightShadows: lights.pointShadowMap.length,
  4706. numSpotLightShadows: lights.spotShadowMap.length,
  4707. numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps,
  4708. numLightProbes: lights.numLightProbes,
  4709. numClippingPlanes: clipping.numPlanes,
  4710. numClipIntersection: clipping.numIntersection,
  4711. dithering: material.dithering,
  4712. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  4713. shadowMapType: renderer.shadowMap.type,
  4714. toneMapping: toneMapping,
  4715. decodeVideoTexture: HAS_MAP && ( material.map.isVideoTexture === true ) && ( ColorManagement.getTransfer( material.map.colorSpace ) === SRGBTransfer ),
  4716. decodeVideoTextureEmissive: HAS_EMISSIVEMAP && ( material.emissiveMap.isVideoTexture === true ) && ( ColorManagement.getTransfer( material.emissiveMap.colorSpace ) === SRGBTransfer ),
  4717. premultipliedAlpha: material.premultipliedAlpha,
  4718. doubleSided: material.side === DoubleSide,
  4719. flipSided: material.side === BackSide,
  4720. useDepthPacking: material.depthPacking >= 0,
  4721. depthPacking: material.depthPacking || 0,
  4722. index0AttributeName: material.index0AttributeName,
  4723. extensionClipCullDistance: HAS_EXTENSIONS && material.extensions.clipCullDistance === true && extensions.has( 'WEBGL_clip_cull_distance' ),
  4724. extensionMultiDraw: ( HAS_EXTENSIONS && material.extensions.multiDraw === true || IS_BATCHEDMESH ) && extensions.has( 'WEBGL_multi_draw' ),
  4725. rendererExtensionParallelShaderCompile: extensions.has( 'KHR_parallel_shader_compile' ),
  4726. customProgramCacheKey: material.customProgramCacheKey()
  4727. };
  4728. // the usage of getChannel() determines the active texture channels for this shader
  4729. parameters.vertexUv1s = _activeChannels.has( 1 );
  4730. parameters.vertexUv2s = _activeChannels.has( 2 );
  4731. parameters.vertexUv3s = _activeChannels.has( 3 );
  4732. _activeChannels.clear();
  4733. return parameters;
  4734. }
  4735. function getProgramCacheKey( parameters ) {
  4736. const array = [];
  4737. if ( parameters.shaderID ) {
  4738. array.push( parameters.shaderID );
  4739. } else {
  4740. array.push( parameters.customVertexShaderID );
  4741. array.push( parameters.customFragmentShaderID );
  4742. }
  4743. if ( parameters.defines !== undefined ) {
  4744. for ( const name in parameters.defines ) {
  4745. array.push( name );
  4746. array.push( parameters.defines[ name ] );
  4747. }
  4748. }
  4749. if ( parameters.isRawShaderMaterial === false ) {
  4750. getProgramCacheKeyParameters( array, parameters );
  4751. getProgramCacheKeyBooleans( array, parameters );
  4752. array.push( renderer.outputColorSpace );
  4753. }
  4754. array.push( parameters.customProgramCacheKey );
  4755. return array.join();
  4756. }
  4757. function getProgramCacheKeyParameters( array, parameters ) {
  4758. array.push( parameters.precision );
  4759. array.push( parameters.outputColorSpace );
  4760. array.push( parameters.envMapMode );
  4761. array.push( parameters.envMapCubeUVHeight );
  4762. array.push( parameters.mapUv );
  4763. array.push( parameters.alphaMapUv );
  4764. array.push( parameters.lightMapUv );
  4765. array.push( parameters.aoMapUv );
  4766. array.push( parameters.bumpMapUv );
  4767. array.push( parameters.normalMapUv );
  4768. array.push( parameters.displacementMapUv );
  4769. array.push( parameters.emissiveMapUv );
  4770. array.push( parameters.metalnessMapUv );
  4771. array.push( parameters.roughnessMapUv );
  4772. array.push( parameters.anisotropyMapUv );
  4773. array.push( parameters.clearcoatMapUv );
  4774. array.push( parameters.clearcoatNormalMapUv );
  4775. array.push( parameters.clearcoatRoughnessMapUv );
  4776. array.push( parameters.iridescenceMapUv );
  4777. array.push( parameters.iridescenceThicknessMapUv );
  4778. array.push( parameters.sheenColorMapUv );
  4779. array.push( parameters.sheenRoughnessMapUv );
  4780. array.push( parameters.specularMapUv );
  4781. array.push( parameters.specularColorMapUv );
  4782. array.push( parameters.specularIntensityMapUv );
  4783. array.push( parameters.transmissionMapUv );
  4784. array.push( parameters.thicknessMapUv );
  4785. array.push( parameters.combine );
  4786. array.push( parameters.fogExp2 );
  4787. array.push( parameters.sizeAttenuation );
  4788. array.push( parameters.morphTargetsCount );
  4789. array.push( parameters.morphAttributeCount );
  4790. array.push( parameters.numDirLights );
  4791. array.push( parameters.numPointLights );
  4792. array.push( parameters.numSpotLights );
  4793. array.push( parameters.numSpotLightMaps );
  4794. array.push( parameters.numHemiLights );
  4795. array.push( parameters.numRectAreaLights );
  4796. array.push( parameters.numDirLightShadows );
  4797. array.push( parameters.numPointLightShadows );
  4798. array.push( parameters.numSpotLightShadows );
  4799. array.push( parameters.numSpotLightShadowsWithMaps );
  4800. array.push( parameters.numLightProbes );
  4801. array.push( parameters.shadowMapType );
  4802. array.push( parameters.toneMapping );
  4803. array.push( parameters.numClippingPlanes );
  4804. array.push( parameters.numClipIntersection );
  4805. array.push( parameters.depthPacking );
  4806. }
  4807. function getProgramCacheKeyBooleans( array, parameters ) {
  4808. _programLayers.disableAll();
  4809. if ( parameters.instancing )
  4810. _programLayers.enable( 0 );
  4811. if ( parameters.instancingColor )
  4812. _programLayers.enable( 1 );
  4813. if ( parameters.instancingMorph )
  4814. _programLayers.enable( 2 );
  4815. if ( parameters.matcap )
  4816. _programLayers.enable( 3 );
  4817. if ( parameters.envMap )
  4818. _programLayers.enable( 4 );
  4819. if ( parameters.normalMapObjectSpace )
  4820. _programLayers.enable( 5 );
  4821. if ( parameters.normalMapTangentSpace )
  4822. _programLayers.enable( 6 );
  4823. if ( parameters.clearcoat )
  4824. _programLayers.enable( 7 );
  4825. if ( parameters.iridescence )
  4826. _programLayers.enable( 8 );
  4827. if ( parameters.alphaTest )
  4828. _programLayers.enable( 9 );
  4829. if ( parameters.vertexColors )
  4830. _programLayers.enable( 10 );
  4831. if ( parameters.vertexAlphas )
  4832. _programLayers.enable( 11 );
  4833. if ( parameters.vertexUv1s )
  4834. _programLayers.enable( 12 );
  4835. if ( parameters.vertexUv2s )
  4836. _programLayers.enable( 13 );
  4837. if ( parameters.vertexUv3s )
  4838. _programLayers.enable( 14 );
  4839. if ( parameters.vertexTangents )
  4840. _programLayers.enable( 15 );
  4841. if ( parameters.anisotropy )
  4842. _programLayers.enable( 16 );
  4843. if ( parameters.alphaHash )
  4844. _programLayers.enable( 17 );
  4845. if ( parameters.batching )
  4846. _programLayers.enable( 18 );
  4847. if ( parameters.dispersion )
  4848. _programLayers.enable( 19 );
  4849. if ( parameters.batchingColor )
  4850. _programLayers.enable( 20 );
  4851. if ( parameters.gradientMap )
  4852. _programLayers.enable( 21 );
  4853. array.push( _programLayers.mask );
  4854. _programLayers.disableAll();
  4855. if ( parameters.fog )
  4856. _programLayers.enable( 0 );
  4857. if ( parameters.useFog )
  4858. _programLayers.enable( 1 );
  4859. if ( parameters.flatShading )
  4860. _programLayers.enable( 2 );
  4861. if ( parameters.logarithmicDepthBuffer )
  4862. _programLayers.enable( 3 );
  4863. if ( parameters.reversedDepthBuffer )
  4864. _programLayers.enable( 4 );
  4865. if ( parameters.skinning )
  4866. _programLayers.enable( 5 );
  4867. if ( parameters.morphTargets )
  4868. _programLayers.enable( 6 );
  4869. if ( parameters.morphNormals )
  4870. _programLayers.enable( 7 );
  4871. if ( parameters.morphColors )
  4872. _programLayers.enable( 8 );
  4873. if ( parameters.premultipliedAlpha )
  4874. _programLayers.enable( 9 );
  4875. if ( parameters.shadowMapEnabled )
  4876. _programLayers.enable( 10 );
  4877. if ( parameters.doubleSided )
  4878. _programLayers.enable( 11 );
  4879. if ( parameters.flipSided )
  4880. _programLayers.enable( 12 );
  4881. if ( parameters.useDepthPacking )
  4882. _programLayers.enable( 13 );
  4883. if ( parameters.dithering )
  4884. _programLayers.enable( 14 );
  4885. if ( parameters.transmission )
  4886. _programLayers.enable( 15 );
  4887. if ( parameters.sheen )
  4888. _programLayers.enable( 16 );
  4889. if ( parameters.opaque )
  4890. _programLayers.enable( 17 );
  4891. if ( parameters.pointsUvs )
  4892. _programLayers.enable( 18 );
  4893. if ( parameters.decodeVideoTexture )
  4894. _programLayers.enable( 19 );
  4895. if ( parameters.decodeVideoTextureEmissive )
  4896. _programLayers.enable( 20 );
  4897. if ( parameters.alphaToCoverage )
  4898. _programLayers.enable( 21 );
  4899. array.push( _programLayers.mask );
  4900. }
  4901. function getUniforms( material ) {
  4902. const shaderID = shaderIDs[ material.type ];
  4903. let uniforms;
  4904. if ( shaderID ) {
  4905. const shader = ShaderLib[ shaderID ];
  4906. uniforms = UniformsUtils.clone( shader.uniforms );
  4907. } else {
  4908. uniforms = material.uniforms;
  4909. }
  4910. return uniforms;
  4911. }
  4912. function acquireProgram( parameters, cacheKey ) {
  4913. let program = programsMap.get( cacheKey );
  4914. if ( program !== undefined ) {
  4915. ++ program.usedTimes;
  4916. } else {
  4917. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  4918. programs.push( program );
  4919. programsMap.set( cacheKey, program );
  4920. }
  4921. return program;
  4922. }
  4923. function releaseProgram( program ) {
  4924. if ( -- program.usedTimes === 0 ) {
  4925. // Remove from unordered set
  4926. const i = programs.indexOf( program );
  4927. programs[ i ] = programs[ programs.length - 1 ];
  4928. programs.pop();
  4929. // Remove from map
  4930. programsMap.delete( program.cacheKey );
  4931. // Free WebGL resources
  4932. program.destroy();
  4933. }
  4934. }
  4935. function releaseShaderCache( material ) {
  4936. _customShaders.remove( material );
  4937. }
  4938. function dispose() {
  4939. _customShaders.dispose();
  4940. }
  4941. return {
  4942. getParameters: getParameters,
  4943. getProgramCacheKey: getProgramCacheKey,
  4944. getUniforms: getUniforms,
  4945. acquireProgram: acquireProgram,
  4946. releaseProgram: releaseProgram,
  4947. releaseShaderCache: releaseShaderCache,
  4948. // Exposed for resource monitoring & error feedback via renderer.info:
  4949. programs: programs,
  4950. dispose: dispose
  4951. };
  4952. }
  4953. function WebGLProperties() {
  4954. let properties = new WeakMap();
  4955. function has( object ) {
  4956. return properties.has( object );
  4957. }
  4958. function get( object ) {
  4959. let map = properties.get( object );
  4960. if ( map === undefined ) {
  4961. map = {};
  4962. properties.set( object, map );
  4963. }
  4964. return map;
  4965. }
  4966. function remove( object ) {
  4967. properties.delete( object );
  4968. }
  4969. function update( object, key, value ) {
  4970. properties.get( object )[ key ] = value;
  4971. }
  4972. function dispose() {
  4973. properties = new WeakMap();
  4974. }
  4975. return {
  4976. has: has,
  4977. get: get,
  4978. remove: remove,
  4979. update: update,
  4980. dispose: dispose
  4981. };
  4982. }
  4983. function painterSortStable( a, b ) {
  4984. if ( a.groupOrder !== b.groupOrder ) {
  4985. return a.groupOrder - b.groupOrder;
  4986. } else if ( a.renderOrder !== b.renderOrder ) {
  4987. return a.renderOrder - b.renderOrder;
  4988. } else if ( a.material.id !== b.material.id ) {
  4989. return a.material.id - b.material.id;
  4990. } else if ( a.materialVariant !== b.materialVariant ) {
  4991. return a.materialVariant - b.materialVariant;
  4992. } else if ( a.z !== b.z ) {
  4993. return a.z - b.z;
  4994. } else {
  4995. return a.id - b.id;
  4996. }
  4997. }
  4998. function reversePainterSortStable( a, b ) {
  4999. if ( a.groupOrder !== b.groupOrder ) {
  5000. return a.groupOrder - b.groupOrder;
  5001. } else if ( a.renderOrder !== b.renderOrder ) {
  5002. return a.renderOrder - b.renderOrder;
  5003. } else if ( a.z !== b.z ) {
  5004. return b.z - a.z;
  5005. } else {
  5006. return a.id - b.id;
  5007. }
  5008. }
  5009. function WebGLRenderList() {
  5010. const renderItems = [];
  5011. let renderItemsIndex = 0;
  5012. const opaque = [];
  5013. const transmissive = [];
  5014. const transparent = [];
  5015. function init() {
  5016. renderItemsIndex = 0;
  5017. opaque.length = 0;
  5018. transmissive.length = 0;
  5019. transparent.length = 0;
  5020. }
  5021. function materialVariant( object ) {
  5022. let variant = 0;
  5023. if ( object.isInstancedMesh ) variant += 2;
  5024. if ( object.isSkinnedMesh ) variant += 1;
  5025. return variant;
  5026. }
  5027. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  5028. let renderItem = renderItems[ renderItemsIndex ];
  5029. if ( renderItem === undefined ) {
  5030. renderItem = {
  5031. id: object.id,
  5032. object: object,
  5033. geometry: geometry,
  5034. material: material,
  5035. materialVariant: materialVariant( object ),
  5036. groupOrder: groupOrder,
  5037. renderOrder: object.renderOrder,
  5038. z: z,
  5039. group: group
  5040. };
  5041. renderItems[ renderItemsIndex ] = renderItem;
  5042. } else {
  5043. renderItem.id = object.id;
  5044. renderItem.object = object;
  5045. renderItem.geometry = geometry;
  5046. renderItem.material = material;
  5047. renderItem.materialVariant = materialVariant( object );
  5048. renderItem.groupOrder = groupOrder;
  5049. renderItem.renderOrder = object.renderOrder;
  5050. renderItem.z = z;
  5051. renderItem.group = group;
  5052. }
  5053. renderItemsIndex ++;
  5054. return renderItem;
  5055. }
  5056. function push( object, geometry, material, groupOrder, z, group ) {
  5057. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  5058. if ( material.transmission > 0.0 ) {
  5059. transmissive.push( renderItem );
  5060. } else if ( material.transparent === true ) {
  5061. transparent.push( renderItem );
  5062. } else {
  5063. opaque.push( renderItem );
  5064. }
  5065. }
  5066. function unshift( object, geometry, material, groupOrder, z, group ) {
  5067. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  5068. if ( material.transmission > 0.0 ) {
  5069. transmissive.unshift( renderItem );
  5070. } else if ( material.transparent === true ) {
  5071. transparent.unshift( renderItem );
  5072. } else {
  5073. opaque.unshift( renderItem );
  5074. }
  5075. }
  5076. function sort( customOpaqueSort, customTransparentSort ) {
  5077. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  5078. if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable );
  5079. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  5080. }
  5081. function finish() {
  5082. // Clear references from inactive renderItems in the list
  5083. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  5084. const renderItem = renderItems[ i ];
  5085. if ( renderItem.id === null ) break;
  5086. renderItem.id = null;
  5087. renderItem.object = null;
  5088. renderItem.geometry = null;
  5089. renderItem.material = null;
  5090. renderItem.group = null;
  5091. }
  5092. }
  5093. return {
  5094. opaque: opaque,
  5095. transmissive: transmissive,
  5096. transparent: transparent,
  5097. init: init,
  5098. push: push,
  5099. unshift: unshift,
  5100. finish: finish,
  5101. sort: sort
  5102. };
  5103. }
  5104. function WebGLRenderLists() {
  5105. let lists = new WeakMap();
  5106. function get( scene, renderCallDepth ) {
  5107. const listArray = lists.get( scene );
  5108. let list;
  5109. if ( listArray === undefined ) {
  5110. list = new WebGLRenderList();
  5111. lists.set( scene, [ list ] );
  5112. } else {
  5113. if ( renderCallDepth >= listArray.length ) {
  5114. list = new WebGLRenderList();
  5115. listArray.push( list );
  5116. } else {
  5117. list = listArray[ renderCallDepth ];
  5118. }
  5119. }
  5120. return list;
  5121. }
  5122. function dispose() {
  5123. lists = new WeakMap();
  5124. }
  5125. return {
  5126. get: get,
  5127. dispose: dispose
  5128. };
  5129. }
  5130. function UniformsCache() {
  5131. const lights = {};
  5132. return {
  5133. get: function ( light ) {
  5134. if ( lights[ light.id ] !== undefined ) {
  5135. return lights[ light.id ];
  5136. }
  5137. let uniforms;
  5138. switch ( light.type ) {
  5139. case 'DirectionalLight':
  5140. uniforms = {
  5141. direction: new Vector3(),
  5142. color: new Color()
  5143. };
  5144. break;
  5145. case 'SpotLight':
  5146. uniforms = {
  5147. position: new Vector3(),
  5148. direction: new Vector3(),
  5149. color: new Color(),
  5150. distance: 0,
  5151. coneCos: 0,
  5152. penumbraCos: 0,
  5153. decay: 0
  5154. };
  5155. break;
  5156. case 'PointLight':
  5157. uniforms = {
  5158. position: new Vector3(),
  5159. color: new Color(),
  5160. distance: 0,
  5161. decay: 0
  5162. };
  5163. break;
  5164. case 'HemisphereLight':
  5165. uniforms = {
  5166. direction: new Vector3(),
  5167. skyColor: new Color(),
  5168. groundColor: new Color()
  5169. };
  5170. break;
  5171. case 'RectAreaLight':
  5172. uniforms = {
  5173. color: new Color(),
  5174. position: new Vector3(),
  5175. halfWidth: new Vector3(),
  5176. halfHeight: new Vector3()
  5177. };
  5178. break;
  5179. }
  5180. lights[ light.id ] = uniforms;
  5181. return uniforms;
  5182. }
  5183. };
  5184. }
  5185. function ShadowUniformsCache() {
  5186. const lights = {};
  5187. return {
  5188. get: function ( light ) {
  5189. if ( lights[ light.id ] !== undefined ) {
  5190. return lights[ light.id ];
  5191. }
  5192. let uniforms;
  5193. switch ( light.type ) {
  5194. case 'DirectionalLight':
  5195. uniforms = {
  5196. shadowIntensity: 1,
  5197. shadowBias: 0,
  5198. shadowNormalBias: 0,
  5199. shadowRadius: 1,
  5200. shadowMapSize: new Vector2()
  5201. };
  5202. break;
  5203. case 'SpotLight':
  5204. uniforms = {
  5205. shadowIntensity: 1,
  5206. shadowBias: 0,
  5207. shadowNormalBias: 0,
  5208. shadowRadius: 1,
  5209. shadowMapSize: new Vector2()
  5210. };
  5211. break;
  5212. case 'PointLight':
  5213. uniforms = {
  5214. shadowIntensity: 1,
  5215. shadowBias: 0,
  5216. shadowNormalBias: 0,
  5217. shadowRadius: 1,
  5218. shadowMapSize: new Vector2(),
  5219. shadowCameraNear: 1,
  5220. shadowCameraFar: 1000
  5221. };
  5222. break;
  5223. // TODO (abelnation): set RectAreaLight shadow uniforms
  5224. }
  5225. lights[ light.id ] = uniforms;
  5226. return uniforms;
  5227. }
  5228. };
  5229. }
  5230. let nextVersion = 0;
  5231. function shadowCastingAndTexturingLightsFirst( lightA, lightB ) {
  5232. return ( lightB.castShadow ? 2 : 0 ) - ( lightA.castShadow ? 2 : 0 ) + ( lightB.map ? 1 : 0 ) - ( lightA.map ? 1 : 0 );
  5233. }
  5234. function WebGLLights( extensions ) {
  5235. const cache = new UniformsCache();
  5236. const shadowCache = ShadowUniformsCache();
  5237. const state = {
  5238. version: 0,
  5239. hash: {
  5240. directionalLength: -1,
  5241. pointLength: -1,
  5242. spotLength: -1,
  5243. rectAreaLength: -1,
  5244. hemiLength: -1,
  5245. numDirectionalShadows: -1,
  5246. numPointShadows: -1,
  5247. numSpotShadows: -1,
  5248. numSpotMaps: -1,
  5249. numLightProbes: -1
  5250. },
  5251. ambient: [ 0, 0, 0 ],
  5252. probe: [],
  5253. directional: [],
  5254. directionalShadow: [],
  5255. directionalShadowMap: [],
  5256. directionalShadowMatrix: [],
  5257. spot: [],
  5258. spotLightMap: [],
  5259. spotShadow: [],
  5260. spotShadowMap: [],
  5261. spotLightMatrix: [],
  5262. rectArea: [],
  5263. rectAreaLTC1: null,
  5264. rectAreaLTC2: null,
  5265. point: [],
  5266. pointShadow: [],
  5267. pointShadowMap: [],
  5268. pointShadowMatrix: [],
  5269. hemi: [],
  5270. numSpotLightShadowsWithMaps: 0,
  5271. numLightProbes: 0
  5272. };
  5273. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  5274. const vector3 = new Vector3();
  5275. const matrix4 = new Matrix4();
  5276. const matrix42 = new Matrix4();
  5277. function setup( lights ) {
  5278. let r = 0, g = 0, b = 0;
  5279. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  5280. let directionalLength = 0;
  5281. let pointLength = 0;
  5282. let spotLength = 0;
  5283. let rectAreaLength = 0;
  5284. let hemiLength = 0;
  5285. let numDirectionalShadows = 0;
  5286. let numPointShadows = 0;
  5287. let numSpotShadows = 0;
  5288. let numSpotMaps = 0;
  5289. let numSpotShadowsWithMaps = 0;
  5290. let numLightProbes = 0;
  5291. // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ]
  5292. lights.sort( shadowCastingAndTexturingLightsFirst );
  5293. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  5294. const light = lights[ i ];
  5295. const color = light.color;
  5296. const intensity = light.intensity;
  5297. const distance = light.distance;
  5298. let shadowMap = null;
  5299. if ( light.shadow && light.shadow.map ) {
  5300. if ( light.shadow.map.texture.format === RGFormat ) {
  5301. // VSM uses color texture with blurred mean/std_dev
  5302. shadowMap = light.shadow.map.texture;
  5303. } else {
  5304. // Other types use depth texture
  5305. shadowMap = light.shadow.map.depthTexture || light.shadow.map.texture;
  5306. }
  5307. }
  5308. if ( light.isAmbientLight ) {
  5309. r += color.r * intensity;
  5310. g += color.g * intensity;
  5311. b += color.b * intensity;
  5312. } else if ( light.isLightProbe ) {
  5313. for ( let j = 0; j < 9; j ++ ) {
  5314. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  5315. }
  5316. numLightProbes ++;
  5317. } else if ( light.isDirectionalLight ) {
  5318. const uniforms = cache.get( light );
  5319. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  5320. if ( light.castShadow ) {
  5321. const shadow = light.shadow;
  5322. const shadowUniforms = shadowCache.get( light );
  5323. shadowUniforms.shadowIntensity = shadow.intensity;
  5324. shadowUniforms.shadowBias = shadow.bias;
  5325. shadowUniforms.shadowNormalBias = shadow.normalBias;
  5326. shadowUniforms.shadowRadius = shadow.radius;
  5327. shadowUniforms.shadowMapSize = shadow.mapSize;
  5328. state.directionalShadow[ directionalLength ] = shadowUniforms;
  5329. state.directionalShadowMap[ directionalLength ] = shadowMap;
  5330. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  5331. numDirectionalShadows ++;
  5332. }
  5333. state.directional[ directionalLength ] = uniforms;
  5334. directionalLength ++;
  5335. } else if ( light.isSpotLight ) {
  5336. const uniforms = cache.get( light );
  5337. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  5338. uniforms.color.copy( color ).multiplyScalar( intensity );
  5339. uniforms.distance = distance;
  5340. uniforms.coneCos = Math.cos( light.angle );
  5341. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  5342. uniforms.decay = light.decay;
  5343. state.spot[ spotLength ] = uniforms;
  5344. const shadow = light.shadow;
  5345. if ( light.map ) {
  5346. state.spotLightMap[ numSpotMaps ] = light.map;
  5347. numSpotMaps ++;
  5348. // make sure the lightMatrix is up to date
  5349. // TODO : do it if required only
  5350. shadow.updateMatrices( light );
  5351. if ( light.castShadow ) numSpotShadowsWithMaps ++;
  5352. }
  5353. state.spotLightMatrix[ spotLength ] = shadow.matrix;
  5354. if ( light.castShadow ) {
  5355. const shadowUniforms = shadowCache.get( light );
  5356. shadowUniforms.shadowIntensity = shadow.intensity;
  5357. shadowUniforms.shadowBias = shadow.bias;
  5358. shadowUniforms.shadowNormalBias = shadow.normalBias;
  5359. shadowUniforms.shadowRadius = shadow.radius;
  5360. shadowUniforms.shadowMapSize = shadow.mapSize;
  5361. state.spotShadow[ spotLength ] = shadowUniforms;
  5362. state.spotShadowMap[ spotLength ] = shadowMap;
  5363. numSpotShadows ++;
  5364. }
  5365. spotLength ++;
  5366. } else if ( light.isRectAreaLight ) {
  5367. const uniforms = cache.get( light );
  5368. uniforms.color.copy( color ).multiplyScalar( intensity );
  5369. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  5370. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  5371. state.rectArea[ rectAreaLength ] = uniforms;
  5372. rectAreaLength ++;
  5373. } else if ( light.isPointLight ) {
  5374. const uniforms = cache.get( light );
  5375. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  5376. uniforms.distance = light.distance;
  5377. uniforms.decay = light.decay;
  5378. if ( light.castShadow ) {
  5379. const shadow = light.shadow;
  5380. const shadowUniforms = shadowCache.get( light );
  5381. shadowUniforms.shadowIntensity = shadow.intensity;
  5382. shadowUniforms.shadowBias = shadow.bias;
  5383. shadowUniforms.shadowNormalBias = shadow.normalBias;
  5384. shadowUniforms.shadowRadius = shadow.radius;
  5385. shadowUniforms.shadowMapSize = shadow.mapSize;
  5386. shadowUniforms.shadowCameraNear = shadow.camera.near;
  5387. shadowUniforms.shadowCameraFar = shadow.camera.far;
  5388. state.pointShadow[ pointLength ] = shadowUniforms;
  5389. state.pointShadowMap[ pointLength ] = shadowMap;
  5390. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  5391. numPointShadows ++;
  5392. }
  5393. state.point[ pointLength ] = uniforms;
  5394. pointLength ++;
  5395. } else if ( light.isHemisphereLight ) {
  5396. const uniforms = cache.get( light );
  5397. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  5398. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  5399. state.hemi[ hemiLength ] = uniforms;
  5400. hemiLength ++;
  5401. }
  5402. }
  5403. if ( rectAreaLength > 0 ) {
  5404. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  5405. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  5406. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  5407. } else {
  5408. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  5409. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  5410. }
  5411. }
  5412. state.ambient[ 0 ] = r;
  5413. state.ambient[ 1 ] = g;
  5414. state.ambient[ 2 ] = b;
  5415. const hash = state.hash;
  5416. if ( hash.directionalLength !== directionalLength ||
  5417. hash.pointLength !== pointLength ||
  5418. hash.spotLength !== spotLength ||
  5419. hash.rectAreaLength !== rectAreaLength ||
  5420. hash.hemiLength !== hemiLength ||
  5421. hash.numDirectionalShadows !== numDirectionalShadows ||
  5422. hash.numPointShadows !== numPointShadows ||
  5423. hash.numSpotShadows !== numSpotShadows ||
  5424. hash.numSpotMaps !== numSpotMaps ||
  5425. hash.numLightProbes !== numLightProbes ) {
  5426. state.directional.length = directionalLength;
  5427. state.spot.length = spotLength;
  5428. state.rectArea.length = rectAreaLength;
  5429. state.point.length = pointLength;
  5430. state.hemi.length = hemiLength;
  5431. state.directionalShadow.length = numDirectionalShadows;
  5432. state.directionalShadowMap.length = numDirectionalShadows;
  5433. state.pointShadow.length = numPointShadows;
  5434. state.pointShadowMap.length = numPointShadows;
  5435. state.spotShadow.length = numSpotShadows;
  5436. state.spotShadowMap.length = numSpotShadows;
  5437. state.directionalShadowMatrix.length = numDirectionalShadows;
  5438. state.pointShadowMatrix.length = numPointShadows;
  5439. state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps;
  5440. state.spotLightMap.length = numSpotMaps;
  5441. state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps;
  5442. state.numLightProbes = numLightProbes;
  5443. hash.directionalLength = directionalLength;
  5444. hash.pointLength = pointLength;
  5445. hash.spotLength = spotLength;
  5446. hash.rectAreaLength = rectAreaLength;
  5447. hash.hemiLength = hemiLength;
  5448. hash.numDirectionalShadows = numDirectionalShadows;
  5449. hash.numPointShadows = numPointShadows;
  5450. hash.numSpotShadows = numSpotShadows;
  5451. hash.numSpotMaps = numSpotMaps;
  5452. hash.numLightProbes = numLightProbes;
  5453. state.version = nextVersion ++;
  5454. }
  5455. }
  5456. function setupView( lights, camera ) {
  5457. let directionalLength = 0;
  5458. let pointLength = 0;
  5459. let spotLength = 0;
  5460. let rectAreaLength = 0;
  5461. let hemiLength = 0;
  5462. const viewMatrix = camera.matrixWorldInverse;
  5463. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  5464. const light = lights[ i ];
  5465. if ( light.isDirectionalLight ) {
  5466. const uniforms = state.directional[ directionalLength ];
  5467. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  5468. vector3.setFromMatrixPosition( light.target.matrixWorld );
  5469. uniforms.direction.sub( vector3 );
  5470. uniforms.direction.transformDirection( viewMatrix );
  5471. directionalLength ++;
  5472. } else if ( light.isSpotLight ) {
  5473. const uniforms = state.spot[ spotLength ];
  5474. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  5475. uniforms.position.applyMatrix4( viewMatrix );
  5476. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  5477. vector3.setFromMatrixPosition( light.target.matrixWorld );
  5478. uniforms.direction.sub( vector3 );
  5479. uniforms.direction.transformDirection( viewMatrix );
  5480. spotLength ++;
  5481. } else if ( light.isRectAreaLight ) {
  5482. const uniforms = state.rectArea[ rectAreaLength ];
  5483. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  5484. uniforms.position.applyMatrix4( viewMatrix );
  5485. // extract local rotation of light to derive width/height half vectors
  5486. matrix42.identity();
  5487. matrix4.copy( light.matrixWorld );
  5488. matrix4.premultiply( viewMatrix );
  5489. matrix42.extractRotation( matrix4 );
  5490. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  5491. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  5492. uniforms.halfWidth.applyMatrix4( matrix42 );
  5493. uniforms.halfHeight.applyMatrix4( matrix42 );
  5494. rectAreaLength ++;
  5495. } else if ( light.isPointLight ) {
  5496. const uniforms = state.point[ pointLength ];
  5497. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  5498. uniforms.position.applyMatrix4( viewMatrix );
  5499. pointLength ++;
  5500. } else if ( light.isHemisphereLight ) {
  5501. const uniforms = state.hemi[ hemiLength ];
  5502. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  5503. uniforms.direction.transformDirection( viewMatrix );
  5504. hemiLength ++;
  5505. }
  5506. }
  5507. }
  5508. return {
  5509. setup: setup,
  5510. setupView: setupView,
  5511. state: state
  5512. };
  5513. }
  5514. function WebGLRenderState( extensions ) {
  5515. const lights = new WebGLLights( extensions );
  5516. const lightsArray = [];
  5517. const shadowsArray = [];
  5518. function init( camera ) {
  5519. state.camera = camera;
  5520. lightsArray.length = 0;
  5521. shadowsArray.length = 0;
  5522. }
  5523. function pushLight( light ) {
  5524. lightsArray.push( light );
  5525. }
  5526. function pushShadow( shadowLight ) {
  5527. shadowsArray.push( shadowLight );
  5528. }
  5529. function setupLights() {
  5530. lights.setup( lightsArray );
  5531. }
  5532. function setupLightsView( camera ) {
  5533. lights.setupView( lightsArray, camera );
  5534. }
  5535. const state = {
  5536. lightsArray: lightsArray,
  5537. shadowsArray: shadowsArray,
  5538. camera: null,
  5539. lights: lights,
  5540. transmissionRenderTarget: {}
  5541. };
  5542. return {
  5543. init: init,
  5544. state: state,
  5545. setupLights: setupLights,
  5546. setupLightsView: setupLightsView,
  5547. pushLight: pushLight,
  5548. pushShadow: pushShadow
  5549. };
  5550. }
  5551. function WebGLRenderStates( extensions ) {
  5552. let renderStates = new WeakMap();
  5553. function get( scene, renderCallDepth = 0 ) {
  5554. const renderStateArray = renderStates.get( scene );
  5555. let renderState;
  5556. if ( renderStateArray === undefined ) {
  5557. renderState = new WebGLRenderState( extensions );
  5558. renderStates.set( scene, [ renderState ] );
  5559. } else {
  5560. if ( renderCallDepth >= renderStateArray.length ) {
  5561. renderState = new WebGLRenderState( extensions );
  5562. renderStateArray.push( renderState );
  5563. } else {
  5564. renderState = renderStateArray[ renderCallDepth ];
  5565. }
  5566. }
  5567. return renderState;
  5568. }
  5569. function dispose() {
  5570. renderStates = new WeakMap();
  5571. }
  5572. return {
  5573. get: get,
  5574. dispose: dispose
  5575. };
  5576. }
  5577. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  5578. const fragment = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\nvoid main() {\n\tconst float samples = float( VSM_SAMPLES );\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n\tfloat uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n\tfor ( float i = 0.0; i < samples; i ++ ) {\n\t\tfloat uvOffset = uvStart + i * uvStride;\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ).rg;\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ).r;\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean / samples;\n\tsquared_mean = squared_mean / samples;\n\tfloat std_dev = sqrt( max( 0.0, squared_mean - mean * mean ) );\n\tgl_FragColor = vec4( mean, std_dev, 0.0, 1.0 );\n}";
  5579. const _cubeDirections = [
  5580. /*@__PURE__*/ new Vector3( 1, 0, 0 ), /*@__PURE__*/ new Vector3( -1, 0, 0 ), /*@__PURE__*/ new Vector3( 0, 1, 0 ),
  5581. /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, 1 ), /*@__PURE__*/ new Vector3( 0, 0, -1 )
  5582. ];
  5583. const _cubeUps = [
  5584. /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, 1 ),
  5585. /*@__PURE__*/ new Vector3( 0, 0, -1 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 )
  5586. ];
  5587. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  5588. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  5589. const _lookTarget = /*@__PURE__*/ new Vector3();
  5590. function WebGLShadowMap( renderer, objects, capabilities ) {
  5591. let _frustum = new Frustum();
  5592. const _shadowMapSize = new Vector2(),
  5593. _viewportSize = new Vector2(),
  5594. _viewport = new Vector4(),
  5595. _depthMaterial = new MeshDepthMaterial(),
  5596. _distanceMaterial = new MeshDistanceMaterial(),
  5597. _materialCache = {},
  5598. _maxTextureSize = capabilities.maxTextureSize;
  5599. const shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide };
  5600. const shadowMaterialVertical = new ShaderMaterial( {
  5601. defines: {
  5602. VSM_SAMPLES: 8
  5603. },
  5604. uniforms: {
  5605. shadow_pass: { value: null },
  5606. resolution: { value: new Vector2() },
  5607. radius: { value: 4.0 }
  5608. },
  5609. vertexShader: vertex,
  5610. fragmentShader: fragment
  5611. } );
  5612. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  5613. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  5614. const fullScreenTri = new BufferGeometry();
  5615. fullScreenTri.setAttribute(
  5616. 'position',
  5617. new BufferAttribute(
  5618. new Float32Array( [ -1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5 ] ),
  5619. 3
  5620. )
  5621. );
  5622. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  5623. const scope = this;
  5624. this.enabled = false;
  5625. this.autoUpdate = true;
  5626. this.needsUpdate = false;
  5627. this.type = PCFShadowMap;
  5628. let _previousType = this.type;
  5629. this.render = function ( lights, scene, camera ) {
  5630. if ( scope.enabled === false ) return;
  5631. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  5632. if ( lights.length === 0 ) return;
  5633. if ( this.type === PCFSoftShadowMap ) {
  5634. warn( 'WebGLShadowMap: PCFSoftShadowMap has been deprecated. Using PCFShadowMap instead.' );
  5635. this.type = PCFShadowMap;
  5636. }
  5637. const currentRenderTarget = renderer.getRenderTarget();
  5638. const activeCubeFace = renderer.getActiveCubeFace();
  5639. const activeMipmapLevel = renderer.getActiveMipmapLevel();
  5640. const _state = renderer.state;
  5641. // Set GL state for depth map.
  5642. _state.setBlending( NoBlending );
  5643. if ( _state.buffers.depth.getReversed() === true ) {
  5644. _state.buffers.color.setClear( 0, 0, 0, 0 );
  5645. } else {
  5646. _state.buffers.color.setClear( 1, 1, 1, 1 );
  5647. }
  5648. _state.buffers.depth.setTest( true );
  5649. _state.setScissorTest( false );
  5650. // check for shadow map type changes
  5651. const typeChanged = _previousType !== this.type;
  5652. // When shadow map type changes, materials need recompilation because sampler types change
  5653. // (sampler2DShadow for PCF vs sampler2D for Basic)
  5654. if ( typeChanged ) {
  5655. scene.traverse( function ( object ) {
  5656. if ( object.material ) {
  5657. if ( Array.isArray( object.material ) ) {
  5658. object.material.forEach( mat => mat.needsUpdate = true );
  5659. } else {
  5660. object.material.needsUpdate = true;
  5661. }
  5662. }
  5663. } );
  5664. }
  5665. // render depth map
  5666. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  5667. const light = lights[ i ];
  5668. const shadow = light.shadow;
  5669. if ( shadow === undefined ) {
  5670. warn( 'WebGLShadowMap:', light, 'has no shadow.' );
  5671. continue;
  5672. }
  5673. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  5674. _shadowMapSize.copy( shadow.mapSize );
  5675. const shadowFrameExtents = shadow.getFrameExtents();
  5676. _shadowMapSize.multiply( shadowFrameExtents );
  5677. _viewportSize.copy( shadow.mapSize );
  5678. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  5679. if ( _shadowMapSize.x > _maxTextureSize ) {
  5680. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  5681. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  5682. shadow.mapSize.x = _viewportSize.x;
  5683. }
  5684. if ( _shadowMapSize.y > _maxTextureSize ) {
  5685. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  5686. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  5687. shadow.mapSize.y = _viewportSize.y;
  5688. }
  5689. }
  5690. if ( shadow.map === null || typeChanged === true ) {
  5691. if ( shadow.map !== null ) {
  5692. if ( shadow.map.depthTexture !== null ) {
  5693. shadow.map.depthTexture.dispose();
  5694. shadow.map.depthTexture = null;
  5695. }
  5696. shadow.map.dispose();
  5697. }
  5698. if ( this.type === VSMShadowMap ) {
  5699. if ( light.isPointLight ) {
  5700. warn( 'WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.' );
  5701. continue;
  5702. }
  5703. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, {
  5704. format: RGFormat,
  5705. type: HalfFloatType,
  5706. minFilter: LinearFilter,
  5707. magFilter: LinearFilter,
  5708. generateMipmaps: false
  5709. } );
  5710. shadow.map.texture.name = light.name + '.shadowMap';
  5711. // Native depth texture for VSM - depth is captured here, then blurred into the color texture
  5712. shadow.map.depthTexture = new DepthTexture( _shadowMapSize.x, _shadowMapSize.y, FloatType );
  5713. shadow.map.depthTexture.name = light.name + '.shadowMapDepth';
  5714. shadow.map.depthTexture.format = DepthFormat;
  5715. shadow.map.depthTexture.compareFunction = null; // For regular sampling (not shadow comparison)
  5716. shadow.map.depthTexture.minFilter = NearestFilter;
  5717. shadow.map.depthTexture.magFilter = NearestFilter;
  5718. } else {
  5719. if ( light.isPointLight ) {
  5720. shadow.map = new WebGLCubeRenderTarget( _shadowMapSize.x );
  5721. shadow.map.depthTexture = new CubeDepthTexture( _shadowMapSize.x, UnsignedIntType );
  5722. } else {
  5723. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y );
  5724. shadow.map.depthTexture = new DepthTexture( _shadowMapSize.x, _shadowMapSize.y, UnsignedIntType );
  5725. }
  5726. shadow.map.depthTexture.name = light.name + '.shadowMap';
  5727. shadow.map.depthTexture.format = DepthFormat;
  5728. const reversedDepthBuffer = renderer.state.buffers.depth.getReversed();
  5729. if ( this.type === PCFShadowMap ) {
  5730. shadow.map.depthTexture.compareFunction = reversedDepthBuffer ? GreaterEqualCompare : LessEqualCompare;
  5731. shadow.map.depthTexture.minFilter = LinearFilter;
  5732. shadow.map.depthTexture.magFilter = LinearFilter;
  5733. } else {
  5734. shadow.map.depthTexture.compareFunction = null;
  5735. shadow.map.depthTexture.minFilter = NearestFilter;
  5736. shadow.map.depthTexture.magFilter = NearestFilter;
  5737. }
  5738. }
  5739. shadow.camera.updateProjectionMatrix();
  5740. }
  5741. // For cube render targets (PointLights), render all 6 faces. Otherwise, render once.
  5742. const faceCount = shadow.map.isWebGLCubeRenderTarget ? 6 : 1;
  5743. for ( let face = 0; face < faceCount; face ++ ) {
  5744. // For cube render targets, render to each face separately
  5745. if ( shadow.map.isWebGLCubeRenderTarget ) {
  5746. renderer.setRenderTarget( shadow.map, face );
  5747. renderer.clear();
  5748. } else {
  5749. // For 2D render targets, use viewports
  5750. if ( face === 0 ) {
  5751. renderer.setRenderTarget( shadow.map );
  5752. renderer.clear();
  5753. }
  5754. const viewport = shadow.getViewport( face );
  5755. _viewport.set(
  5756. _viewportSize.x * viewport.x,
  5757. _viewportSize.y * viewport.y,
  5758. _viewportSize.x * viewport.z,
  5759. _viewportSize.y * viewport.w
  5760. );
  5761. _state.viewport( _viewport );
  5762. }
  5763. if ( light.isPointLight ) {
  5764. const camera = shadow.camera;
  5765. const shadowMatrix = shadow.matrix;
  5766. const far = light.distance || camera.far;
  5767. if ( far !== camera.far ) {
  5768. camera.far = far;
  5769. camera.updateProjectionMatrix();
  5770. }
  5771. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  5772. camera.position.copy( _lightPositionWorld );
  5773. _lookTarget.copy( camera.position );
  5774. _lookTarget.add( _cubeDirections[ face ] );
  5775. camera.up.copy( _cubeUps[ face ] );
  5776. camera.lookAt( _lookTarget );
  5777. camera.updateMatrixWorld();
  5778. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  5779. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  5780. shadow._frustum.setFromProjectionMatrix( _projScreenMatrix, camera.coordinateSystem, camera.reversedDepth );
  5781. } else {
  5782. shadow.updateMatrices( light );
  5783. }
  5784. _frustum = shadow.getFrustum();
  5785. renderObject( scene, camera, shadow.camera, light, this.type );
  5786. }
  5787. // do blur pass for VSM
  5788. if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) {
  5789. VSMPass( shadow, camera );
  5790. }
  5791. shadow.needsUpdate = false;
  5792. }
  5793. _previousType = this.type;
  5794. scope.needsUpdate = false;
  5795. renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  5796. };
  5797. function VSMPass( shadow, camera ) {
  5798. const geometry = objects.update( fullScreenMesh );
  5799. if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) {
  5800. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  5801. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  5802. shadowMaterialVertical.needsUpdate = true;
  5803. shadowMaterialHorizontal.needsUpdate = true;
  5804. }
  5805. if ( shadow.mapPass === null ) {
  5806. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, {
  5807. format: RGFormat,
  5808. type: HalfFloatType
  5809. } );
  5810. }
  5811. // vertical pass - read from native depth texture
  5812. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.depthTexture;
  5813. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  5814. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  5815. renderer.setRenderTarget( shadow.mapPass );
  5816. renderer.clear();
  5817. renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  5818. // horizontal pass
  5819. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  5820. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  5821. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  5822. renderer.setRenderTarget( shadow.map );
  5823. renderer.clear();
  5824. renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  5825. }
  5826. function getDepthMaterial( object, material, light, type ) {
  5827. let result = null;
  5828. const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial;
  5829. if ( customMaterial !== undefined ) {
  5830. result = customMaterial;
  5831. } else {
  5832. result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial;
  5833. if ( ( renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) ||
  5834. ( material.displacementMap && material.displacementScale !== 0 ) ||
  5835. ( material.alphaMap && material.alphaTest > 0 ) ||
  5836. ( material.map && material.alphaTest > 0 ) ||
  5837. ( material.alphaToCoverage === true ) ) {
  5838. // in this case we need a unique material instance reflecting the
  5839. // appropriate state
  5840. const keyA = result.uuid, keyB = material.uuid;
  5841. let materialsForVariant = _materialCache[ keyA ];
  5842. if ( materialsForVariant === undefined ) {
  5843. materialsForVariant = {};
  5844. _materialCache[ keyA ] = materialsForVariant;
  5845. }
  5846. let cachedMaterial = materialsForVariant[ keyB ];
  5847. if ( cachedMaterial === undefined ) {
  5848. cachedMaterial = result.clone();
  5849. materialsForVariant[ keyB ] = cachedMaterial;
  5850. material.addEventListener( 'dispose', onMaterialDispose );
  5851. }
  5852. result = cachedMaterial;
  5853. }
  5854. }
  5855. result.visible = material.visible;
  5856. result.wireframe = material.wireframe;
  5857. if ( type === VSMShadowMap ) {
  5858. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  5859. } else {
  5860. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  5861. }
  5862. result.alphaMap = material.alphaMap;
  5863. result.alphaTest = ( material.alphaToCoverage === true ) ? 0.5 : material.alphaTest; // approximate alphaToCoverage by using a fixed alphaTest value
  5864. result.map = material.map;
  5865. result.clipShadows = material.clipShadows;
  5866. result.clippingPlanes = material.clippingPlanes;
  5867. result.clipIntersection = material.clipIntersection;
  5868. result.displacementMap = material.displacementMap;
  5869. result.displacementScale = material.displacementScale;
  5870. result.displacementBias = material.displacementBias;
  5871. result.wireframeLinewidth = material.wireframeLinewidth;
  5872. result.linewidth = material.linewidth;
  5873. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  5874. const materialProperties = renderer.properties.get( result );
  5875. materialProperties.light = light;
  5876. }
  5877. return result;
  5878. }
  5879. function renderObject( object, camera, shadowCamera, light, type ) {
  5880. if ( object.visible === false ) return;
  5881. const visible = object.layers.test( camera.layers );
  5882. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  5883. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  5884. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  5885. const geometry = objects.update( object );
  5886. const material = object.material;
  5887. if ( Array.isArray( material ) ) {
  5888. const groups = geometry.groups;
  5889. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  5890. const group = groups[ k ];
  5891. const groupMaterial = material[ group.materialIndex ];
  5892. if ( groupMaterial && groupMaterial.visible ) {
  5893. const depthMaterial = getDepthMaterial( object, groupMaterial, light, type );
  5894. object.onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  5895. renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  5896. object.onAfterShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  5897. }
  5898. }
  5899. } else if ( material.visible ) {
  5900. const depthMaterial = getDepthMaterial( object, material, light, type );
  5901. object.onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  5902. renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  5903. object.onAfterShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  5904. }
  5905. }
  5906. }
  5907. const children = object.children;
  5908. for ( let i = 0, l = children.length; i < l; i ++ ) {
  5909. renderObject( children[ i ], camera, shadowCamera, light, type );
  5910. }
  5911. }
  5912. function onMaterialDispose( event ) {
  5913. const material = event.target;
  5914. material.removeEventListener( 'dispose', onMaterialDispose );
  5915. // make sure to remove the unique distance/depth materials used for shadow map rendering
  5916. for ( const id in _materialCache ) {
  5917. const cache = _materialCache[ id ];
  5918. const uuid = event.target.uuid;
  5919. if ( uuid in cache ) {
  5920. const shadowMaterial = cache[ uuid ];
  5921. shadowMaterial.dispose();
  5922. delete cache[ uuid ];
  5923. }
  5924. }
  5925. }
  5926. }
  5927. const reversedFuncs = {
  5928. [ NeverDepth ]: AlwaysDepth,
  5929. [ LessDepth ]: GreaterDepth,
  5930. [ EqualDepth ]: NotEqualDepth,
  5931. [ LessEqualDepth ]: GreaterEqualDepth,
  5932. [ AlwaysDepth ]: NeverDepth,
  5933. [ GreaterDepth ]: LessDepth,
  5934. [ NotEqualDepth ]: EqualDepth,
  5935. [ GreaterEqualDepth ]: LessEqualDepth,
  5936. };
  5937. function WebGLState( gl, extensions ) {
  5938. function ColorBuffer() {
  5939. let locked = false;
  5940. const color = new Vector4();
  5941. let currentColorMask = null;
  5942. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  5943. return {
  5944. setMask: function ( colorMask ) {
  5945. if ( currentColorMask !== colorMask && ! locked ) {
  5946. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  5947. currentColorMask = colorMask;
  5948. }
  5949. },
  5950. setLocked: function ( lock ) {
  5951. locked = lock;
  5952. },
  5953. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  5954. if ( premultipliedAlpha === true ) {
  5955. r *= a; g *= a; b *= a;
  5956. }
  5957. color.set( r, g, b, a );
  5958. if ( currentColorClear.equals( color ) === false ) {
  5959. gl.clearColor( r, g, b, a );
  5960. currentColorClear.copy( color );
  5961. }
  5962. },
  5963. reset: function () {
  5964. locked = false;
  5965. currentColorMask = null;
  5966. currentColorClear.set( -1, 0, 0, 0 ); // set to invalid state
  5967. }
  5968. };
  5969. }
  5970. function DepthBuffer() {
  5971. let locked = false;
  5972. let currentReversed = false;
  5973. let currentDepthMask = null;
  5974. let currentDepthFunc = null;
  5975. let currentDepthClear = null;
  5976. return {
  5977. setReversed: function ( reversed ) {
  5978. if ( currentReversed !== reversed ) {
  5979. const ext = extensions.get( 'EXT_clip_control' );
  5980. if ( reversed ) {
  5981. ext.clipControlEXT( ext.LOWER_LEFT_EXT, ext.ZERO_TO_ONE_EXT );
  5982. } else {
  5983. ext.clipControlEXT( ext.LOWER_LEFT_EXT, ext.NEGATIVE_ONE_TO_ONE_EXT );
  5984. }
  5985. currentReversed = reversed;
  5986. const oldDepth = currentDepthClear;
  5987. currentDepthClear = null;
  5988. this.setClear( oldDepth );
  5989. }
  5990. },
  5991. getReversed: function () {
  5992. return currentReversed;
  5993. },
  5994. setTest: function ( depthTest ) {
  5995. if ( depthTest ) {
  5996. enable( gl.DEPTH_TEST );
  5997. } else {
  5998. disable( gl.DEPTH_TEST );
  5999. }
  6000. },
  6001. setMask: function ( depthMask ) {
  6002. if ( currentDepthMask !== depthMask && ! locked ) {
  6003. gl.depthMask( depthMask );
  6004. currentDepthMask = depthMask;
  6005. }
  6006. },
  6007. setFunc: function ( depthFunc ) {
  6008. if ( currentReversed ) depthFunc = reversedFuncs[ depthFunc ];
  6009. if ( currentDepthFunc !== depthFunc ) {
  6010. switch ( depthFunc ) {
  6011. case NeverDepth:
  6012. gl.depthFunc( gl.NEVER );
  6013. break;
  6014. case AlwaysDepth:
  6015. gl.depthFunc( gl.ALWAYS );
  6016. break;
  6017. case LessDepth:
  6018. gl.depthFunc( gl.LESS );
  6019. break;
  6020. case LessEqualDepth:
  6021. gl.depthFunc( gl.LEQUAL );
  6022. break;
  6023. case EqualDepth:
  6024. gl.depthFunc( gl.EQUAL );
  6025. break;
  6026. case GreaterEqualDepth:
  6027. gl.depthFunc( gl.GEQUAL );
  6028. break;
  6029. case GreaterDepth:
  6030. gl.depthFunc( gl.GREATER );
  6031. break;
  6032. case NotEqualDepth:
  6033. gl.depthFunc( gl.NOTEQUAL );
  6034. break;
  6035. default:
  6036. gl.depthFunc( gl.LEQUAL );
  6037. }
  6038. currentDepthFunc = depthFunc;
  6039. }
  6040. },
  6041. setLocked: function ( lock ) {
  6042. locked = lock;
  6043. },
  6044. setClear: function ( depth ) {
  6045. if ( currentDepthClear !== depth ) {
  6046. if ( currentReversed ) {
  6047. depth = 1 - depth;
  6048. }
  6049. gl.clearDepth( depth );
  6050. currentDepthClear = depth;
  6051. }
  6052. },
  6053. reset: function () {
  6054. locked = false;
  6055. currentDepthMask = null;
  6056. currentDepthFunc = null;
  6057. currentDepthClear = null;
  6058. currentReversed = false;
  6059. }
  6060. };
  6061. }
  6062. function StencilBuffer() {
  6063. let locked = false;
  6064. let currentStencilMask = null;
  6065. let currentStencilFunc = null;
  6066. let currentStencilRef = null;
  6067. let currentStencilFuncMask = null;
  6068. let currentStencilFail = null;
  6069. let currentStencilZFail = null;
  6070. let currentStencilZPass = null;
  6071. let currentStencilClear = null;
  6072. return {
  6073. setTest: function ( stencilTest ) {
  6074. if ( ! locked ) {
  6075. if ( stencilTest ) {
  6076. enable( gl.STENCIL_TEST );
  6077. } else {
  6078. disable( gl.STENCIL_TEST );
  6079. }
  6080. }
  6081. },
  6082. setMask: function ( stencilMask ) {
  6083. if ( currentStencilMask !== stencilMask && ! locked ) {
  6084. gl.stencilMask( stencilMask );
  6085. currentStencilMask = stencilMask;
  6086. }
  6087. },
  6088. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  6089. if ( currentStencilFunc !== stencilFunc ||
  6090. currentStencilRef !== stencilRef ||
  6091. currentStencilFuncMask !== stencilMask ) {
  6092. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  6093. currentStencilFunc = stencilFunc;
  6094. currentStencilRef = stencilRef;
  6095. currentStencilFuncMask = stencilMask;
  6096. }
  6097. },
  6098. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  6099. if ( currentStencilFail !== stencilFail ||
  6100. currentStencilZFail !== stencilZFail ||
  6101. currentStencilZPass !== stencilZPass ) {
  6102. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  6103. currentStencilFail = stencilFail;
  6104. currentStencilZFail = stencilZFail;
  6105. currentStencilZPass = stencilZPass;
  6106. }
  6107. },
  6108. setLocked: function ( lock ) {
  6109. locked = lock;
  6110. },
  6111. setClear: function ( stencil ) {
  6112. if ( currentStencilClear !== stencil ) {
  6113. gl.clearStencil( stencil );
  6114. currentStencilClear = stencil;
  6115. }
  6116. },
  6117. reset: function () {
  6118. locked = false;
  6119. currentStencilMask = null;
  6120. currentStencilFunc = null;
  6121. currentStencilRef = null;
  6122. currentStencilFuncMask = null;
  6123. currentStencilFail = null;
  6124. currentStencilZFail = null;
  6125. currentStencilZPass = null;
  6126. currentStencilClear = null;
  6127. }
  6128. };
  6129. }
  6130. //
  6131. const colorBuffer = new ColorBuffer();
  6132. const depthBuffer = new DepthBuffer();
  6133. const stencilBuffer = new StencilBuffer();
  6134. const uboBindings = new WeakMap();
  6135. const uboProgramMap = new WeakMap();
  6136. let enabledCapabilities = {};
  6137. let currentBoundFramebuffers = {};
  6138. let currentDrawbuffers = new WeakMap();
  6139. let defaultDrawbuffers = [];
  6140. let currentProgram = null;
  6141. let currentBlendingEnabled = false;
  6142. let currentBlending = null;
  6143. let currentBlendEquation = null;
  6144. let currentBlendSrc = null;
  6145. let currentBlendDst = null;
  6146. let currentBlendEquationAlpha = null;
  6147. let currentBlendSrcAlpha = null;
  6148. let currentBlendDstAlpha = null;
  6149. let currentBlendColor = new Color( 0, 0, 0 );
  6150. let currentBlendAlpha = 0;
  6151. let currentPremultipledAlpha = false;
  6152. let currentFlipSided = null;
  6153. let currentCullFace = null;
  6154. let currentLineWidth = null;
  6155. let currentPolygonOffsetFactor = null;
  6156. let currentPolygonOffsetUnits = null;
  6157. const maxTextures = gl.getParameter( gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS );
  6158. let lineWidthAvailable = false;
  6159. let version = 0;
  6160. const glVersion = gl.getParameter( gl.VERSION );
  6161. if ( glVersion.indexOf( 'WebGL' ) !== -1 ) {
  6162. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  6163. lineWidthAvailable = ( version >= 1.0 );
  6164. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== -1 ) {
  6165. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  6166. lineWidthAvailable = ( version >= 2.0 );
  6167. }
  6168. let currentTextureSlot = null;
  6169. let currentBoundTextures = {};
  6170. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  6171. const viewportParam = gl.getParameter( gl.VIEWPORT );
  6172. const currentScissor = new Vector4().fromArray( scissorParam );
  6173. const currentViewport = new Vector4().fromArray( viewportParam );
  6174. function createTexture( type, target, count, dimensions ) {
  6175. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  6176. const texture = gl.createTexture();
  6177. gl.bindTexture( type, texture );
  6178. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  6179. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  6180. for ( let i = 0; i < count; i ++ ) {
  6181. if ( type === gl.TEXTURE_3D || type === gl.TEXTURE_2D_ARRAY ) {
  6182. gl.texImage3D( target, 0, gl.RGBA, 1, 1, dimensions, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  6183. } else {
  6184. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  6185. }
  6186. }
  6187. return texture;
  6188. }
  6189. const emptyTextures = {};
  6190. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  6191. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  6192. emptyTextures[ gl.TEXTURE_2D_ARRAY ] = createTexture( gl.TEXTURE_2D_ARRAY, gl.TEXTURE_2D_ARRAY, 1, 1 );
  6193. emptyTextures[ gl.TEXTURE_3D ] = createTexture( gl.TEXTURE_3D, gl.TEXTURE_3D, 1, 1 );
  6194. // init
  6195. colorBuffer.setClear( 0, 0, 0, 1 );
  6196. depthBuffer.setClear( 1 );
  6197. stencilBuffer.setClear( 0 );
  6198. enable( gl.DEPTH_TEST );
  6199. depthBuffer.setFunc( LessEqualDepth );
  6200. setFlipSided( false );
  6201. setCullFace( CullFaceBack );
  6202. enable( gl.CULL_FACE );
  6203. setBlending( NoBlending );
  6204. //
  6205. function enable( id ) {
  6206. if ( enabledCapabilities[ id ] !== true ) {
  6207. gl.enable( id );
  6208. enabledCapabilities[ id ] = true;
  6209. }
  6210. }
  6211. function disable( id ) {
  6212. if ( enabledCapabilities[ id ] !== false ) {
  6213. gl.disable( id );
  6214. enabledCapabilities[ id ] = false;
  6215. }
  6216. }
  6217. function bindFramebuffer( target, framebuffer ) {
  6218. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  6219. gl.bindFramebuffer( target, framebuffer );
  6220. currentBoundFramebuffers[ target ] = framebuffer;
  6221. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  6222. if ( target === gl.DRAW_FRAMEBUFFER ) {
  6223. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  6224. }
  6225. if ( target === gl.FRAMEBUFFER ) {
  6226. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  6227. }
  6228. return true;
  6229. }
  6230. return false;
  6231. }
  6232. function drawBuffers( renderTarget, framebuffer ) {
  6233. let drawBuffers = defaultDrawbuffers;
  6234. let needsUpdate = false;
  6235. if ( renderTarget ) {
  6236. drawBuffers = currentDrawbuffers.get( framebuffer );
  6237. if ( drawBuffers === undefined ) {
  6238. drawBuffers = [];
  6239. currentDrawbuffers.set( framebuffer, drawBuffers );
  6240. }
  6241. const textures = renderTarget.textures;
  6242. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  6243. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  6244. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  6245. }
  6246. drawBuffers.length = textures.length;
  6247. needsUpdate = true;
  6248. }
  6249. } else {
  6250. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  6251. drawBuffers[ 0 ] = gl.BACK;
  6252. needsUpdate = true;
  6253. }
  6254. }
  6255. if ( needsUpdate ) {
  6256. gl.drawBuffers( drawBuffers );
  6257. }
  6258. }
  6259. function useProgram( program ) {
  6260. if ( currentProgram !== program ) {
  6261. gl.useProgram( program );
  6262. currentProgram = program;
  6263. return true;
  6264. }
  6265. return false;
  6266. }
  6267. const equationToGL = {
  6268. [ AddEquation ]: gl.FUNC_ADD,
  6269. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  6270. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  6271. };
  6272. equationToGL[ MinEquation ] = gl.MIN;
  6273. equationToGL[ MaxEquation ] = gl.MAX;
  6274. const factorToGL = {
  6275. [ ZeroFactor ]: gl.ZERO,
  6276. [ OneFactor ]: gl.ONE,
  6277. [ SrcColorFactor ]: gl.SRC_COLOR,
  6278. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  6279. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  6280. [ DstColorFactor ]: gl.DST_COLOR,
  6281. [ DstAlphaFactor ]: gl.DST_ALPHA,
  6282. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  6283. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  6284. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  6285. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA,
  6286. [ ConstantColorFactor ]: gl.CONSTANT_COLOR,
  6287. [ OneMinusConstantColorFactor ]: gl.ONE_MINUS_CONSTANT_COLOR,
  6288. [ ConstantAlphaFactor ]: gl.CONSTANT_ALPHA,
  6289. [ OneMinusConstantAlphaFactor ]: gl.ONE_MINUS_CONSTANT_ALPHA
  6290. };
  6291. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, blendColor, blendAlpha, premultipliedAlpha ) {
  6292. if ( blending === NoBlending ) {
  6293. if ( currentBlendingEnabled === true ) {
  6294. disable( gl.BLEND );
  6295. currentBlendingEnabled = false;
  6296. }
  6297. return;
  6298. }
  6299. if ( currentBlendingEnabled === false ) {
  6300. enable( gl.BLEND );
  6301. currentBlendingEnabled = true;
  6302. }
  6303. if ( blending !== CustomBlending ) {
  6304. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  6305. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  6306. gl.blendEquation( gl.FUNC_ADD );
  6307. currentBlendEquation = AddEquation;
  6308. currentBlendEquationAlpha = AddEquation;
  6309. }
  6310. if ( premultipliedAlpha ) {
  6311. switch ( blending ) {
  6312. case NormalBlending:
  6313. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  6314. break;
  6315. case AdditiveBlending:
  6316. gl.blendFunc( gl.ONE, gl.ONE );
  6317. break;
  6318. case SubtractiveBlending:
  6319. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  6320. break;
  6321. case MultiplyBlending:
  6322. gl.blendFuncSeparate( gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE );
  6323. break;
  6324. default:
  6325. error( 'WebGLState: Invalid blending: ', blending );
  6326. break;
  6327. }
  6328. } else {
  6329. switch ( blending ) {
  6330. case NormalBlending:
  6331. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  6332. break;
  6333. case AdditiveBlending:
  6334. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE );
  6335. break;
  6336. case SubtractiveBlending:
  6337. error( 'WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true' );
  6338. break;
  6339. case MultiplyBlending:
  6340. error( 'WebGLState: MultiplyBlending requires material.premultipliedAlpha = true' );
  6341. break;
  6342. default:
  6343. error( 'WebGLState: Invalid blending: ', blending );
  6344. break;
  6345. }
  6346. }
  6347. currentBlendSrc = null;
  6348. currentBlendDst = null;
  6349. currentBlendSrcAlpha = null;
  6350. currentBlendDstAlpha = null;
  6351. currentBlendColor.set( 0, 0, 0 );
  6352. currentBlendAlpha = 0;
  6353. currentBlending = blending;
  6354. currentPremultipledAlpha = premultipliedAlpha;
  6355. }
  6356. return;
  6357. }
  6358. // custom blending
  6359. blendEquationAlpha = blendEquationAlpha || blendEquation;
  6360. blendSrcAlpha = blendSrcAlpha || blendSrc;
  6361. blendDstAlpha = blendDstAlpha || blendDst;
  6362. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  6363. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  6364. currentBlendEquation = blendEquation;
  6365. currentBlendEquationAlpha = blendEquationAlpha;
  6366. }
  6367. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  6368. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  6369. currentBlendSrc = blendSrc;
  6370. currentBlendDst = blendDst;
  6371. currentBlendSrcAlpha = blendSrcAlpha;
  6372. currentBlendDstAlpha = blendDstAlpha;
  6373. }
  6374. if ( blendColor.equals( currentBlendColor ) === false || blendAlpha !== currentBlendAlpha ) {
  6375. gl.blendColor( blendColor.r, blendColor.g, blendColor.b, blendAlpha );
  6376. currentBlendColor.copy( blendColor );
  6377. currentBlendAlpha = blendAlpha;
  6378. }
  6379. currentBlending = blending;
  6380. currentPremultipledAlpha = false;
  6381. }
  6382. function setMaterial( material, frontFaceCW ) {
  6383. material.side === DoubleSide
  6384. ? disable( gl.CULL_FACE )
  6385. : enable( gl.CULL_FACE );
  6386. let flipSided = ( material.side === BackSide );
  6387. if ( frontFaceCW ) flipSided = ! flipSided;
  6388. setFlipSided( flipSided );
  6389. ( material.blending === NormalBlending && material.transparent === false )
  6390. ? setBlending( NoBlending )
  6391. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.blendColor, material.blendAlpha, material.premultipliedAlpha );
  6392. depthBuffer.setFunc( material.depthFunc );
  6393. depthBuffer.setTest( material.depthTest );
  6394. depthBuffer.setMask( material.depthWrite );
  6395. colorBuffer.setMask( material.colorWrite );
  6396. const stencilWrite = material.stencilWrite;
  6397. stencilBuffer.setTest( stencilWrite );
  6398. if ( stencilWrite ) {
  6399. stencilBuffer.setMask( material.stencilWriteMask );
  6400. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  6401. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  6402. }
  6403. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  6404. material.alphaToCoverage === true
  6405. ? enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  6406. : disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  6407. }
  6408. //
  6409. function setFlipSided( flipSided ) {
  6410. if ( currentFlipSided !== flipSided ) {
  6411. if ( flipSided ) {
  6412. gl.frontFace( gl.CW );
  6413. } else {
  6414. gl.frontFace( gl.CCW );
  6415. }
  6416. currentFlipSided = flipSided;
  6417. }
  6418. }
  6419. function setCullFace( cullFace ) {
  6420. if ( cullFace !== CullFaceNone ) {
  6421. enable( gl.CULL_FACE );
  6422. if ( cullFace !== currentCullFace ) {
  6423. if ( cullFace === CullFaceBack ) {
  6424. gl.cullFace( gl.BACK );
  6425. } else if ( cullFace === CullFaceFront ) {
  6426. gl.cullFace( gl.FRONT );
  6427. } else {
  6428. gl.cullFace( gl.FRONT_AND_BACK );
  6429. }
  6430. }
  6431. } else {
  6432. disable( gl.CULL_FACE );
  6433. }
  6434. currentCullFace = cullFace;
  6435. }
  6436. function setLineWidth( width ) {
  6437. if ( width !== currentLineWidth ) {
  6438. if ( lineWidthAvailable ) gl.lineWidth( width );
  6439. currentLineWidth = width;
  6440. }
  6441. }
  6442. function setPolygonOffset( polygonOffset, factor, units ) {
  6443. if ( polygonOffset ) {
  6444. enable( gl.POLYGON_OFFSET_FILL );
  6445. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  6446. gl.polygonOffset( factor, units );
  6447. currentPolygonOffsetFactor = factor;
  6448. currentPolygonOffsetUnits = units;
  6449. }
  6450. } else {
  6451. disable( gl.POLYGON_OFFSET_FILL );
  6452. }
  6453. }
  6454. function setScissorTest( scissorTest ) {
  6455. if ( scissorTest ) {
  6456. enable( gl.SCISSOR_TEST );
  6457. } else {
  6458. disable( gl.SCISSOR_TEST );
  6459. }
  6460. }
  6461. // texture
  6462. function activeTexture( webglSlot ) {
  6463. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  6464. if ( currentTextureSlot !== webglSlot ) {
  6465. gl.activeTexture( webglSlot );
  6466. currentTextureSlot = webglSlot;
  6467. }
  6468. }
  6469. function bindTexture( webglType, webglTexture, webglSlot ) {
  6470. if ( webglSlot === undefined ) {
  6471. if ( currentTextureSlot === null ) {
  6472. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  6473. } else {
  6474. webglSlot = currentTextureSlot;
  6475. }
  6476. }
  6477. let boundTexture = currentBoundTextures[ webglSlot ];
  6478. if ( boundTexture === undefined ) {
  6479. boundTexture = { type: undefined, texture: undefined };
  6480. currentBoundTextures[ webglSlot ] = boundTexture;
  6481. }
  6482. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  6483. if ( currentTextureSlot !== webglSlot ) {
  6484. gl.activeTexture( webglSlot );
  6485. currentTextureSlot = webglSlot;
  6486. }
  6487. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  6488. boundTexture.type = webglType;
  6489. boundTexture.texture = webglTexture;
  6490. }
  6491. }
  6492. function unbindTexture() {
  6493. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  6494. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  6495. gl.bindTexture( boundTexture.type, null );
  6496. boundTexture.type = undefined;
  6497. boundTexture.texture = undefined;
  6498. }
  6499. }
  6500. function compressedTexImage2D() {
  6501. try {
  6502. gl.compressedTexImage2D( ...arguments );
  6503. } catch ( e ) {
  6504. error( 'WebGLState:', e );
  6505. }
  6506. }
  6507. function compressedTexImage3D() {
  6508. try {
  6509. gl.compressedTexImage3D( ...arguments );
  6510. } catch ( e ) {
  6511. error( 'WebGLState:', e );
  6512. }
  6513. }
  6514. function texSubImage2D() {
  6515. try {
  6516. gl.texSubImage2D( ...arguments );
  6517. } catch ( e ) {
  6518. error( 'WebGLState:', e );
  6519. }
  6520. }
  6521. function texSubImage3D() {
  6522. try {
  6523. gl.texSubImage3D( ...arguments );
  6524. } catch ( e ) {
  6525. error( 'WebGLState:', e );
  6526. }
  6527. }
  6528. function compressedTexSubImage2D() {
  6529. try {
  6530. gl.compressedTexSubImage2D( ...arguments );
  6531. } catch ( e ) {
  6532. error( 'WebGLState:', e );
  6533. }
  6534. }
  6535. function compressedTexSubImage3D() {
  6536. try {
  6537. gl.compressedTexSubImage3D( ...arguments );
  6538. } catch ( e ) {
  6539. error( 'WebGLState:', e );
  6540. }
  6541. }
  6542. function texStorage2D() {
  6543. try {
  6544. gl.texStorage2D( ...arguments );
  6545. } catch ( e ) {
  6546. error( 'WebGLState:', e );
  6547. }
  6548. }
  6549. function texStorage3D() {
  6550. try {
  6551. gl.texStorage3D( ...arguments );
  6552. } catch ( e ) {
  6553. error( 'WebGLState:', e );
  6554. }
  6555. }
  6556. function texImage2D() {
  6557. try {
  6558. gl.texImage2D( ...arguments );
  6559. } catch ( e ) {
  6560. error( 'WebGLState:', e );
  6561. }
  6562. }
  6563. function texImage3D() {
  6564. try {
  6565. gl.texImage3D( ...arguments );
  6566. } catch ( e ) {
  6567. error( 'WebGLState:', e );
  6568. }
  6569. }
  6570. //
  6571. function scissor( scissor ) {
  6572. if ( currentScissor.equals( scissor ) === false ) {
  6573. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  6574. currentScissor.copy( scissor );
  6575. }
  6576. }
  6577. function viewport( viewport ) {
  6578. if ( currentViewport.equals( viewport ) === false ) {
  6579. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  6580. currentViewport.copy( viewport );
  6581. }
  6582. }
  6583. function updateUBOMapping( uniformsGroup, program ) {
  6584. let mapping = uboProgramMap.get( program );
  6585. if ( mapping === undefined ) {
  6586. mapping = new WeakMap();
  6587. uboProgramMap.set( program, mapping );
  6588. }
  6589. let blockIndex = mapping.get( uniformsGroup );
  6590. if ( blockIndex === undefined ) {
  6591. blockIndex = gl.getUniformBlockIndex( program, uniformsGroup.name );
  6592. mapping.set( uniformsGroup, blockIndex );
  6593. }
  6594. }
  6595. function uniformBlockBinding( uniformsGroup, program ) {
  6596. const mapping = uboProgramMap.get( program );
  6597. const blockIndex = mapping.get( uniformsGroup );
  6598. if ( uboBindings.get( program ) !== blockIndex ) {
  6599. // bind shader specific block index to global block point
  6600. gl.uniformBlockBinding( program, blockIndex, uniformsGroup.__bindingPointIndex );
  6601. uboBindings.set( program, blockIndex );
  6602. }
  6603. }
  6604. //
  6605. function reset() {
  6606. // reset state
  6607. gl.disable( gl.BLEND );
  6608. gl.disable( gl.CULL_FACE );
  6609. gl.disable( gl.DEPTH_TEST );
  6610. gl.disable( gl.POLYGON_OFFSET_FILL );
  6611. gl.disable( gl.SCISSOR_TEST );
  6612. gl.disable( gl.STENCIL_TEST );
  6613. gl.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  6614. gl.blendEquation( gl.FUNC_ADD );
  6615. gl.blendFunc( gl.ONE, gl.ZERO );
  6616. gl.blendFuncSeparate( gl.ONE, gl.ZERO, gl.ONE, gl.ZERO );
  6617. gl.blendColor( 0, 0, 0, 0 );
  6618. gl.colorMask( true, true, true, true );
  6619. gl.clearColor( 0, 0, 0, 0 );
  6620. gl.depthMask( true );
  6621. gl.depthFunc( gl.LESS );
  6622. depthBuffer.setReversed( false );
  6623. gl.clearDepth( 1 );
  6624. gl.stencilMask( 0xffffffff );
  6625. gl.stencilFunc( gl.ALWAYS, 0, 0xffffffff );
  6626. gl.stencilOp( gl.KEEP, gl.KEEP, gl.KEEP );
  6627. gl.clearStencil( 0 );
  6628. gl.cullFace( gl.BACK );
  6629. gl.frontFace( gl.CCW );
  6630. gl.polygonOffset( 0, 0 );
  6631. gl.activeTexture( gl.TEXTURE0 );
  6632. gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  6633. gl.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  6634. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  6635. gl.useProgram( null );
  6636. gl.lineWidth( 1 );
  6637. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  6638. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  6639. // reset internals
  6640. enabledCapabilities = {};
  6641. currentTextureSlot = null;
  6642. currentBoundTextures = {};
  6643. currentBoundFramebuffers = {};
  6644. currentDrawbuffers = new WeakMap();
  6645. defaultDrawbuffers = [];
  6646. currentProgram = null;
  6647. currentBlendingEnabled = false;
  6648. currentBlending = null;
  6649. currentBlendEquation = null;
  6650. currentBlendSrc = null;
  6651. currentBlendDst = null;
  6652. currentBlendEquationAlpha = null;
  6653. currentBlendSrcAlpha = null;
  6654. currentBlendDstAlpha = null;
  6655. currentBlendColor = new Color( 0, 0, 0 );
  6656. currentBlendAlpha = 0;
  6657. currentPremultipledAlpha = false;
  6658. currentFlipSided = null;
  6659. currentCullFace = null;
  6660. currentLineWidth = null;
  6661. currentPolygonOffsetFactor = null;
  6662. currentPolygonOffsetUnits = null;
  6663. currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  6664. currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  6665. colorBuffer.reset();
  6666. depthBuffer.reset();
  6667. stencilBuffer.reset();
  6668. }
  6669. return {
  6670. buffers: {
  6671. color: colorBuffer,
  6672. depth: depthBuffer,
  6673. stencil: stencilBuffer
  6674. },
  6675. enable: enable,
  6676. disable: disable,
  6677. bindFramebuffer: bindFramebuffer,
  6678. drawBuffers: drawBuffers,
  6679. useProgram: useProgram,
  6680. setBlending: setBlending,
  6681. setMaterial: setMaterial,
  6682. setFlipSided: setFlipSided,
  6683. setCullFace: setCullFace,
  6684. setLineWidth: setLineWidth,
  6685. setPolygonOffset: setPolygonOffset,
  6686. setScissorTest: setScissorTest,
  6687. activeTexture: activeTexture,
  6688. bindTexture: bindTexture,
  6689. unbindTexture: unbindTexture,
  6690. compressedTexImage2D: compressedTexImage2D,
  6691. compressedTexImage3D: compressedTexImage3D,
  6692. texImage2D: texImage2D,
  6693. texImage3D: texImage3D,
  6694. updateUBOMapping: updateUBOMapping,
  6695. uniformBlockBinding: uniformBlockBinding,
  6696. texStorage2D: texStorage2D,
  6697. texStorage3D: texStorage3D,
  6698. texSubImage2D: texSubImage2D,
  6699. texSubImage3D: texSubImage3D,
  6700. compressedTexSubImage2D: compressedTexSubImage2D,
  6701. compressedTexSubImage3D: compressedTexSubImage3D,
  6702. scissor: scissor,
  6703. viewport: viewport,
  6704. reset: reset
  6705. };
  6706. }
  6707. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  6708. const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null;
  6709. const supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  6710. const _imageDimensions = new Vector2();
  6711. const _videoTextures = new WeakMap();
  6712. let _canvas;
  6713. const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source
  6714. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  6715. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  6716. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  6717. let useOffscreenCanvas = false;
  6718. try {
  6719. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  6720. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  6721. } catch ( err ) {
  6722. // Ignore any errors
  6723. }
  6724. function createCanvas( width, height ) {
  6725. // Use OffscreenCanvas when available. Specially needed in web workers
  6726. return useOffscreenCanvas ?
  6727. new OffscreenCanvas( width, height ) : createElementNS( 'canvas' );
  6728. }
  6729. function resizeImage( image, needsNewCanvas, maxSize ) {
  6730. let scale = 1;
  6731. const dimensions = getDimensions( image );
  6732. // handle case if texture exceeds max size
  6733. if ( dimensions.width > maxSize || dimensions.height > maxSize ) {
  6734. scale = maxSize / Math.max( dimensions.width, dimensions.height );
  6735. }
  6736. // only perform resize if necessary
  6737. if ( scale < 1 ) {
  6738. // only perform resize for certain image types
  6739. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  6740. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  6741. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ||
  6742. ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) ) {
  6743. const width = Math.floor( scale * dimensions.width );
  6744. const height = Math.floor( scale * dimensions.height );
  6745. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  6746. // cube textures can't reuse the same canvas
  6747. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  6748. canvas.width = width;
  6749. canvas.height = height;
  6750. const context = canvas.getContext( '2d' );
  6751. context.drawImage( image, 0, 0, width, height );
  6752. warn( 'WebGLRenderer: Texture has been resized from (' + dimensions.width + 'x' + dimensions.height + ') to (' + width + 'x' + height + ').' );
  6753. return canvas;
  6754. } else {
  6755. if ( 'data' in image ) {
  6756. warn( 'WebGLRenderer: Image in DataTexture is too big (' + dimensions.width + 'x' + dimensions.height + ').' );
  6757. }
  6758. return image;
  6759. }
  6760. }
  6761. return image;
  6762. }
  6763. function textureNeedsGenerateMipmaps( texture ) {
  6764. return texture.generateMipmaps;
  6765. }
  6766. function generateMipmap( target ) {
  6767. _gl.generateMipmap( target );
  6768. }
  6769. function getTargetType( texture ) {
  6770. if ( texture.isWebGLCubeRenderTarget ) return _gl.TEXTURE_CUBE_MAP;
  6771. if ( texture.isWebGL3DRenderTarget ) return _gl.TEXTURE_3D;
  6772. if ( texture.isWebGLArrayRenderTarget || texture.isCompressedArrayTexture ) return _gl.TEXTURE_2D_ARRAY;
  6773. return _gl.TEXTURE_2D;
  6774. }
  6775. function getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  6776. if ( internalFormatName !== null ) {
  6777. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  6778. warn( 'WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  6779. }
  6780. let internalFormat = glFormat;
  6781. if ( glFormat === _gl.RED ) {
  6782. if ( glType === _gl.FLOAT ) internalFormat = _gl.R32F;
  6783. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.R16F;
  6784. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8;
  6785. }
  6786. if ( glFormat === _gl.RED_INTEGER ) {
  6787. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8UI;
  6788. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.R16UI;
  6789. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.R32UI;
  6790. if ( glType === _gl.BYTE ) internalFormat = _gl.R8I;
  6791. if ( glType === _gl.SHORT ) internalFormat = _gl.R16I;
  6792. if ( glType === _gl.INT ) internalFormat = _gl.R32I;
  6793. }
  6794. if ( glFormat === _gl.RG ) {
  6795. if ( glType === _gl.FLOAT ) internalFormat = _gl.RG32F;
  6796. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RG16F;
  6797. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8;
  6798. }
  6799. if ( glFormat === _gl.RG_INTEGER ) {
  6800. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8UI;
  6801. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RG16UI;
  6802. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RG32UI;
  6803. if ( glType === _gl.BYTE ) internalFormat = _gl.RG8I;
  6804. if ( glType === _gl.SHORT ) internalFormat = _gl.RG16I;
  6805. if ( glType === _gl.INT ) internalFormat = _gl.RG32I;
  6806. }
  6807. if ( glFormat === _gl.RGB_INTEGER ) {
  6808. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RGB8UI;
  6809. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RGB16UI;
  6810. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RGB32UI;
  6811. if ( glType === _gl.BYTE ) internalFormat = _gl.RGB8I;
  6812. if ( glType === _gl.SHORT ) internalFormat = _gl.RGB16I;
  6813. if ( glType === _gl.INT ) internalFormat = _gl.RGB32I;
  6814. }
  6815. if ( glFormat === _gl.RGBA_INTEGER ) {
  6816. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RGBA8UI;
  6817. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RGBA16UI;
  6818. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RGBA32UI;
  6819. if ( glType === _gl.BYTE ) internalFormat = _gl.RGBA8I;
  6820. if ( glType === _gl.SHORT ) internalFormat = _gl.RGBA16I;
  6821. if ( glType === _gl.INT ) internalFormat = _gl.RGBA32I;
  6822. }
  6823. if ( glFormat === _gl.RGB ) {
  6824. if ( glType === _gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = _gl.RGB9_E5;
  6825. if ( glType === _gl.UNSIGNED_INT_10F_11F_11F_REV ) internalFormat = _gl.R11F_G11F_B10F;
  6826. }
  6827. if ( glFormat === _gl.RGBA ) {
  6828. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  6829. if ( glType === _gl.FLOAT ) internalFormat = _gl.RGBA32F;
  6830. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RGBA16F;
  6831. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;
  6832. if ( glType === _gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = _gl.RGBA4;
  6833. if ( glType === _gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = _gl.RGB5_A1;
  6834. }
  6835. if ( internalFormat === _gl.R16F || internalFormat === _gl.R32F ||
  6836. internalFormat === _gl.RG16F || internalFormat === _gl.RG32F ||
  6837. internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F ) {
  6838. extensions.get( 'EXT_color_buffer_float' );
  6839. }
  6840. return internalFormat;
  6841. }
  6842. function getInternalDepthFormat( useStencil, depthType ) {
  6843. let glInternalFormat;
  6844. if ( useStencil ) {
  6845. if ( depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type ) {
  6846. glInternalFormat = _gl.DEPTH24_STENCIL8;
  6847. } else if ( depthType === FloatType ) {
  6848. glInternalFormat = _gl.DEPTH32F_STENCIL8;
  6849. } else if ( depthType === UnsignedShortType ) {
  6850. glInternalFormat = _gl.DEPTH24_STENCIL8;
  6851. warn( 'DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.' );
  6852. }
  6853. } else {
  6854. if ( depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type ) {
  6855. glInternalFormat = _gl.DEPTH_COMPONENT24;
  6856. } else if ( depthType === FloatType ) {
  6857. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  6858. } else if ( depthType === UnsignedShortType ) {
  6859. glInternalFormat = _gl.DEPTH_COMPONENT16;
  6860. }
  6861. }
  6862. return glInternalFormat;
  6863. }
  6864. function getMipLevels( texture, image ) {
  6865. if ( textureNeedsGenerateMipmaps( texture ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) {
  6866. return Math.log2( Math.max( image.width, image.height ) ) + 1;
  6867. } else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) {
  6868. // user-defined mipmaps
  6869. return texture.mipmaps.length;
  6870. } else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) {
  6871. return image.mipmaps.length;
  6872. } else {
  6873. // texture without mipmaps (only base level)
  6874. return 1;
  6875. }
  6876. }
  6877. //
  6878. function onTextureDispose( event ) {
  6879. const texture = event.target;
  6880. texture.removeEventListener( 'dispose', onTextureDispose );
  6881. deallocateTexture( texture );
  6882. if ( texture.isVideoTexture ) {
  6883. _videoTextures.delete( texture );
  6884. }
  6885. }
  6886. function onRenderTargetDispose( event ) {
  6887. const renderTarget = event.target;
  6888. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  6889. deallocateRenderTarget( renderTarget );
  6890. }
  6891. //
  6892. function deallocateTexture( texture ) {
  6893. const textureProperties = properties.get( texture );
  6894. if ( textureProperties.__webglInit === undefined ) return;
  6895. // check if it's necessary to remove the WebGLTexture object
  6896. const source = texture.source;
  6897. const webglTextures = _sources.get( source );
  6898. if ( webglTextures ) {
  6899. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  6900. webglTexture.usedTimes --;
  6901. // the WebGLTexture object is not used anymore, remove it
  6902. if ( webglTexture.usedTimes === 0 ) {
  6903. deleteTexture( texture );
  6904. }
  6905. // remove the weak map entry if no WebGLTexture uses the source anymore
  6906. if ( Object.keys( webglTextures ).length === 0 ) {
  6907. _sources.delete( source );
  6908. }
  6909. }
  6910. properties.remove( texture );
  6911. }
  6912. function deleteTexture( texture ) {
  6913. const textureProperties = properties.get( texture );
  6914. _gl.deleteTexture( textureProperties.__webglTexture );
  6915. const source = texture.source;
  6916. const webglTextures = _sources.get( source );
  6917. delete webglTextures[ textureProperties.__cacheKey ];
  6918. info.memory.textures --;
  6919. }
  6920. function deallocateRenderTarget( renderTarget ) {
  6921. const renderTargetProperties = properties.get( renderTarget );
  6922. if ( renderTarget.depthTexture ) {
  6923. renderTarget.depthTexture.dispose();
  6924. properties.remove( renderTarget.depthTexture );
  6925. }
  6926. if ( renderTarget.isWebGLCubeRenderTarget ) {
  6927. for ( let i = 0; i < 6; i ++ ) {
  6928. if ( Array.isArray( renderTargetProperties.__webglFramebuffer[ i ] ) ) {
  6929. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer[ i ].length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ][ level ] );
  6930. } else {
  6931. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  6932. }
  6933. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  6934. }
  6935. } else {
  6936. if ( Array.isArray( renderTargetProperties.__webglFramebuffer ) ) {
  6937. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer.length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ level ] );
  6938. } else {
  6939. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  6940. }
  6941. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  6942. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  6943. if ( renderTargetProperties.__webglColorRenderbuffer ) {
  6944. for ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) {
  6945. if ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] );
  6946. }
  6947. }
  6948. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  6949. }
  6950. const textures = renderTarget.textures;
  6951. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  6952. const attachmentProperties = properties.get( textures[ i ] );
  6953. if ( attachmentProperties.__webglTexture ) {
  6954. _gl.deleteTexture( attachmentProperties.__webglTexture );
  6955. info.memory.textures --;
  6956. }
  6957. properties.remove( textures[ i ] );
  6958. }
  6959. properties.remove( renderTarget );
  6960. }
  6961. //
  6962. let textureUnits = 0;
  6963. function resetTextureUnits() {
  6964. textureUnits = 0;
  6965. }
  6966. function allocateTextureUnit() {
  6967. const textureUnit = textureUnits;
  6968. if ( textureUnit >= capabilities.maxTextures ) {
  6969. warn( 'WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  6970. }
  6971. textureUnits += 1;
  6972. return textureUnit;
  6973. }
  6974. function getTextureCacheKey( texture ) {
  6975. const array = [];
  6976. array.push( texture.wrapS );
  6977. array.push( texture.wrapT );
  6978. array.push( texture.wrapR || 0 );
  6979. array.push( texture.magFilter );
  6980. array.push( texture.minFilter );
  6981. array.push( texture.anisotropy );
  6982. array.push( texture.internalFormat );
  6983. array.push( texture.format );
  6984. array.push( texture.type );
  6985. array.push( texture.generateMipmaps );
  6986. array.push( texture.premultiplyAlpha );
  6987. array.push( texture.flipY );
  6988. array.push( texture.unpackAlignment );
  6989. array.push( texture.colorSpace );
  6990. return array.join();
  6991. }
  6992. //
  6993. function setTexture2D( texture, slot ) {
  6994. const textureProperties = properties.get( texture );
  6995. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  6996. if ( texture.isRenderTargetTexture === false && texture.isExternalTexture !== true && texture.version > 0 && textureProperties.__version !== texture.version ) {
  6997. const image = texture.image;
  6998. if ( image === null ) {
  6999. warn( 'WebGLRenderer: Texture marked for update but no image data found.' );
  7000. } else if ( image.complete === false ) {
  7001. warn( 'WebGLRenderer: Texture marked for update but image is incomplete' );
  7002. } else {
  7003. uploadTexture( textureProperties, texture, slot );
  7004. return;
  7005. }
  7006. } else if ( texture.isExternalTexture ) {
  7007. textureProperties.__webglTexture = texture.sourceTexture ? texture.sourceTexture : null;
  7008. }
  7009. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  7010. }
  7011. function setTexture2DArray( texture, slot ) {
  7012. const textureProperties = properties.get( texture );
  7013. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  7014. uploadTexture( textureProperties, texture, slot );
  7015. return;
  7016. } else if ( texture.isExternalTexture ) {
  7017. textureProperties.__webglTexture = texture.sourceTexture ? texture.sourceTexture : null;
  7018. }
  7019. state.bindTexture( _gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  7020. }
  7021. function setTexture3D( texture, slot ) {
  7022. const textureProperties = properties.get( texture );
  7023. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  7024. uploadTexture( textureProperties, texture, slot );
  7025. return;
  7026. }
  7027. state.bindTexture( _gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  7028. }
  7029. function setTextureCube( texture, slot ) {
  7030. const textureProperties = properties.get( texture );
  7031. if ( texture.isCubeDepthTexture !== true && texture.version > 0 && textureProperties.__version !== texture.version ) {
  7032. uploadCubeTexture( textureProperties, texture, slot );
  7033. return;
  7034. }
  7035. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  7036. }
  7037. const wrappingToGL = {
  7038. [ RepeatWrapping ]: _gl.REPEAT,
  7039. [ ClampToEdgeWrapping ]: _gl.CLAMP_TO_EDGE,
  7040. [ MirroredRepeatWrapping ]: _gl.MIRRORED_REPEAT
  7041. };
  7042. const filterToGL = {
  7043. [ NearestFilter ]: _gl.NEAREST,
  7044. [ NearestMipmapNearestFilter ]: _gl.NEAREST_MIPMAP_NEAREST,
  7045. [ NearestMipmapLinearFilter ]: _gl.NEAREST_MIPMAP_LINEAR,
  7046. [ LinearFilter ]: _gl.LINEAR,
  7047. [ LinearMipmapNearestFilter ]: _gl.LINEAR_MIPMAP_NEAREST,
  7048. [ LinearMipmapLinearFilter ]: _gl.LINEAR_MIPMAP_LINEAR
  7049. };
  7050. const compareToGL = {
  7051. [ NeverCompare ]: _gl.NEVER,
  7052. [ AlwaysCompare ]: _gl.ALWAYS,
  7053. [ LessCompare ]: _gl.LESS,
  7054. [ LessEqualCompare ]: _gl.LEQUAL,
  7055. [ EqualCompare ]: _gl.EQUAL,
  7056. [ GreaterEqualCompare ]: _gl.GEQUAL,
  7057. [ GreaterCompare ]: _gl.GREATER,
  7058. [ NotEqualCompare ]: _gl.NOTEQUAL
  7059. };
  7060. function setTextureParameters( textureType, texture ) {
  7061. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false &&
  7062. ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  7063. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter ) ) {
  7064. warn( 'WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device.' );
  7065. }
  7066. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  7067. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  7068. if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) {
  7069. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  7070. }
  7071. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  7072. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[ texture.minFilter ] );
  7073. if ( texture.compareFunction ) {
  7074. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_MODE, _gl.COMPARE_REF_TO_TEXTURE );
  7075. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  7076. }
  7077. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  7078. if ( texture.magFilter === NearestFilter ) return;
  7079. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  7080. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension
  7081. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  7082. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  7083. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  7084. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  7085. }
  7086. }
  7087. }
  7088. function initTexture( textureProperties, texture ) {
  7089. let forceUpload = false;
  7090. if ( textureProperties.__webglInit === undefined ) {
  7091. textureProperties.__webglInit = true;
  7092. texture.addEventListener( 'dispose', onTextureDispose );
  7093. }
  7094. // create Source <-> WebGLTextures mapping if necessary
  7095. const source = texture.source;
  7096. let webglTextures = _sources.get( source );
  7097. if ( webglTextures === undefined ) {
  7098. webglTextures = {};
  7099. _sources.set( source, webglTextures );
  7100. }
  7101. // check if there is already a WebGLTexture object for the given texture parameters
  7102. const textureCacheKey = getTextureCacheKey( texture );
  7103. if ( textureCacheKey !== textureProperties.__cacheKey ) {
  7104. // if not, create a new instance of WebGLTexture
  7105. if ( webglTextures[ textureCacheKey ] === undefined ) {
  7106. // create new entry
  7107. webglTextures[ textureCacheKey ] = {
  7108. texture: _gl.createTexture(),
  7109. usedTimes: 0
  7110. };
  7111. info.memory.textures ++;
  7112. // when a new instance of WebGLTexture was created, a texture upload is required
  7113. // even if the image contents are identical
  7114. forceUpload = true;
  7115. }
  7116. webglTextures[ textureCacheKey ].usedTimes ++;
  7117. // every time the texture cache key changes, it's necessary to check if an instance of
  7118. // WebGLTexture can be deleted in order to avoid a memory leak.
  7119. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  7120. if ( webglTexture !== undefined ) {
  7121. webglTextures[ textureProperties.__cacheKey ].usedTimes --;
  7122. if ( webglTexture.usedTimes === 0 ) {
  7123. deleteTexture( texture );
  7124. }
  7125. }
  7126. // store references to cache key and WebGLTexture object
  7127. textureProperties.__cacheKey = textureCacheKey;
  7128. textureProperties.__webglTexture = webglTextures[ textureCacheKey ].texture;
  7129. }
  7130. return forceUpload;
  7131. }
  7132. function getRow( index, rowLength, componentStride ) {
  7133. return Math.floor( Math.floor( index / componentStride ) / rowLength );
  7134. }
  7135. function updateTexture( texture, image, glFormat, glType ) {
  7136. const componentStride = 4; // only RGBA supported
  7137. const updateRanges = texture.updateRanges;
  7138. if ( updateRanges.length === 0 ) {
  7139. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data );
  7140. } else {
  7141. // Before applying update ranges, we merge any adjacent / overlapping
  7142. // ranges to reduce load on `gl.texSubImage2D`. Empirically, this has led
  7143. // to performance improvements for applications which make heavy use of
  7144. // update ranges. Likely due to GPU command overhead.
  7145. //
  7146. // Note that to reduce garbage collection between frames, we merge the
  7147. // update ranges in-place. This is safe because this method will clear the
  7148. // update ranges once updated.
  7149. updateRanges.sort( ( a, b ) => a.start - b.start );
  7150. // To merge the update ranges in-place, we work from left to right in the
  7151. // existing updateRanges array, merging ranges. This may result in a final
  7152. // array which is smaller than the original. This index tracks the last
  7153. // index representing a merged range, any data after this index can be
  7154. // trimmed once the merge algorithm is completed.
  7155. let mergeIndex = 0;
  7156. for ( let i = 1; i < updateRanges.length; i ++ ) {
  7157. const previousRange = updateRanges[ mergeIndex ];
  7158. const range = updateRanges[ i ];
  7159. // Only merge if in the same row and overlapping/adjacent
  7160. const previousEnd = previousRange.start + previousRange.count;
  7161. const currentRow = getRow( range.start, image.width, componentStride );
  7162. const previousRow = getRow( previousRange.start, image.width, componentStride );
  7163. // We add one here to merge adjacent ranges. This is safe because ranges
  7164. // operate over positive integers.
  7165. if (
  7166. range.start <= previousEnd + 1 &&
  7167. currentRow === previousRow &&
  7168. getRow( range.start + range.count - 1, image.width, componentStride ) === currentRow // ensure range doesn't spill
  7169. ) {
  7170. previousRange.count = Math.max(
  7171. previousRange.count,
  7172. range.start + range.count - previousRange.start
  7173. );
  7174. } else {
  7175. ++ mergeIndex;
  7176. updateRanges[ mergeIndex ] = range;
  7177. }
  7178. }
  7179. // Trim the array to only contain the merged ranges.
  7180. updateRanges.length = mergeIndex + 1;
  7181. const currentUnpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  7182. const currentUnpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  7183. const currentUnpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  7184. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  7185. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  7186. const range = updateRanges[ i ];
  7187. const pixelStart = Math.floor( range.start / componentStride );
  7188. const pixelCount = Math.ceil( range.count / componentStride );
  7189. const x = pixelStart % image.width;
  7190. const y = Math.floor( pixelStart / image.width );
  7191. // Assumes update ranges refer to contiguous memory
  7192. const width = pixelCount;
  7193. const height = 1;
  7194. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, x );
  7195. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, y );
  7196. state.texSubImage2D( _gl.TEXTURE_2D, 0, x, y, width, height, glFormat, glType, image.data );
  7197. }
  7198. texture.clearUpdateRanges();
  7199. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  7200. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  7201. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  7202. }
  7203. }
  7204. function uploadTexture( textureProperties, texture, slot ) {
  7205. let textureType = _gl.TEXTURE_2D;
  7206. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) textureType = _gl.TEXTURE_2D_ARRAY;
  7207. if ( texture.isData3DTexture ) textureType = _gl.TEXTURE_3D;
  7208. const forceUpload = initTexture( textureProperties, texture );
  7209. const source = texture.source;
  7210. state.bindTexture( textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  7211. const sourceProperties = properties.get( source );
  7212. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  7213. state.activeTexture( _gl.TEXTURE0 + slot );
  7214. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  7215. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  7216. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  7217. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  7218. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  7219. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  7220. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  7221. let image = resizeImage( texture.image, false, capabilities.maxTextureSize );
  7222. image = verifyColorSpace( texture, image );
  7223. const glFormat = utils.convert( texture.format, texture.colorSpace );
  7224. const glType = utils.convert( texture.type );
  7225. let glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  7226. setTextureParameters( textureType, texture );
  7227. let mipmap;
  7228. const mipmaps = texture.mipmaps;
  7229. const useTexStorage = ( texture.isVideoTexture !== true );
  7230. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  7231. const dataReady = source.dataReady;
  7232. const levels = getMipLevels( texture, image );
  7233. if ( texture.isDepthTexture ) {
  7234. glInternalFormat = getInternalDepthFormat( texture.format === DepthStencilFormat, texture.type );
  7235. //
  7236. if ( allocateMemory ) {
  7237. if ( useTexStorage ) {
  7238. state.texStorage2D( _gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height );
  7239. } else {
  7240. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  7241. }
  7242. }
  7243. } else if ( texture.isDataTexture ) {
  7244. // use manually created mipmaps if available
  7245. // if there are no manual mipmaps
  7246. // set 0 level mipmap and then use GL to generate other mipmap levels
  7247. if ( mipmaps.length > 0 ) {
  7248. if ( useTexStorage && allocateMemory ) {
  7249. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  7250. }
  7251. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  7252. mipmap = mipmaps[ i ];
  7253. if ( useTexStorage ) {
  7254. if ( dataReady ) {
  7255. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  7256. }
  7257. } else {
  7258. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  7259. }
  7260. }
  7261. texture.generateMipmaps = false;
  7262. } else {
  7263. if ( useTexStorage ) {
  7264. if ( allocateMemory ) {
  7265. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  7266. }
  7267. if ( dataReady ) {
  7268. updateTexture( texture, image, glFormat, glType );
  7269. }
  7270. } else {
  7271. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  7272. }
  7273. }
  7274. } else if ( texture.isCompressedTexture ) {
  7275. if ( texture.isCompressedArrayTexture ) {
  7276. if ( useTexStorage && allocateMemory ) {
  7277. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height, image.depth );
  7278. }
  7279. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  7280. mipmap = mipmaps[ i ];
  7281. if ( texture.format !== RGBAFormat ) {
  7282. if ( glFormat !== null ) {
  7283. if ( useTexStorage ) {
  7284. if ( dataReady ) {
  7285. if ( texture.layerUpdates.size > 0 ) {
  7286. const layerByteLength = getByteLength( mipmap.width, mipmap.height, texture.format, texture.type );
  7287. for ( const layerIndex of texture.layerUpdates ) {
  7288. const layerData = mipmap.data.subarray(
  7289. layerIndex * layerByteLength / mipmap.data.BYTES_PER_ELEMENT,
  7290. ( layerIndex + 1 ) * layerByteLength / mipmap.data.BYTES_PER_ELEMENT
  7291. );
  7292. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, layerIndex, mipmap.width, mipmap.height, 1, glFormat, layerData );
  7293. }
  7294. texture.clearLayerUpdates();
  7295. } else {
  7296. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  7297. }
  7298. }
  7299. } else {
  7300. state.compressedTexImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0 );
  7301. }
  7302. } else {
  7303. warn( 'WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  7304. }
  7305. } else {
  7306. if ( useTexStorage ) {
  7307. if ( dataReady ) {
  7308. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  7309. }
  7310. } else {
  7311. state.texImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data );
  7312. }
  7313. }
  7314. }
  7315. } else {
  7316. if ( useTexStorage && allocateMemory ) {
  7317. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  7318. }
  7319. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  7320. mipmap = mipmaps[ i ];
  7321. if ( texture.format !== RGBAFormat ) {
  7322. if ( glFormat !== null ) {
  7323. if ( useTexStorage ) {
  7324. if ( dataReady ) {
  7325. state.compressedTexSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  7326. }
  7327. } else {
  7328. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  7329. }
  7330. } else {
  7331. warn( 'WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  7332. }
  7333. } else {
  7334. if ( useTexStorage ) {
  7335. if ( dataReady ) {
  7336. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  7337. }
  7338. } else {
  7339. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  7340. }
  7341. }
  7342. }
  7343. }
  7344. } else if ( texture.isDataArrayTexture ) {
  7345. if ( useTexStorage ) {
  7346. if ( allocateMemory ) {
  7347. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth );
  7348. }
  7349. if ( dataReady ) {
  7350. if ( texture.layerUpdates.size > 0 ) {
  7351. const layerByteLength = getByteLength( image.width, image.height, texture.format, texture.type );
  7352. for ( const layerIndex of texture.layerUpdates ) {
  7353. const layerData = image.data.subarray(
  7354. layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT,
  7355. ( layerIndex + 1 ) * layerByteLength / image.data.BYTES_PER_ELEMENT
  7356. );
  7357. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData );
  7358. }
  7359. texture.clearLayerUpdates();
  7360. } else {
  7361. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  7362. }
  7363. }
  7364. } else {
  7365. state.texImage3D( _gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  7366. }
  7367. } else if ( texture.isData3DTexture ) {
  7368. if ( useTexStorage ) {
  7369. if ( allocateMemory ) {
  7370. state.texStorage3D( _gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth );
  7371. }
  7372. if ( dataReady ) {
  7373. state.texSubImage3D( _gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  7374. }
  7375. } else {
  7376. state.texImage3D( _gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  7377. }
  7378. } else if ( texture.isFramebufferTexture ) {
  7379. if ( allocateMemory ) {
  7380. if ( useTexStorage ) {
  7381. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  7382. } else {
  7383. let width = image.width, height = image.height;
  7384. for ( let i = 0; i < levels; i ++ ) {
  7385. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, width, height, 0, glFormat, glType, null );
  7386. width >>= 1;
  7387. height >>= 1;
  7388. }
  7389. }
  7390. }
  7391. } else {
  7392. // regular Texture (image, video, canvas)
  7393. // use manually created mipmaps if available
  7394. // if there are no manual mipmaps
  7395. // set 0 level mipmap and then use GL to generate other mipmap levels
  7396. if ( mipmaps.length > 0 ) {
  7397. if ( useTexStorage && allocateMemory ) {
  7398. const dimensions = getDimensions( mipmaps[ 0 ] );
  7399. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height );
  7400. }
  7401. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  7402. mipmap = mipmaps[ i ];
  7403. if ( useTexStorage ) {
  7404. if ( dataReady ) {
  7405. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap );
  7406. }
  7407. } else {
  7408. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap );
  7409. }
  7410. }
  7411. texture.generateMipmaps = false;
  7412. } else {
  7413. if ( useTexStorage ) {
  7414. if ( allocateMemory ) {
  7415. const dimensions = getDimensions( image );
  7416. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height );
  7417. }
  7418. if ( dataReady ) {
  7419. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image );
  7420. }
  7421. } else {
  7422. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image );
  7423. }
  7424. }
  7425. }
  7426. if ( textureNeedsGenerateMipmaps( texture ) ) {
  7427. generateMipmap( textureType );
  7428. }
  7429. sourceProperties.__version = source.version;
  7430. if ( texture.onUpdate ) texture.onUpdate( texture );
  7431. }
  7432. textureProperties.__version = texture.version;
  7433. }
  7434. function uploadCubeTexture( textureProperties, texture, slot ) {
  7435. if ( texture.image.length !== 6 ) return;
  7436. const forceUpload = initTexture( textureProperties, texture );
  7437. const source = texture.source;
  7438. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  7439. const sourceProperties = properties.get( source );
  7440. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  7441. state.activeTexture( _gl.TEXTURE0 + slot );
  7442. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  7443. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  7444. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  7445. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  7446. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  7447. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  7448. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  7449. const isCompressed = ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture );
  7450. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  7451. const cubeImage = [];
  7452. for ( let i = 0; i < 6; i ++ ) {
  7453. if ( ! isCompressed && ! isDataTexture ) {
  7454. cubeImage[ i ] = resizeImage( texture.image[ i ], true, capabilities.maxCubemapSize );
  7455. } else {
  7456. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  7457. }
  7458. cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] );
  7459. }
  7460. const image = cubeImage[ 0 ],
  7461. glFormat = utils.convert( texture.format, texture.colorSpace ),
  7462. glType = utils.convert( texture.type ),
  7463. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  7464. const useTexStorage = ( texture.isVideoTexture !== true );
  7465. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  7466. const dataReady = source.dataReady;
  7467. let levels = getMipLevels( texture, image );
  7468. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture );
  7469. let mipmaps;
  7470. if ( isCompressed ) {
  7471. if ( useTexStorage && allocateMemory ) {
  7472. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height );
  7473. }
  7474. for ( let i = 0; i < 6; i ++ ) {
  7475. mipmaps = cubeImage[ i ].mipmaps;
  7476. for ( let j = 0; j < mipmaps.length; j ++ ) {
  7477. const mipmap = mipmaps[ j ];
  7478. if ( texture.format !== RGBAFormat ) {
  7479. if ( glFormat !== null ) {
  7480. if ( useTexStorage ) {
  7481. if ( dataReady ) {
  7482. state.compressedTexSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  7483. }
  7484. } else {
  7485. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  7486. }
  7487. } else {
  7488. warn( 'WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  7489. }
  7490. } else {
  7491. if ( useTexStorage ) {
  7492. if ( dataReady ) {
  7493. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  7494. }
  7495. } else {
  7496. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  7497. }
  7498. }
  7499. }
  7500. }
  7501. } else {
  7502. mipmaps = texture.mipmaps;
  7503. if ( useTexStorage && allocateMemory ) {
  7504. // TODO: Uniformly handle mipmap definitions
  7505. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  7506. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  7507. if ( mipmaps.length > 0 ) levels ++;
  7508. const dimensions = getDimensions( cubeImage[ 0 ] );
  7509. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, dimensions.width, dimensions.height );
  7510. }
  7511. for ( let i = 0; i < 6; i ++ ) {
  7512. if ( isDataTexture ) {
  7513. if ( useTexStorage ) {
  7514. if ( dataReady ) {
  7515. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data );
  7516. }
  7517. } else {
  7518. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  7519. }
  7520. for ( let j = 0; j < mipmaps.length; j ++ ) {
  7521. const mipmap = mipmaps[ j ];
  7522. const mipmapImage = mipmap.image[ i ].image;
  7523. if ( useTexStorage ) {
  7524. if ( dataReady ) {
  7525. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data );
  7526. }
  7527. } else {
  7528. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  7529. }
  7530. }
  7531. } else {
  7532. if ( useTexStorage ) {
  7533. if ( dataReady ) {
  7534. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] );
  7535. }
  7536. } else {
  7537. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  7538. }
  7539. for ( let j = 0; j < mipmaps.length; j ++ ) {
  7540. const mipmap = mipmaps[ j ];
  7541. if ( useTexStorage ) {
  7542. if ( dataReady ) {
  7543. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] );
  7544. }
  7545. } else {
  7546. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  7547. }
  7548. }
  7549. }
  7550. }
  7551. }
  7552. if ( textureNeedsGenerateMipmaps( texture ) ) {
  7553. // We assume images for cube map have the same size.
  7554. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  7555. }
  7556. sourceProperties.__version = source.version;
  7557. if ( texture.onUpdate ) texture.onUpdate( texture );
  7558. }
  7559. textureProperties.__version = texture.version;
  7560. }
  7561. // Render targets
  7562. // Setup storage for target texture and bind it to correct framebuffer
  7563. function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget, level ) {
  7564. const glFormat = utils.convert( texture.format, texture.colorSpace );
  7565. const glType = utils.convert( texture.type );
  7566. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  7567. const renderTargetProperties = properties.get( renderTarget );
  7568. const textureProperties = properties.get( texture );
  7569. textureProperties.__renderTarget = renderTarget;
  7570. if ( ! renderTargetProperties.__hasExternalTextures ) {
  7571. const width = Math.max( 1, renderTarget.width >> level );
  7572. const height = Math.max( 1, renderTarget.height >> level );
  7573. if ( textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY ) {
  7574. state.texImage3D( textureTarget, level, glInternalFormat, width, height, renderTarget.depth, 0, glFormat, glType, null );
  7575. } else {
  7576. state.texImage2D( textureTarget, level, glInternalFormat, width, height, 0, glFormat, glType, null );
  7577. }
  7578. }
  7579. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  7580. if ( useMultisampledRTT( renderTarget ) ) {
  7581. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, 0, getRenderTargetSamples( renderTarget ) );
  7582. } else if ( textureTarget === _gl.TEXTURE_2D || ( textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z ) ) { // see #24753
  7583. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, level );
  7584. }
  7585. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  7586. }
  7587. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  7588. function setupRenderBufferStorage( renderbuffer, renderTarget, useMultisample ) {
  7589. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  7590. if ( renderTarget.depthBuffer ) {
  7591. // retrieve the depth attachment types
  7592. const depthTexture = renderTarget.depthTexture;
  7593. const depthType = depthTexture && depthTexture.isDepthTexture ? depthTexture.type : null;
  7594. const glInternalFormat = getInternalDepthFormat( renderTarget.stencilBuffer, depthType );
  7595. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  7596. // set up the attachment
  7597. if ( useMultisampledRTT( renderTarget ) ) {
  7598. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, getRenderTargetSamples( renderTarget ), glInternalFormat, renderTarget.width, renderTarget.height );
  7599. } else if ( useMultisample ) {
  7600. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, getRenderTargetSamples( renderTarget ), glInternalFormat, renderTarget.width, renderTarget.height );
  7601. } else {
  7602. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  7603. }
  7604. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  7605. } else {
  7606. const textures = renderTarget.textures;
  7607. for ( let i = 0; i < textures.length; i ++ ) {
  7608. const texture = textures[ i ];
  7609. const glFormat = utils.convert( texture.format, texture.colorSpace );
  7610. const glType = utils.convert( texture.type );
  7611. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  7612. if ( useMultisampledRTT( renderTarget ) ) {
  7613. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, getRenderTargetSamples( renderTarget ), glInternalFormat, renderTarget.width, renderTarget.height );
  7614. } else if ( useMultisample ) {
  7615. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, getRenderTargetSamples( renderTarget ), glInternalFormat, renderTarget.width, renderTarget.height );
  7616. } else {
  7617. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  7618. }
  7619. }
  7620. }
  7621. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  7622. }
  7623. // Setup resources for a Depth Texture for a FBO (needs an extension)
  7624. function setupDepthTexture( framebuffer, renderTarget, cubeFace ) {
  7625. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  7626. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  7627. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  7628. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  7629. }
  7630. const textureProperties = properties.get( renderTarget.depthTexture );
  7631. textureProperties.__renderTarget = renderTarget;
  7632. // upload an empty depth texture with framebuffer size
  7633. if ( ! textureProperties.__webglTexture ||
  7634. renderTarget.depthTexture.image.width !== renderTarget.width ||
  7635. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  7636. renderTarget.depthTexture.image.width = renderTarget.width;
  7637. renderTarget.depthTexture.image.height = renderTarget.height;
  7638. renderTarget.depthTexture.needsUpdate = true;
  7639. }
  7640. if ( isCube ) {
  7641. // For cube depth textures, initialize and bind without uploading image data
  7642. if ( textureProperties.__webglInit === undefined ) {
  7643. textureProperties.__webglInit = true;
  7644. renderTarget.depthTexture.addEventListener( 'dispose', onTextureDispose );
  7645. }
  7646. // Only create and allocate storage once
  7647. if ( textureProperties.__webglTexture === undefined ) {
  7648. textureProperties.__webglTexture = _gl.createTexture();
  7649. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  7650. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.depthTexture );
  7651. // Allocate storage for all 6 faces with correct depth texture format
  7652. const glFormat = utils.convert( renderTarget.depthTexture.format );
  7653. const glType = utils.convert( renderTarget.depthTexture.type );
  7654. // Use proper internal format for depth textures
  7655. let glInternalFormat;
  7656. if ( renderTarget.depthTexture.format === DepthFormat ) {
  7657. glInternalFormat = _gl.DEPTH_COMPONENT24;
  7658. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  7659. glInternalFormat = _gl.DEPTH24_STENCIL8;
  7660. }
  7661. for ( let i = 0; i < 6; i ++ ) {
  7662. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  7663. }
  7664. }
  7665. } else {
  7666. setTexture2D( renderTarget.depthTexture, 0 );
  7667. }
  7668. const webglDepthTexture = textureProperties.__webglTexture;
  7669. const samples = getRenderTargetSamples( renderTarget );
  7670. const glTextureType = isCube ? _gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace : _gl.TEXTURE_2D;
  7671. const glAttachmentType = renderTarget.depthTexture.format === DepthStencilFormat ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  7672. if ( renderTarget.depthTexture.format === DepthFormat ) {
  7673. if ( useMultisampledRTT( renderTarget ) ) {
  7674. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, glAttachmentType, glTextureType, webglDepthTexture, 0, samples );
  7675. } else {
  7676. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, glAttachmentType, glTextureType, webglDepthTexture, 0 );
  7677. }
  7678. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  7679. if ( useMultisampledRTT( renderTarget ) ) {
  7680. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, glAttachmentType, glTextureType, webglDepthTexture, 0, samples );
  7681. } else {
  7682. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, glAttachmentType, glTextureType, webglDepthTexture, 0 );
  7683. }
  7684. } else {
  7685. throw new Error( 'Unknown depthTexture format' );
  7686. }
  7687. }
  7688. // Setup GL resources for a non-texture depth buffer
  7689. function setupDepthRenderbuffer( renderTarget ) {
  7690. const renderTargetProperties = properties.get( renderTarget );
  7691. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  7692. // if the bound depth texture has changed
  7693. if ( renderTargetProperties.__boundDepthTexture !== renderTarget.depthTexture ) {
  7694. // fire the dispose event to get rid of stored state associated with the previously bound depth buffer
  7695. const depthTexture = renderTarget.depthTexture;
  7696. if ( renderTargetProperties.__depthDisposeCallback ) {
  7697. renderTargetProperties.__depthDisposeCallback();
  7698. }
  7699. // set up dispose listeners to track when the currently attached buffer is implicitly unbound
  7700. if ( depthTexture ) {
  7701. const disposeEvent = () => {
  7702. delete renderTargetProperties.__boundDepthTexture;
  7703. delete renderTargetProperties.__depthDisposeCallback;
  7704. depthTexture.removeEventListener( 'dispose', disposeEvent );
  7705. };
  7706. depthTexture.addEventListener( 'dispose', disposeEvent );
  7707. renderTargetProperties.__depthDisposeCallback = disposeEvent;
  7708. }
  7709. renderTargetProperties.__boundDepthTexture = depthTexture;
  7710. }
  7711. if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  7712. if ( isCube ) {
  7713. // For cube render targets with depth texture, setup each face
  7714. for ( let i = 0; i < 6; i ++ ) {
  7715. setupDepthTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, i );
  7716. }
  7717. } else {
  7718. const mipmaps = renderTarget.texture.mipmaps;
  7719. if ( mipmaps && mipmaps.length > 0 ) {
  7720. setupDepthTexture( renderTargetProperties.__webglFramebuffer[ 0 ], renderTarget, 0 );
  7721. } else {
  7722. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget, 0 );
  7723. }
  7724. }
  7725. } else {
  7726. if ( isCube ) {
  7727. renderTargetProperties.__webglDepthbuffer = [];
  7728. for ( let i = 0; i < 6; i ++ ) {
  7729. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  7730. if ( renderTargetProperties.__webglDepthbuffer[ i ] === undefined ) {
  7731. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  7732. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  7733. } else {
  7734. // attach buffer if it's been created already
  7735. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  7736. const renderbuffer = renderTargetProperties.__webglDepthbuffer[ i ];
  7737. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  7738. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  7739. }
  7740. }
  7741. } else {
  7742. const mipmaps = renderTarget.texture.mipmaps;
  7743. if ( mipmaps && mipmaps.length > 0 ) {
  7744. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ 0 ] );
  7745. } else {
  7746. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  7747. }
  7748. if ( renderTargetProperties.__webglDepthbuffer === undefined ) {
  7749. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  7750. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  7751. } else {
  7752. // attach buffer if it's been created already
  7753. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  7754. const renderbuffer = renderTargetProperties.__webglDepthbuffer;
  7755. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  7756. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  7757. }
  7758. }
  7759. }
  7760. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  7761. }
  7762. // rebind framebuffer with external textures
  7763. function rebindTextures( renderTarget, colorTexture, depthTexture ) {
  7764. const renderTargetProperties = properties.get( renderTarget );
  7765. if ( colorTexture !== undefined ) {
  7766. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, 0 );
  7767. }
  7768. if ( depthTexture !== undefined ) {
  7769. setupDepthRenderbuffer( renderTarget );
  7770. }
  7771. }
  7772. // Set up GL resources for the render target
  7773. function setupRenderTarget( renderTarget ) {
  7774. const texture = renderTarget.texture;
  7775. const renderTargetProperties = properties.get( renderTarget );
  7776. const textureProperties = properties.get( texture );
  7777. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  7778. const textures = renderTarget.textures;
  7779. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  7780. const isMultipleRenderTargets = ( textures.length > 1 );
  7781. if ( ! isMultipleRenderTargets ) {
  7782. if ( textureProperties.__webglTexture === undefined ) {
  7783. textureProperties.__webglTexture = _gl.createTexture();
  7784. }
  7785. textureProperties.__version = texture.version;
  7786. info.memory.textures ++;
  7787. }
  7788. // Setup framebuffer
  7789. if ( isCube ) {
  7790. renderTargetProperties.__webglFramebuffer = [];
  7791. for ( let i = 0; i < 6; i ++ ) {
  7792. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  7793. renderTargetProperties.__webglFramebuffer[ i ] = [];
  7794. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  7795. renderTargetProperties.__webglFramebuffer[ i ][ level ] = _gl.createFramebuffer();
  7796. }
  7797. } else {
  7798. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  7799. }
  7800. }
  7801. } else {
  7802. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  7803. renderTargetProperties.__webglFramebuffer = [];
  7804. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  7805. renderTargetProperties.__webglFramebuffer[ level ] = _gl.createFramebuffer();
  7806. }
  7807. } else {
  7808. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  7809. }
  7810. if ( isMultipleRenderTargets ) {
  7811. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  7812. const attachmentProperties = properties.get( textures[ i ] );
  7813. if ( attachmentProperties.__webglTexture === undefined ) {
  7814. attachmentProperties.__webglTexture = _gl.createTexture();
  7815. info.memory.textures ++;
  7816. }
  7817. }
  7818. }
  7819. if ( ( renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  7820. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  7821. renderTargetProperties.__webglColorRenderbuffer = [];
  7822. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  7823. for ( let i = 0; i < textures.length; i ++ ) {
  7824. const texture = textures[ i ];
  7825. renderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer();
  7826. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  7827. const glFormat = utils.convert( texture.format, texture.colorSpace );
  7828. const glType = utils.convert( texture.type );
  7829. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, renderTarget.isXRRenderTarget === true );
  7830. const samples = getRenderTargetSamples( renderTarget );
  7831. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  7832. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  7833. }
  7834. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  7835. if ( renderTarget.depthBuffer ) {
  7836. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  7837. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  7838. }
  7839. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  7840. }
  7841. }
  7842. // Setup color buffer
  7843. if ( isCube ) {
  7844. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  7845. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture );
  7846. for ( let i = 0; i < 6; i ++ ) {
  7847. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  7848. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  7849. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ][ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level );
  7850. }
  7851. } else {
  7852. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0 );
  7853. }
  7854. }
  7855. if ( textureNeedsGenerateMipmaps( texture ) ) {
  7856. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  7857. }
  7858. state.unbindTexture();
  7859. } else if ( isMultipleRenderTargets ) {
  7860. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  7861. const attachment = textures[ i ];
  7862. const attachmentProperties = properties.get( attachment );
  7863. let glTextureType = _gl.TEXTURE_2D;
  7864. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  7865. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  7866. }
  7867. state.bindTexture( glTextureType, attachmentProperties.__webglTexture );
  7868. setTextureParameters( glTextureType, attachment );
  7869. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, glTextureType, 0 );
  7870. if ( textureNeedsGenerateMipmaps( attachment ) ) {
  7871. generateMipmap( glTextureType );
  7872. }
  7873. }
  7874. state.unbindTexture();
  7875. } else {
  7876. let glTextureType = _gl.TEXTURE_2D;
  7877. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  7878. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  7879. }
  7880. state.bindTexture( glTextureType, textureProperties.__webglTexture );
  7881. setTextureParameters( glTextureType, texture );
  7882. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  7883. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  7884. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, level );
  7885. }
  7886. } else {
  7887. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, 0 );
  7888. }
  7889. if ( textureNeedsGenerateMipmaps( texture ) ) {
  7890. generateMipmap( glTextureType );
  7891. }
  7892. state.unbindTexture();
  7893. }
  7894. // Setup depth and stencil buffers
  7895. if ( renderTarget.depthBuffer ) {
  7896. setupDepthRenderbuffer( renderTarget );
  7897. }
  7898. }
  7899. function updateRenderTargetMipmap( renderTarget ) {
  7900. const textures = renderTarget.textures;
  7901. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  7902. const texture = textures[ i ];
  7903. if ( textureNeedsGenerateMipmaps( texture ) ) {
  7904. const targetType = getTargetType( renderTarget );
  7905. const webglTexture = properties.get( texture ).__webglTexture;
  7906. state.bindTexture( targetType, webglTexture );
  7907. generateMipmap( targetType );
  7908. state.unbindTexture();
  7909. }
  7910. }
  7911. }
  7912. const invalidationArrayRead = [];
  7913. const invalidationArrayDraw = [];
  7914. function updateMultisampleRenderTarget( renderTarget ) {
  7915. if ( renderTarget.samples > 0 ) {
  7916. if ( useMultisampledRTT( renderTarget ) === false ) {
  7917. const textures = renderTarget.textures;
  7918. const width = renderTarget.width;
  7919. const height = renderTarget.height;
  7920. let mask = _gl.COLOR_BUFFER_BIT;
  7921. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  7922. const renderTargetProperties = properties.get( renderTarget );
  7923. const isMultipleRenderTargets = ( textures.length > 1 );
  7924. // If MRT we need to remove FBO attachments
  7925. if ( isMultipleRenderTargets ) {
  7926. for ( let i = 0; i < textures.length; i ++ ) {
  7927. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  7928. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null );
  7929. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  7930. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0 );
  7931. }
  7932. }
  7933. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  7934. const mipmaps = renderTarget.texture.mipmaps;
  7935. if ( mipmaps && mipmaps.length > 0 ) {
  7936. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ 0 ] );
  7937. } else {
  7938. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  7939. }
  7940. for ( let i = 0; i < textures.length; i ++ ) {
  7941. if ( renderTarget.resolveDepthBuffer ) {
  7942. if ( renderTarget.depthBuffer ) mask |= _gl.DEPTH_BUFFER_BIT;
  7943. // resolving stencil is slow with a D3D backend. disable it for all transmission render targets (see #27799)
  7944. if ( renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer ) mask |= _gl.STENCIL_BUFFER_BIT;
  7945. }
  7946. if ( isMultipleRenderTargets ) {
  7947. _gl.framebufferRenderbuffer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  7948. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  7949. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0 );
  7950. }
  7951. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST );
  7952. if ( supportsInvalidateFramebuffer === true ) {
  7953. invalidationArrayRead.length = 0;
  7954. invalidationArrayDraw.length = 0;
  7955. invalidationArrayRead.push( _gl.COLOR_ATTACHMENT0 + i );
  7956. if ( renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false ) {
  7957. invalidationArrayRead.push( depthStyle );
  7958. invalidationArrayDraw.push( depthStyle );
  7959. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, invalidationArrayDraw );
  7960. }
  7961. _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, invalidationArrayRead );
  7962. }
  7963. }
  7964. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  7965. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  7966. // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments
  7967. if ( isMultipleRenderTargets ) {
  7968. for ( let i = 0; i < textures.length; i ++ ) {
  7969. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  7970. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  7971. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  7972. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  7973. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0 );
  7974. }
  7975. }
  7976. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  7977. } else {
  7978. if ( renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false && supportsInvalidateFramebuffer ) {
  7979. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  7980. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, [ depthStyle ] );
  7981. }
  7982. }
  7983. }
  7984. }
  7985. function getRenderTargetSamples( renderTarget ) {
  7986. return Math.min( capabilities.maxSamples, renderTarget.samples );
  7987. }
  7988. function useMultisampledRTT( renderTarget ) {
  7989. const renderTargetProperties = properties.get( renderTarget );
  7990. return renderTarget.samples > 0 && extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTargetProperties.__useRenderToTexture !== false;
  7991. }
  7992. function updateVideoTexture( texture ) {
  7993. const frame = info.render.frame;
  7994. // Check the last frame we updated the VideoTexture
  7995. if ( _videoTextures.get( texture ) !== frame ) {
  7996. _videoTextures.set( texture, frame );
  7997. texture.update();
  7998. }
  7999. }
  8000. function verifyColorSpace( texture, image ) {
  8001. const colorSpace = texture.colorSpace;
  8002. const format = texture.format;
  8003. const type = texture.type;
  8004. if ( texture.isCompressedTexture === true || texture.isVideoTexture === true ) return image;
  8005. if ( colorSpace !== LinearSRGBColorSpace && colorSpace !== NoColorSpace ) {
  8006. // sRGB
  8007. if ( ColorManagement.getTransfer( colorSpace ) === SRGBTransfer ) {
  8008. // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
  8009. if ( format !== RGBAFormat || type !== UnsignedByteType ) {
  8010. warn( 'WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' );
  8011. }
  8012. } else {
  8013. error( 'WebGLTextures: Unsupported texture color space:', colorSpace );
  8014. }
  8015. }
  8016. return image;
  8017. }
  8018. function getDimensions( image ) {
  8019. if ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) {
  8020. // if intrinsic data are not available, fallback to width/height
  8021. _imageDimensions.width = image.naturalWidth || image.width;
  8022. _imageDimensions.height = image.naturalHeight || image.height;
  8023. } else if ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) {
  8024. _imageDimensions.width = image.displayWidth;
  8025. _imageDimensions.height = image.displayHeight;
  8026. } else {
  8027. _imageDimensions.width = image.width;
  8028. _imageDimensions.height = image.height;
  8029. }
  8030. return _imageDimensions;
  8031. }
  8032. //
  8033. this.allocateTextureUnit = allocateTextureUnit;
  8034. this.resetTextureUnits = resetTextureUnits;
  8035. this.setTexture2D = setTexture2D;
  8036. this.setTexture2DArray = setTexture2DArray;
  8037. this.setTexture3D = setTexture3D;
  8038. this.setTextureCube = setTextureCube;
  8039. this.rebindTextures = rebindTextures;
  8040. this.setupRenderTarget = setupRenderTarget;
  8041. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  8042. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  8043. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  8044. this.setupFrameBufferTexture = setupFrameBufferTexture;
  8045. this.useMultisampledRTT = useMultisampledRTT;
  8046. this.isReversedDepthBuffer = function () {
  8047. return state.buffers.depth.getReversed();
  8048. };
  8049. }
  8050. function WebGLUtils( gl, extensions ) {
  8051. function convert( p, colorSpace = NoColorSpace ) {
  8052. let extension;
  8053. const transfer = ColorManagement.getTransfer( colorSpace );
  8054. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  8055. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  8056. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  8057. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  8058. if ( p === UnsignedInt101111Type ) return gl.UNSIGNED_INT_10F_11F_11F_REV;
  8059. if ( p === ByteType ) return gl.BYTE;
  8060. if ( p === ShortType ) return gl.SHORT;
  8061. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  8062. if ( p === IntType ) return gl.INT;
  8063. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  8064. if ( p === FloatType ) return gl.FLOAT;
  8065. if ( p === HalfFloatType ) return gl.HALF_FLOAT;
  8066. if ( p === AlphaFormat ) return gl.ALPHA;
  8067. if ( p === RGBFormat ) return gl.RGB;
  8068. if ( p === RGBAFormat ) return gl.RGBA;
  8069. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  8070. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  8071. // WebGL2 formats.
  8072. if ( p === RedFormat ) return gl.RED;
  8073. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  8074. if ( p === RGFormat ) return gl.RG;
  8075. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  8076. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  8077. // S3TC
  8078. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  8079. if ( transfer === SRGBTransfer ) {
  8080. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  8081. if ( extension !== null ) {
  8082. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  8083. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  8084. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  8085. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  8086. } else {
  8087. return null;
  8088. }
  8089. } else {
  8090. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  8091. if ( extension !== null ) {
  8092. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  8093. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  8094. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  8095. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  8096. } else {
  8097. return null;
  8098. }
  8099. }
  8100. }
  8101. // PVRTC
  8102. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  8103. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  8104. if ( extension !== null ) {
  8105. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  8106. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  8107. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  8108. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  8109. } else {
  8110. return null;
  8111. }
  8112. }
  8113. // ETC
  8114. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format || p === R11_EAC_Format || p === SIGNED_R11_EAC_Format || p === RG11_EAC_Format || p === SIGNED_RG11_EAC_Format ) {
  8115. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  8116. if ( extension !== null ) {
  8117. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  8118. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  8119. if ( p === R11_EAC_Format ) return extension.COMPRESSED_R11_EAC;
  8120. if ( p === SIGNED_R11_EAC_Format ) return extension.COMPRESSED_SIGNED_R11_EAC;
  8121. if ( p === RG11_EAC_Format ) return extension.COMPRESSED_RG11_EAC;
  8122. if ( p === SIGNED_RG11_EAC_Format ) return extension.COMPRESSED_SIGNED_RG11_EAC;
  8123. } else {
  8124. return null;
  8125. }
  8126. }
  8127. // ASTC
  8128. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  8129. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  8130. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  8131. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  8132. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  8133. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  8134. if ( extension !== null ) {
  8135. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  8136. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  8137. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  8138. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  8139. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  8140. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  8141. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  8142. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  8143. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  8144. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  8145. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  8146. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  8147. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  8148. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  8149. } else {
  8150. return null;
  8151. }
  8152. }
  8153. // BPTC
  8154. if ( p === RGBA_BPTC_Format || p === RGB_BPTC_SIGNED_Format || p === RGB_BPTC_UNSIGNED_Format ) {
  8155. extension = extensions.get( 'EXT_texture_compression_bptc' );
  8156. if ( extension !== null ) {
  8157. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  8158. if ( p === RGB_BPTC_SIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;
  8159. if ( p === RGB_BPTC_UNSIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT;
  8160. } else {
  8161. return null;
  8162. }
  8163. }
  8164. // RGTC
  8165. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  8166. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  8167. if ( extension !== null ) {
  8168. if ( p === RED_RGTC1_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  8169. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  8170. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  8171. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  8172. } else {
  8173. return null;
  8174. }
  8175. }
  8176. //
  8177. if ( p === UnsignedInt248Type ) return gl.UNSIGNED_INT_24_8;
  8178. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  8179. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  8180. }
  8181. return { convert: convert };
  8182. }
  8183. const _occlusion_vertex = `
  8184. void main() {
  8185. gl_Position = vec4( position, 1.0 );
  8186. }`;
  8187. const _occlusion_fragment = `
  8188. uniform sampler2DArray depthColor;
  8189. uniform float depthWidth;
  8190. uniform float depthHeight;
  8191. void main() {
  8192. vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );
  8193. if ( coord.x >= 1.0 ) {
  8194. gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;
  8195. } else {
  8196. gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;
  8197. }
  8198. }`;
  8199. /**
  8200. * A XR module that manages the access to the Depth Sensing API.
  8201. */
  8202. class WebXRDepthSensing {
  8203. /**
  8204. * Constructs a new depth sensing module.
  8205. */
  8206. constructor() {
  8207. /**
  8208. * An opaque texture representing the depth of the user's environment.
  8209. *
  8210. * @type {?ExternalTexture}
  8211. */
  8212. this.texture = null;
  8213. /**
  8214. * A plane mesh for visualizing the depth texture.
  8215. *
  8216. * @type {?Mesh}
  8217. */
  8218. this.mesh = null;
  8219. /**
  8220. * The depth near value.
  8221. *
  8222. * @type {number}
  8223. */
  8224. this.depthNear = 0;
  8225. /**
  8226. * The depth near far.
  8227. *
  8228. * @type {number}
  8229. */
  8230. this.depthFar = 0;
  8231. }
  8232. /**
  8233. * Inits the depth sensing module
  8234. *
  8235. * @param {XRWebGLDepthInformation} depthData - The XR depth data.
  8236. * @param {XRRenderState} renderState - The XR render state.
  8237. */
  8238. init( depthData, renderState ) {
  8239. if ( this.texture === null ) {
  8240. const texture = new ExternalTexture( depthData.texture );
  8241. if ( ( depthData.depthNear !== renderState.depthNear ) || ( depthData.depthFar !== renderState.depthFar ) ) {
  8242. this.depthNear = depthData.depthNear;
  8243. this.depthFar = depthData.depthFar;
  8244. }
  8245. this.texture = texture;
  8246. }
  8247. }
  8248. /**
  8249. * Returns a plane mesh that visualizes the depth texture.
  8250. *
  8251. * @param {ArrayCamera} cameraXR - The XR camera.
  8252. * @return {?Mesh} The plane mesh.
  8253. */
  8254. getMesh( cameraXR ) {
  8255. if ( this.texture !== null ) {
  8256. if ( this.mesh === null ) {
  8257. const viewport = cameraXR.cameras[ 0 ].viewport;
  8258. const material = new ShaderMaterial( {
  8259. vertexShader: _occlusion_vertex,
  8260. fragmentShader: _occlusion_fragment,
  8261. uniforms: {
  8262. depthColor: { value: this.texture },
  8263. depthWidth: { value: viewport.z },
  8264. depthHeight: { value: viewport.w }
  8265. }
  8266. } );
  8267. this.mesh = new Mesh( new PlaneGeometry( 20, 20 ), material );
  8268. }
  8269. }
  8270. return this.mesh;
  8271. }
  8272. /**
  8273. * Resets the module
  8274. */
  8275. reset() {
  8276. this.texture = null;
  8277. this.mesh = null;
  8278. }
  8279. /**
  8280. * Returns a texture representing the depth of the user's environment.
  8281. *
  8282. * @return {?ExternalTexture} The depth texture.
  8283. */
  8284. getDepthTexture() {
  8285. return this.texture;
  8286. }
  8287. }
  8288. /**
  8289. * This class represents an abstraction of the WebXR Device API and is
  8290. * internally used by {@link WebGLRenderer}. `WebXRManager` also provides a public
  8291. * interface that allows users to enable/disable XR and perform XR related
  8292. * tasks like for instance retrieving controllers.
  8293. *
  8294. * @augments EventDispatcher
  8295. * @hideconstructor
  8296. */
  8297. class WebXRManager extends EventDispatcher {
  8298. /**
  8299. * Constructs a new WebGL renderer.
  8300. *
  8301. * @param {WebGLRenderer} renderer - The renderer.
  8302. * @param {WebGL2RenderingContext} gl - The rendering context.
  8303. */
  8304. constructor( renderer, gl ) {
  8305. super();
  8306. const scope = this;
  8307. let session = null;
  8308. let framebufferScaleFactor = 1.0;
  8309. let referenceSpace = null;
  8310. let referenceSpaceType = 'local-floor';
  8311. // Set default foveation to maximum.
  8312. let foveation = 1.0;
  8313. let customReferenceSpace = null;
  8314. let pose = null;
  8315. let glBinding = null;
  8316. let glProjLayer = null;
  8317. let glBaseLayer = null;
  8318. let xrFrame = null;
  8319. const supportsGlBinding = typeof XRWebGLBinding !== 'undefined';
  8320. const depthSensing = new WebXRDepthSensing();
  8321. const cameraAccessTextures = {};
  8322. const attributes = gl.getContextAttributes();
  8323. let initialRenderTarget = null;
  8324. let newRenderTarget = null;
  8325. const controllers = [];
  8326. const controllerInputSources = [];
  8327. const currentSize = new Vector2();
  8328. let currentPixelRatio = null;
  8329. //
  8330. const cameraL = new PerspectiveCamera();
  8331. cameraL.viewport = new Vector4();
  8332. const cameraR = new PerspectiveCamera();
  8333. cameraR.viewport = new Vector4();
  8334. const cameras = [ cameraL, cameraR ];
  8335. const cameraXR = new ArrayCamera();
  8336. let _currentDepthNear = null;
  8337. let _currentDepthFar = null;
  8338. //
  8339. /**
  8340. * Whether the manager's XR camera should be automatically updated or not.
  8341. *
  8342. * @type {boolean}
  8343. * @default true
  8344. */
  8345. this.cameraAutoUpdate = true;
  8346. /**
  8347. * This flag notifies the renderer to be ready for XR rendering. Set it to `true`
  8348. * if you are going to use XR in your app.
  8349. *
  8350. * @type {boolean}
  8351. * @default false
  8352. */
  8353. this.enabled = false;
  8354. /**
  8355. * Whether XR presentation is active or not.
  8356. *
  8357. * @type {boolean}
  8358. * @readonly
  8359. * @default false
  8360. */
  8361. this.isPresenting = false;
  8362. /**
  8363. * Returns a group representing the `target ray` space of the XR controller.
  8364. * Use this space for visualizing 3D objects that support the user in pointing
  8365. * tasks like UI interaction.
  8366. *
  8367. * @param {number} index - The index of the controller.
  8368. * @return {Group} A group representing the `target ray` space.
  8369. */
  8370. this.getController = function ( index ) {
  8371. let controller = controllers[ index ];
  8372. if ( controller === undefined ) {
  8373. controller = new WebXRController();
  8374. controllers[ index ] = controller;
  8375. }
  8376. return controller.getTargetRaySpace();
  8377. };
  8378. /**
  8379. * Returns a group representing the `grip` space of the XR controller.
  8380. * Use this space for visualizing 3D objects that support the user in pointing
  8381. * tasks like UI interaction.
  8382. *
  8383. * Note: If you want to show something in the user's hand AND offer a
  8384. * pointing ray at the same time, you'll want to attached the handheld object
  8385. * to the group returned by `getControllerGrip()` and the ray to the
  8386. * group returned by `getController()`. The idea is to have two
  8387. * different groups in two different coordinate spaces for the same WebXR
  8388. * controller.
  8389. *
  8390. * @param {number} index - The index of the controller.
  8391. * @return {Group} A group representing the `grip` space.
  8392. */
  8393. this.getControllerGrip = function ( index ) {
  8394. let controller = controllers[ index ];
  8395. if ( controller === undefined ) {
  8396. controller = new WebXRController();
  8397. controllers[ index ] = controller;
  8398. }
  8399. return controller.getGripSpace();
  8400. };
  8401. /**
  8402. * Returns a group representing the `hand` space of the XR controller.
  8403. * Use this space for visualizing 3D objects that support the user in pointing
  8404. * tasks like UI interaction.
  8405. *
  8406. * @param {number} index - The index of the controller.
  8407. * @return {Group} A group representing the `hand` space.
  8408. */
  8409. this.getHand = function ( index ) {
  8410. let controller = controllers[ index ];
  8411. if ( controller === undefined ) {
  8412. controller = new WebXRController();
  8413. controllers[ index ] = controller;
  8414. }
  8415. return controller.getHandSpace();
  8416. };
  8417. //
  8418. function onSessionEvent( event ) {
  8419. const controllerIndex = controllerInputSources.indexOf( event.inputSource );
  8420. if ( controllerIndex === -1 ) {
  8421. return;
  8422. }
  8423. const controller = controllers[ controllerIndex ];
  8424. if ( controller !== undefined ) {
  8425. controller.update( event.inputSource, event.frame, customReferenceSpace || referenceSpace );
  8426. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  8427. }
  8428. }
  8429. function onSessionEnd() {
  8430. session.removeEventListener( 'select', onSessionEvent );
  8431. session.removeEventListener( 'selectstart', onSessionEvent );
  8432. session.removeEventListener( 'selectend', onSessionEvent );
  8433. session.removeEventListener( 'squeeze', onSessionEvent );
  8434. session.removeEventListener( 'squeezestart', onSessionEvent );
  8435. session.removeEventListener( 'squeezeend', onSessionEvent );
  8436. session.removeEventListener( 'end', onSessionEnd );
  8437. session.removeEventListener( 'inputsourceschange', onInputSourcesChange );
  8438. for ( let i = 0; i < controllers.length; i ++ ) {
  8439. const inputSource = controllerInputSources[ i ];
  8440. if ( inputSource === null ) continue;
  8441. controllerInputSources[ i ] = null;
  8442. controllers[ i ].disconnect( inputSource );
  8443. }
  8444. _currentDepthNear = null;
  8445. _currentDepthFar = null;
  8446. depthSensing.reset();
  8447. for ( const key in cameraAccessTextures ) {
  8448. delete cameraAccessTextures[ key ];
  8449. }
  8450. // restore framebuffer/rendering state
  8451. renderer.setRenderTarget( initialRenderTarget );
  8452. glBaseLayer = null;
  8453. glProjLayer = null;
  8454. glBinding = null;
  8455. session = null;
  8456. newRenderTarget = null;
  8457. //
  8458. animation.stop();
  8459. scope.isPresenting = false;
  8460. renderer.setPixelRatio( currentPixelRatio );
  8461. renderer.setSize( currentSize.width, currentSize.height, false );
  8462. scope.dispatchEvent( { type: 'sessionend' } );
  8463. }
  8464. /**
  8465. * Sets the framebuffer scale factor.
  8466. *
  8467. * This method can not be used during a XR session.
  8468. *
  8469. * @param {number} value - The framebuffer scale factor.
  8470. */
  8471. this.setFramebufferScaleFactor = function ( value ) {
  8472. framebufferScaleFactor = value;
  8473. if ( scope.isPresenting === true ) {
  8474. warn( 'WebXRManager: Cannot change framebuffer scale while presenting.' );
  8475. }
  8476. };
  8477. /**
  8478. * Sets the reference space type. Can be used to configure a spatial relationship with the user's physical
  8479. * environment. Depending on how the user moves in 3D space, setting an appropriate reference space can
  8480. * improve tracking. Default is `local-floor`. Valid values can be found here
  8481. * https://developer.mozilla.org/en-US/docs/Web/API/XRReferenceSpace#reference_space_types.
  8482. *
  8483. * This method can not be used during a XR session.
  8484. *
  8485. * @param {string} value - The reference space type.
  8486. */
  8487. this.setReferenceSpaceType = function ( value ) {
  8488. referenceSpaceType = value;
  8489. if ( scope.isPresenting === true ) {
  8490. warn( 'WebXRManager: Cannot change reference space type while presenting.' );
  8491. }
  8492. };
  8493. /**
  8494. * Returns the XR reference space.
  8495. *
  8496. * @return {XRReferenceSpace} The XR reference space.
  8497. */
  8498. this.getReferenceSpace = function () {
  8499. return customReferenceSpace || referenceSpace;
  8500. };
  8501. /**
  8502. * Sets a custom XR reference space.
  8503. *
  8504. * @param {XRReferenceSpace} space - The XR reference space.
  8505. */
  8506. this.setReferenceSpace = function ( space ) {
  8507. customReferenceSpace = space;
  8508. };
  8509. /**
  8510. * Returns the current base layer.
  8511. *
  8512. * This is an `XRProjectionLayer` when the targeted XR device supports the
  8513. * WebXR Layers API, or an `XRWebGLLayer` otherwise.
  8514. *
  8515. * @return {?(XRWebGLLayer|XRProjectionLayer)} The XR base layer.
  8516. */
  8517. this.getBaseLayer = function () {
  8518. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  8519. };
  8520. /**
  8521. * Returns the current XR binding.
  8522. *
  8523. * Creates a new binding if needed and the browser is
  8524. * capable of doing so.
  8525. *
  8526. * @return {?XRWebGLBinding} The XR binding. Returns `null` if one cannot be created.
  8527. */
  8528. this.getBinding = function () {
  8529. if ( glBinding === null && supportsGlBinding ) {
  8530. glBinding = new XRWebGLBinding( session, gl );
  8531. }
  8532. return glBinding;
  8533. };
  8534. /**
  8535. * Returns the current XR frame.
  8536. *
  8537. * @return {?XRFrame} The XR frame. Returns `null` when used outside a XR session.
  8538. */
  8539. this.getFrame = function () {
  8540. return xrFrame;
  8541. };
  8542. /**
  8543. * Returns the current XR session.
  8544. *
  8545. * @return {?XRSession} The XR session. Returns `null` when used outside a XR session.
  8546. */
  8547. this.getSession = function () {
  8548. return session;
  8549. };
  8550. /**
  8551. * After a XR session has been requested usually with one of the `*Button` modules, it
  8552. * is injected into the renderer with this method. This method triggers the start of
  8553. * the actual XR rendering.
  8554. *
  8555. * @async
  8556. * @param {XRSession} value - The XR session to set.
  8557. * @return {Promise} A Promise that resolves when the session has been set.
  8558. */
  8559. this.setSession = async function ( value ) {
  8560. session = value;
  8561. if ( session !== null ) {
  8562. initialRenderTarget = renderer.getRenderTarget();
  8563. session.addEventListener( 'select', onSessionEvent );
  8564. session.addEventListener( 'selectstart', onSessionEvent );
  8565. session.addEventListener( 'selectend', onSessionEvent );
  8566. session.addEventListener( 'squeeze', onSessionEvent );
  8567. session.addEventListener( 'squeezestart', onSessionEvent );
  8568. session.addEventListener( 'squeezeend', onSessionEvent );
  8569. session.addEventListener( 'end', onSessionEnd );
  8570. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  8571. if ( attributes.xrCompatible !== true ) {
  8572. await gl.makeXRCompatible();
  8573. }
  8574. currentPixelRatio = renderer.getPixelRatio();
  8575. renderer.getSize( currentSize );
  8576. // Check that the browser implements the necessary APIs to use an
  8577. // XRProjectionLayer rather than an XRWebGLLayer
  8578. const supportsLayers = supportsGlBinding && 'createProjectionLayer' in XRWebGLBinding.prototype;
  8579. if ( ! supportsLayers ) {
  8580. const layerInit = {
  8581. antialias: attributes.antialias,
  8582. alpha: true,
  8583. depth: attributes.depth,
  8584. stencil: attributes.stencil,
  8585. framebufferScaleFactor: framebufferScaleFactor
  8586. };
  8587. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  8588. session.updateRenderState( { baseLayer: glBaseLayer } );
  8589. renderer.setPixelRatio( 1 );
  8590. renderer.setSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, false );
  8591. newRenderTarget = new WebGLRenderTarget(
  8592. glBaseLayer.framebufferWidth,
  8593. glBaseLayer.framebufferHeight,
  8594. {
  8595. format: RGBAFormat,
  8596. type: UnsignedByteType,
  8597. colorSpace: renderer.outputColorSpace,
  8598. stencilBuffer: attributes.stencil,
  8599. resolveDepthBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  8600. resolveStencilBuffer: ( glBaseLayer.ignoreDepthValues === false )
  8601. }
  8602. );
  8603. } else {
  8604. let depthFormat = null;
  8605. let depthType = null;
  8606. let glDepthFormat = null;
  8607. if ( attributes.depth ) {
  8608. glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  8609. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  8610. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
  8611. }
  8612. const projectionlayerInit = {
  8613. colorFormat: gl.RGBA8,
  8614. depthFormat: glDepthFormat,
  8615. scaleFactor: framebufferScaleFactor
  8616. };
  8617. glBinding = this.getBinding();
  8618. glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  8619. session.updateRenderState( { layers: [ glProjLayer ] } );
  8620. renderer.setPixelRatio( 1 );
  8621. renderer.setSize( glProjLayer.textureWidth, glProjLayer.textureHeight, false );
  8622. newRenderTarget = new WebGLRenderTarget(
  8623. glProjLayer.textureWidth,
  8624. glProjLayer.textureHeight,
  8625. {
  8626. format: RGBAFormat,
  8627. type: UnsignedByteType,
  8628. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  8629. stencilBuffer: attributes.stencil,
  8630. colorSpace: renderer.outputColorSpace,
  8631. samples: attributes.antialias ? 4 : 0,
  8632. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false ),
  8633. resolveStencilBuffer: ( glProjLayer.ignoreDepthValues === false )
  8634. } );
  8635. }
  8636. newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  8637. this.setFoveation( foveation );
  8638. customReferenceSpace = null;
  8639. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  8640. animation.setContext( session );
  8641. animation.start();
  8642. scope.isPresenting = true;
  8643. scope.dispatchEvent( { type: 'sessionstart' } );
  8644. }
  8645. };
  8646. /**
  8647. * Returns the environment blend mode from the current XR session.
  8648. *
  8649. * @return {'opaque'|'additive'|'alpha-blend'|undefined} The environment blend mode. Returns `undefined` when used outside of a XR session.
  8650. */
  8651. this.getEnvironmentBlendMode = function () {
  8652. if ( session !== null ) {
  8653. return session.environmentBlendMode;
  8654. }
  8655. };
  8656. /**
  8657. * Returns the current depth texture computed via depth sensing.
  8658. *
  8659. * See {@link WebXRDepthSensing#getDepthTexture}.
  8660. *
  8661. * @return {?Texture} The depth texture.
  8662. */
  8663. this.getDepthTexture = function () {
  8664. return depthSensing.getDepthTexture();
  8665. };
  8666. function onInputSourcesChange( event ) {
  8667. // Notify disconnected
  8668. for ( let i = 0; i < event.removed.length; i ++ ) {
  8669. const inputSource = event.removed[ i ];
  8670. const index = controllerInputSources.indexOf( inputSource );
  8671. if ( index >= 0 ) {
  8672. controllerInputSources[ index ] = null;
  8673. controllers[ index ].disconnect( inputSource );
  8674. }
  8675. }
  8676. // Notify connected
  8677. for ( let i = 0; i < event.added.length; i ++ ) {
  8678. const inputSource = event.added[ i ];
  8679. let controllerIndex = controllerInputSources.indexOf( inputSource );
  8680. if ( controllerIndex === -1 ) {
  8681. // Assign input source a controller that currently has no input source
  8682. for ( let i = 0; i < controllers.length; i ++ ) {
  8683. if ( i >= controllerInputSources.length ) {
  8684. controllerInputSources.push( inputSource );
  8685. controllerIndex = i;
  8686. break;
  8687. } else if ( controllerInputSources[ i ] === null ) {
  8688. controllerInputSources[ i ] = inputSource;
  8689. controllerIndex = i;
  8690. break;
  8691. }
  8692. }
  8693. // If all controllers do currently receive input we ignore new ones
  8694. if ( controllerIndex === -1 ) break;
  8695. }
  8696. const controller = controllers[ controllerIndex ];
  8697. if ( controller ) {
  8698. controller.connect( inputSource );
  8699. }
  8700. }
  8701. }
  8702. //
  8703. const cameraLPos = new Vector3();
  8704. const cameraRPos = new Vector3();
  8705. /**
  8706. * Assumes 2 cameras that are parallel and share an X-axis, and that
  8707. * the cameras' projection and world matrices have already been set.
  8708. * And that near and far planes are identical for both cameras.
  8709. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  8710. *
  8711. * @param {ArrayCamera} camera - The camera to update.
  8712. * @param {PerspectiveCamera} cameraL - The left camera.
  8713. * @param {PerspectiveCamera} cameraR - The right camera.
  8714. */
  8715. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  8716. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  8717. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  8718. const ipd = cameraLPos.distanceTo( cameraRPos );
  8719. const projL = cameraL.projectionMatrix.elements;
  8720. const projR = cameraR.projectionMatrix.elements;
  8721. // VR systems will have identical far and near planes, and
  8722. // most likely identical top and bottom frustum extents.
  8723. // Use the left camera for these values.
  8724. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  8725. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  8726. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  8727. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  8728. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  8729. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  8730. const left = near * leftFov;
  8731. const right = near * rightFov;
  8732. // Calculate the new camera's position offset from the
  8733. // left camera. xOffset should be roughly half `ipd`.
  8734. const zOffset = ipd / ( - leftFov + rightFov );
  8735. const xOffset = zOffset * - leftFov;
  8736. // TODO: Better way to apply this offset?
  8737. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  8738. camera.translateX( xOffset );
  8739. camera.translateZ( zOffset );
  8740. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  8741. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  8742. // Check if the projection uses an infinite far plane.
  8743. if ( projL[ 10 ] === -1 ) {
  8744. // Use the projection matrix from the left eye.
  8745. // The camera offset is sufficient to include the view volumes
  8746. // of both eyes (assuming symmetric projections).
  8747. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  8748. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  8749. } else {
  8750. // Find the union of the frustum values of the cameras and scale
  8751. // the values so that the near plane's position does not change in world space,
  8752. // although must now be relative to the new union camera.
  8753. const near2 = near + zOffset;
  8754. const far2 = far + zOffset;
  8755. const left2 = left - xOffset;
  8756. const right2 = right + ( ipd - xOffset );
  8757. const top2 = topFov * far / far2 * near2;
  8758. const bottom2 = bottomFov * far / far2 * near2;
  8759. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  8760. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  8761. }
  8762. }
  8763. function updateCamera( camera, parent ) {
  8764. if ( parent === null ) {
  8765. camera.matrixWorld.copy( camera.matrix );
  8766. } else {
  8767. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  8768. }
  8769. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  8770. }
  8771. /**
  8772. * Updates the state of the XR camera. Use this method on app level if you
  8773. * set `cameraAutoUpdate` to `false`. The method requires the non-XR
  8774. * camera of the scene as a parameter. The passed in camera's transformation
  8775. * is automatically adjusted to the position of the XR camera when calling
  8776. * this method.
  8777. *
  8778. * @param {Camera} camera - The camera.
  8779. */
  8780. this.updateCamera = function ( camera ) {
  8781. if ( session === null ) return;
  8782. let depthNear = camera.near;
  8783. let depthFar = camera.far;
  8784. if ( depthSensing.texture !== null ) {
  8785. if ( depthSensing.depthNear > 0 ) depthNear = depthSensing.depthNear;
  8786. if ( depthSensing.depthFar > 0 ) depthFar = depthSensing.depthFar;
  8787. }
  8788. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  8789. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  8790. if ( _currentDepthNear !== cameraXR.near || _currentDepthFar !== cameraXR.far ) {
  8791. // Note that the new renderState won't apply until the next frame. See #18320
  8792. session.updateRenderState( {
  8793. depthNear: cameraXR.near,
  8794. depthFar: cameraXR.far
  8795. } );
  8796. _currentDepthNear = cameraXR.near;
  8797. _currentDepthFar = cameraXR.far;
  8798. }
  8799. // inherit camera layers and enable eye layers (1 = left, 2 = right)
  8800. cameraXR.layers.mask = camera.layers.mask | 0b110;
  8801. cameraL.layers.mask = cameraXR.layers.mask & 0b011;
  8802. cameraR.layers.mask = cameraXR.layers.mask & 0b101;
  8803. const parent = camera.parent;
  8804. const cameras = cameraXR.cameras;
  8805. updateCamera( cameraXR, parent );
  8806. for ( let i = 0; i < cameras.length; i ++ ) {
  8807. updateCamera( cameras[ i ], parent );
  8808. }
  8809. // update projection matrix for proper view frustum culling
  8810. if ( cameras.length === 2 ) {
  8811. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  8812. } else {
  8813. // assume single camera setup (AR)
  8814. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  8815. }
  8816. // update user camera and its children
  8817. updateUserCamera( camera, cameraXR, parent );
  8818. };
  8819. function updateUserCamera( camera, cameraXR, parent ) {
  8820. if ( parent === null ) {
  8821. camera.matrix.copy( cameraXR.matrixWorld );
  8822. } else {
  8823. camera.matrix.copy( parent.matrixWorld );
  8824. camera.matrix.invert();
  8825. camera.matrix.multiply( cameraXR.matrixWorld );
  8826. }
  8827. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  8828. camera.updateMatrixWorld( true );
  8829. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  8830. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  8831. if ( camera.isPerspectiveCamera ) {
  8832. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  8833. camera.zoom = 1;
  8834. }
  8835. }
  8836. /**
  8837. * Returns an instance of {@link ArrayCamera} which represents the XR camera
  8838. * of the active XR session. For each view it holds a separate camera object.
  8839. *
  8840. * The camera's `fov` is currently not used and does not reflect the fov of
  8841. * the XR camera. If you need the fov on app level, you have to compute in
  8842. * manually from the XR camera's projection matrices.
  8843. *
  8844. * @return {ArrayCamera} The XR camera.
  8845. */
  8846. this.getCamera = function () {
  8847. return cameraXR;
  8848. };
  8849. /**
  8850. * Returns the amount of foveation used by the XR compositor for the projection layer.
  8851. *
  8852. * @return {number|undefined} The amount of foveation.
  8853. */
  8854. this.getFoveation = function () {
  8855. if ( glProjLayer === null && glBaseLayer === null ) {
  8856. return undefined;
  8857. }
  8858. return foveation;
  8859. };
  8860. /**
  8861. * Sets the foveation value.
  8862. *
  8863. * @param {number} value - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  8864. * and `1` means maximum foveation (the edges render at lower resolution).
  8865. */
  8866. this.setFoveation = function ( value ) {
  8867. // 0 = no foveation = full resolution
  8868. // 1 = maximum foveation = the edges render at lower resolution
  8869. foveation = value;
  8870. if ( glProjLayer !== null ) {
  8871. glProjLayer.fixedFoveation = value;
  8872. }
  8873. if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) {
  8874. glBaseLayer.fixedFoveation = value;
  8875. }
  8876. };
  8877. /**
  8878. * Returns `true` if depth sensing is supported.
  8879. *
  8880. * @return {boolean} Whether depth sensing is supported or not.
  8881. */
  8882. this.hasDepthSensing = function () {
  8883. return depthSensing.texture !== null;
  8884. };
  8885. /**
  8886. * Returns the depth sensing mesh.
  8887. *
  8888. * See {@link WebXRDepthSensing#getMesh}.
  8889. *
  8890. * @return {Mesh} The depth sensing mesh.
  8891. */
  8892. this.getDepthSensingMesh = function () {
  8893. return depthSensing.getMesh( cameraXR );
  8894. };
  8895. /**
  8896. * Retrieves an opaque texture from the view-aligned {@link XRCamera}.
  8897. * Only available during the current animation loop.
  8898. *
  8899. * @param {XRCamera} xrCamera - The camera to query.
  8900. * @return {?Texture} An opaque texture representing the current raw camera frame.
  8901. */
  8902. this.getCameraTexture = function ( xrCamera ) {
  8903. return cameraAccessTextures[ xrCamera ];
  8904. };
  8905. // Animation Loop
  8906. let onAnimationFrameCallback = null;
  8907. function onAnimationFrame( time, frame ) {
  8908. pose = frame.getViewerPose( customReferenceSpace || referenceSpace );
  8909. xrFrame = frame;
  8910. if ( pose !== null ) {
  8911. const views = pose.views;
  8912. if ( glBaseLayer !== null ) {
  8913. renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer );
  8914. renderer.setRenderTarget( newRenderTarget );
  8915. }
  8916. let cameraXRNeedsUpdate = false;
  8917. // check if it's necessary to rebuild cameraXR's camera list
  8918. if ( views.length !== cameraXR.cameras.length ) {
  8919. cameraXR.cameras.length = 0;
  8920. cameraXRNeedsUpdate = true;
  8921. }
  8922. for ( let i = 0; i < views.length; i ++ ) {
  8923. const view = views[ i ];
  8924. let viewport = null;
  8925. if ( glBaseLayer !== null ) {
  8926. viewport = glBaseLayer.getViewport( view );
  8927. } else {
  8928. const glSubImage = glBinding.getViewSubImage( glProjLayer, view );
  8929. viewport = glSubImage.viewport;
  8930. // For side-by-side projection, we only produce a single texture for both eyes.
  8931. if ( i === 0 ) {
  8932. renderer.setRenderTargetTextures(
  8933. newRenderTarget,
  8934. glSubImage.colorTexture,
  8935. glSubImage.depthStencilTexture );
  8936. renderer.setRenderTarget( newRenderTarget );
  8937. }
  8938. }
  8939. let camera = cameras[ i ];
  8940. if ( camera === undefined ) {
  8941. camera = new PerspectiveCamera();
  8942. camera.layers.enable( i );
  8943. camera.viewport = new Vector4();
  8944. cameras[ i ] = camera;
  8945. }
  8946. camera.matrix.fromArray( view.transform.matrix );
  8947. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  8948. camera.projectionMatrix.fromArray( view.projectionMatrix );
  8949. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  8950. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  8951. if ( i === 0 ) {
  8952. cameraXR.matrix.copy( camera.matrix );
  8953. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  8954. }
  8955. if ( cameraXRNeedsUpdate === true ) {
  8956. cameraXR.cameras.push( camera );
  8957. }
  8958. }
  8959. //
  8960. const enabledFeatures = session.enabledFeatures;
  8961. const gpuDepthSensingEnabled = enabledFeatures &&
  8962. enabledFeatures.includes( 'depth-sensing' ) &&
  8963. session.depthUsage == 'gpu-optimized';
  8964. if ( gpuDepthSensingEnabled && supportsGlBinding ) {
  8965. glBinding = scope.getBinding();
  8966. const depthData = glBinding.getDepthInformation( views[ 0 ] );
  8967. if ( depthData && depthData.isValid && depthData.texture ) {
  8968. depthSensing.init( depthData, session.renderState );
  8969. }
  8970. }
  8971. const cameraAccessEnabled = enabledFeatures &&
  8972. enabledFeatures.includes( 'camera-access' );
  8973. if ( cameraAccessEnabled && supportsGlBinding ) {
  8974. renderer.state.unbindTexture();
  8975. glBinding = scope.getBinding();
  8976. for ( let i = 0; i < views.length; i ++ ) {
  8977. const camera = views[ i ].camera;
  8978. if ( camera ) {
  8979. let cameraTex = cameraAccessTextures[ camera ];
  8980. if ( ! cameraTex ) {
  8981. cameraTex = new ExternalTexture();
  8982. cameraAccessTextures[ camera ] = cameraTex;
  8983. }
  8984. const glTexture = glBinding.getCameraImage( camera );
  8985. cameraTex.sourceTexture = glTexture;
  8986. }
  8987. }
  8988. }
  8989. }
  8990. //
  8991. for ( let i = 0; i < controllers.length; i ++ ) {
  8992. const inputSource = controllerInputSources[ i ];
  8993. const controller = controllers[ i ];
  8994. if ( inputSource !== null && controller !== undefined ) {
  8995. controller.update( inputSource, frame, customReferenceSpace || referenceSpace );
  8996. }
  8997. }
  8998. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  8999. if ( frame.detectedPlanes ) {
  9000. scope.dispatchEvent( { type: 'planesdetected', data: frame } );
  9001. }
  9002. xrFrame = null;
  9003. }
  9004. const animation = new WebGLAnimation();
  9005. animation.setAnimationLoop( onAnimationFrame );
  9006. this.setAnimationLoop = function ( callback ) {
  9007. onAnimationFrameCallback = callback;
  9008. };
  9009. this.dispose = function () {};
  9010. }
  9011. }
  9012. const _e1 = /*@__PURE__*/ new Euler();
  9013. const _m1 = /*@__PURE__*/ new Matrix4();
  9014. function WebGLMaterials( renderer, properties ) {
  9015. function refreshTransformUniform( map, uniform ) {
  9016. if ( map.matrixAutoUpdate === true ) {
  9017. map.updateMatrix();
  9018. }
  9019. uniform.value.copy( map.matrix );
  9020. }
  9021. function refreshFogUniforms( uniforms, fog ) {
  9022. fog.color.getRGB( uniforms.fogColor.value, getUnlitUniformColorSpace( renderer ) );
  9023. if ( fog.isFog ) {
  9024. uniforms.fogNear.value = fog.near;
  9025. uniforms.fogFar.value = fog.far;
  9026. } else if ( fog.isFogExp2 ) {
  9027. uniforms.fogDensity.value = fog.density;
  9028. }
  9029. }
  9030. function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) {
  9031. if ( material.isMeshBasicMaterial ) {
  9032. refreshUniformsCommon( uniforms, material );
  9033. } else if ( material.isMeshLambertMaterial ) {
  9034. refreshUniformsCommon( uniforms, material );
  9035. } else if ( material.isMeshToonMaterial ) {
  9036. refreshUniformsCommon( uniforms, material );
  9037. refreshUniformsToon( uniforms, material );
  9038. } else if ( material.isMeshPhongMaterial ) {
  9039. refreshUniformsCommon( uniforms, material );
  9040. refreshUniformsPhong( uniforms, material );
  9041. } else if ( material.isMeshStandardMaterial ) {
  9042. refreshUniformsCommon( uniforms, material );
  9043. refreshUniformsStandard( uniforms, material );
  9044. if ( material.isMeshPhysicalMaterial ) {
  9045. refreshUniformsPhysical( uniforms, material, transmissionRenderTarget );
  9046. }
  9047. } else if ( material.isMeshMatcapMaterial ) {
  9048. refreshUniformsCommon( uniforms, material );
  9049. refreshUniformsMatcap( uniforms, material );
  9050. } else if ( material.isMeshDepthMaterial ) {
  9051. refreshUniformsCommon( uniforms, material );
  9052. } else if ( material.isMeshDistanceMaterial ) {
  9053. refreshUniformsCommon( uniforms, material );
  9054. refreshUniformsDistance( uniforms, material );
  9055. } else if ( material.isMeshNormalMaterial ) {
  9056. refreshUniformsCommon( uniforms, material );
  9057. } else if ( material.isLineBasicMaterial ) {
  9058. refreshUniformsLine( uniforms, material );
  9059. if ( material.isLineDashedMaterial ) {
  9060. refreshUniformsDash( uniforms, material );
  9061. }
  9062. } else if ( material.isPointsMaterial ) {
  9063. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  9064. } else if ( material.isSpriteMaterial ) {
  9065. refreshUniformsSprites( uniforms, material );
  9066. } else if ( material.isShadowMaterial ) {
  9067. uniforms.color.value.copy( material.color );
  9068. uniforms.opacity.value = material.opacity;
  9069. } else if ( material.isShaderMaterial ) {
  9070. material.uniformsNeedUpdate = false; // #15581
  9071. }
  9072. }
  9073. function refreshUniformsCommon( uniforms, material ) {
  9074. uniforms.opacity.value = material.opacity;
  9075. if ( material.color ) {
  9076. uniforms.diffuse.value.copy( material.color );
  9077. }
  9078. if ( material.emissive ) {
  9079. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  9080. }
  9081. if ( material.map ) {
  9082. uniforms.map.value = material.map;
  9083. refreshTransformUniform( material.map, uniforms.mapTransform );
  9084. }
  9085. if ( material.alphaMap ) {
  9086. uniforms.alphaMap.value = material.alphaMap;
  9087. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  9088. }
  9089. if ( material.bumpMap ) {
  9090. uniforms.bumpMap.value = material.bumpMap;
  9091. refreshTransformUniform( material.bumpMap, uniforms.bumpMapTransform );
  9092. uniforms.bumpScale.value = material.bumpScale;
  9093. if ( material.side === BackSide ) {
  9094. uniforms.bumpScale.value *= -1;
  9095. }
  9096. }
  9097. if ( material.normalMap ) {
  9098. uniforms.normalMap.value = material.normalMap;
  9099. refreshTransformUniform( material.normalMap, uniforms.normalMapTransform );
  9100. uniforms.normalScale.value.copy( material.normalScale );
  9101. if ( material.side === BackSide ) {
  9102. uniforms.normalScale.value.negate();
  9103. }
  9104. }
  9105. if ( material.displacementMap ) {
  9106. uniforms.displacementMap.value = material.displacementMap;
  9107. refreshTransformUniform( material.displacementMap, uniforms.displacementMapTransform );
  9108. uniforms.displacementScale.value = material.displacementScale;
  9109. uniforms.displacementBias.value = material.displacementBias;
  9110. }
  9111. if ( material.emissiveMap ) {
  9112. uniforms.emissiveMap.value = material.emissiveMap;
  9113. refreshTransformUniform( material.emissiveMap, uniforms.emissiveMapTransform );
  9114. }
  9115. if ( material.specularMap ) {
  9116. uniforms.specularMap.value = material.specularMap;
  9117. refreshTransformUniform( material.specularMap, uniforms.specularMapTransform );
  9118. }
  9119. if ( material.alphaTest > 0 ) {
  9120. uniforms.alphaTest.value = material.alphaTest;
  9121. }
  9122. const materialProperties = properties.get( material );
  9123. const envMap = materialProperties.envMap;
  9124. const envMapRotation = materialProperties.envMapRotation;
  9125. if ( envMap ) {
  9126. uniforms.envMap.value = envMap;
  9127. _e1.copy( envMapRotation );
  9128. // accommodate left-handed frame
  9129. _e1.x *= -1; _e1.y *= -1; _e1.z *= -1;
  9130. if ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) {
  9131. // environment maps which are not cube render targets or PMREMs follow a different convention
  9132. _e1.y *= -1;
  9133. _e1.z *= -1;
  9134. }
  9135. uniforms.envMapRotation.value.setFromMatrix4( _m1.makeRotationFromEuler( _e1 ) );
  9136. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? -1 : 1;
  9137. uniforms.reflectivity.value = material.reflectivity;
  9138. uniforms.ior.value = material.ior;
  9139. uniforms.refractionRatio.value = material.refractionRatio;
  9140. }
  9141. if ( material.lightMap ) {
  9142. uniforms.lightMap.value = material.lightMap;
  9143. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  9144. refreshTransformUniform( material.lightMap, uniforms.lightMapTransform );
  9145. }
  9146. if ( material.aoMap ) {
  9147. uniforms.aoMap.value = material.aoMap;
  9148. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  9149. refreshTransformUniform( material.aoMap, uniforms.aoMapTransform );
  9150. }
  9151. }
  9152. function refreshUniformsLine( uniforms, material ) {
  9153. uniforms.diffuse.value.copy( material.color );
  9154. uniforms.opacity.value = material.opacity;
  9155. if ( material.map ) {
  9156. uniforms.map.value = material.map;
  9157. refreshTransformUniform( material.map, uniforms.mapTransform );
  9158. }
  9159. }
  9160. function refreshUniformsDash( uniforms, material ) {
  9161. uniforms.dashSize.value = material.dashSize;
  9162. uniforms.totalSize.value = material.dashSize + material.gapSize;
  9163. uniforms.scale.value = material.scale;
  9164. }
  9165. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  9166. uniforms.diffuse.value.copy( material.color );
  9167. uniforms.opacity.value = material.opacity;
  9168. uniforms.size.value = material.size * pixelRatio;
  9169. uniforms.scale.value = height * 0.5;
  9170. if ( material.map ) {
  9171. uniforms.map.value = material.map;
  9172. refreshTransformUniform( material.map, uniforms.uvTransform );
  9173. }
  9174. if ( material.alphaMap ) {
  9175. uniforms.alphaMap.value = material.alphaMap;
  9176. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  9177. }
  9178. if ( material.alphaTest > 0 ) {
  9179. uniforms.alphaTest.value = material.alphaTest;
  9180. }
  9181. }
  9182. function refreshUniformsSprites( uniforms, material ) {
  9183. uniforms.diffuse.value.copy( material.color );
  9184. uniforms.opacity.value = material.opacity;
  9185. uniforms.rotation.value = material.rotation;
  9186. if ( material.map ) {
  9187. uniforms.map.value = material.map;
  9188. refreshTransformUniform( material.map, uniforms.mapTransform );
  9189. }
  9190. if ( material.alphaMap ) {
  9191. uniforms.alphaMap.value = material.alphaMap;
  9192. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  9193. }
  9194. if ( material.alphaTest > 0 ) {
  9195. uniforms.alphaTest.value = material.alphaTest;
  9196. }
  9197. }
  9198. function refreshUniformsPhong( uniforms, material ) {
  9199. uniforms.specular.value.copy( material.specular );
  9200. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  9201. }
  9202. function refreshUniformsToon( uniforms, material ) {
  9203. if ( material.gradientMap ) {
  9204. uniforms.gradientMap.value = material.gradientMap;
  9205. }
  9206. }
  9207. function refreshUniformsStandard( uniforms, material ) {
  9208. uniforms.metalness.value = material.metalness;
  9209. if ( material.metalnessMap ) {
  9210. uniforms.metalnessMap.value = material.metalnessMap;
  9211. refreshTransformUniform( material.metalnessMap, uniforms.metalnessMapTransform );
  9212. }
  9213. uniforms.roughness.value = material.roughness;
  9214. if ( material.roughnessMap ) {
  9215. uniforms.roughnessMap.value = material.roughnessMap;
  9216. refreshTransformUniform( material.roughnessMap, uniforms.roughnessMapTransform );
  9217. }
  9218. if ( material.envMap ) {
  9219. //uniforms.envMap.value = material.envMap; // part of uniforms common
  9220. uniforms.envMapIntensity.value = material.envMapIntensity;
  9221. }
  9222. }
  9223. function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) {
  9224. uniforms.ior.value = material.ior; // also part of uniforms common
  9225. if ( material.sheen > 0 ) {
  9226. uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen );
  9227. uniforms.sheenRoughness.value = material.sheenRoughness;
  9228. if ( material.sheenColorMap ) {
  9229. uniforms.sheenColorMap.value = material.sheenColorMap;
  9230. refreshTransformUniform( material.sheenColorMap, uniforms.sheenColorMapTransform );
  9231. }
  9232. if ( material.sheenRoughnessMap ) {
  9233. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  9234. refreshTransformUniform( material.sheenRoughnessMap, uniforms.sheenRoughnessMapTransform );
  9235. }
  9236. }
  9237. if ( material.clearcoat > 0 ) {
  9238. uniforms.clearcoat.value = material.clearcoat;
  9239. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  9240. if ( material.clearcoatMap ) {
  9241. uniforms.clearcoatMap.value = material.clearcoatMap;
  9242. refreshTransformUniform( material.clearcoatMap, uniforms.clearcoatMapTransform );
  9243. }
  9244. if ( material.clearcoatRoughnessMap ) {
  9245. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  9246. refreshTransformUniform( material.clearcoatRoughnessMap, uniforms.clearcoatRoughnessMapTransform );
  9247. }
  9248. if ( material.clearcoatNormalMap ) {
  9249. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  9250. refreshTransformUniform( material.clearcoatNormalMap, uniforms.clearcoatNormalMapTransform );
  9251. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  9252. if ( material.side === BackSide ) {
  9253. uniforms.clearcoatNormalScale.value.negate();
  9254. }
  9255. }
  9256. }
  9257. if ( material.dispersion > 0 ) {
  9258. uniforms.dispersion.value = material.dispersion;
  9259. }
  9260. if ( material.iridescence > 0 ) {
  9261. uniforms.iridescence.value = material.iridescence;
  9262. uniforms.iridescenceIOR.value = material.iridescenceIOR;
  9263. uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ];
  9264. uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ];
  9265. if ( material.iridescenceMap ) {
  9266. uniforms.iridescenceMap.value = material.iridescenceMap;
  9267. refreshTransformUniform( material.iridescenceMap, uniforms.iridescenceMapTransform );
  9268. }
  9269. if ( material.iridescenceThicknessMap ) {
  9270. uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap;
  9271. refreshTransformUniform( material.iridescenceThicknessMap, uniforms.iridescenceThicknessMapTransform );
  9272. }
  9273. }
  9274. if ( material.transmission > 0 ) {
  9275. uniforms.transmission.value = material.transmission;
  9276. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  9277. uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height );
  9278. if ( material.transmissionMap ) {
  9279. uniforms.transmissionMap.value = material.transmissionMap;
  9280. refreshTransformUniform( material.transmissionMap, uniforms.transmissionMapTransform );
  9281. }
  9282. uniforms.thickness.value = material.thickness;
  9283. if ( material.thicknessMap ) {
  9284. uniforms.thicknessMap.value = material.thicknessMap;
  9285. refreshTransformUniform( material.thicknessMap, uniforms.thicknessMapTransform );
  9286. }
  9287. uniforms.attenuationDistance.value = material.attenuationDistance;
  9288. uniforms.attenuationColor.value.copy( material.attenuationColor );
  9289. }
  9290. if ( material.anisotropy > 0 ) {
  9291. uniforms.anisotropyVector.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  9292. if ( material.anisotropyMap ) {
  9293. uniforms.anisotropyMap.value = material.anisotropyMap;
  9294. refreshTransformUniform( material.anisotropyMap, uniforms.anisotropyMapTransform );
  9295. }
  9296. }
  9297. uniforms.specularIntensity.value = material.specularIntensity;
  9298. uniforms.specularColor.value.copy( material.specularColor );
  9299. if ( material.specularColorMap ) {
  9300. uniforms.specularColorMap.value = material.specularColorMap;
  9301. refreshTransformUniform( material.specularColorMap, uniforms.specularColorMapTransform );
  9302. }
  9303. if ( material.specularIntensityMap ) {
  9304. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  9305. refreshTransformUniform( material.specularIntensityMap, uniforms.specularIntensityMapTransform );
  9306. }
  9307. }
  9308. function refreshUniformsMatcap( uniforms, material ) {
  9309. if ( material.matcap ) {
  9310. uniforms.matcap.value = material.matcap;
  9311. }
  9312. }
  9313. function refreshUniformsDistance( uniforms, material ) {
  9314. const light = properties.get( material ).light;
  9315. uniforms.referencePosition.value.setFromMatrixPosition( light.matrixWorld );
  9316. uniforms.nearDistance.value = light.shadow.camera.near;
  9317. uniforms.farDistance.value = light.shadow.camera.far;
  9318. }
  9319. return {
  9320. refreshFogUniforms: refreshFogUniforms,
  9321. refreshMaterialUniforms: refreshMaterialUniforms
  9322. };
  9323. }
  9324. function WebGLUniformsGroups( gl, info, capabilities, state ) {
  9325. let buffers = {};
  9326. let updateList = {};
  9327. let allocatedBindingPoints = [];
  9328. const maxBindingPoints = gl.getParameter( gl.MAX_UNIFORM_BUFFER_BINDINGS ); // binding points are global whereas block indices are per shader program
  9329. function bind( uniformsGroup, program ) {
  9330. const webglProgram = program.program;
  9331. state.uniformBlockBinding( uniformsGroup, webglProgram );
  9332. }
  9333. function update( uniformsGroup, program ) {
  9334. let buffer = buffers[ uniformsGroup.id ];
  9335. if ( buffer === undefined ) {
  9336. prepareUniformsGroup( uniformsGroup );
  9337. buffer = createBuffer( uniformsGroup );
  9338. buffers[ uniformsGroup.id ] = buffer;
  9339. uniformsGroup.addEventListener( 'dispose', onUniformsGroupsDispose );
  9340. }
  9341. // ensure to update the binding points/block indices mapping for this program
  9342. const webglProgram = program.program;
  9343. state.updateUBOMapping( uniformsGroup, webglProgram );
  9344. // update UBO once per frame
  9345. const frame = info.render.frame;
  9346. if ( updateList[ uniformsGroup.id ] !== frame ) {
  9347. updateBufferData( uniformsGroup );
  9348. updateList[ uniformsGroup.id ] = frame;
  9349. }
  9350. }
  9351. function createBuffer( uniformsGroup ) {
  9352. // the setup of an UBO is independent of a particular shader program but global
  9353. const bindingPointIndex = allocateBindingPointIndex();
  9354. uniformsGroup.__bindingPointIndex = bindingPointIndex;
  9355. const buffer = gl.createBuffer();
  9356. const size = uniformsGroup.__size;
  9357. const usage = uniformsGroup.usage;
  9358. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  9359. gl.bufferData( gl.UNIFORM_BUFFER, size, usage );
  9360. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  9361. gl.bindBufferBase( gl.UNIFORM_BUFFER, bindingPointIndex, buffer );
  9362. return buffer;
  9363. }
  9364. function allocateBindingPointIndex() {
  9365. for ( let i = 0; i < maxBindingPoints; i ++ ) {
  9366. if ( allocatedBindingPoints.indexOf( i ) === -1 ) {
  9367. allocatedBindingPoints.push( i );
  9368. return i;
  9369. }
  9370. }
  9371. error( 'WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.' );
  9372. return 0;
  9373. }
  9374. function updateBufferData( uniformsGroup ) {
  9375. const buffer = buffers[ uniformsGroup.id ];
  9376. const uniforms = uniformsGroup.uniforms;
  9377. const cache = uniformsGroup.__cache;
  9378. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  9379. for ( let i = 0, il = uniforms.length; i < il; i ++ ) {
  9380. const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
  9381. for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
  9382. const uniform = uniformArray[ j ];
  9383. if ( hasUniformChanged( uniform, i, j, cache ) === true ) {
  9384. const offset = uniform.__offset;
  9385. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  9386. let arrayOffset = 0;
  9387. for ( let k = 0; k < values.length; k ++ ) {
  9388. const value = values[ k ];
  9389. const info = getUniformSize( value );
  9390. // TODO add integer and struct support
  9391. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  9392. uniform.__data[ 0 ] = value;
  9393. gl.bufferSubData( gl.UNIFORM_BUFFER, offset + arrayOffset, uniform.__data );
  9394. } else if ( value.isMatrix3 ) {
  9395. // manually converting 3x3 to 3x4
  9396. uniform.__data[ 0 ] = value.elements[ 0 ];
  9397. uniform.__data[ 1 ] = value.elements[ 1 ];
  9398. uniform.__data[ 2 ] = value.elements[ 2 ];
  9399. uniform.__data[ 3 ] = 0;
  9400. uniform.__data[ 4 ] = value.elements[ 3 ];
  9401. uniform.__data[ 5 ] = value.elements[ 4 ];
  9402. uniform.__data[ 6 ] = value.elements[ 5 ];
  9403. uniform.__data[ 7 ] = 0;
  9404. uniform.__data[ 8 ] = value.elements[ 6 ];
  9405. uniform.__data[ 9 ] = value.elements[ 7 ];
  9406. uniform.__data[ 10 ] = value.elements[ 8 ];
  9407. uniform.__data[ 11 ] = 0;
  9408. } else {
  9409. value.toArray( uniform.__data, arrayOffset );
  9410. arrayOffset += info.storage / Float32Array.BYTES_PER_ELEMENT;
  9411. }
  9412. }
  9413. gl.bufferSubData( gl.UNIFORM_BUFFER, offset, uniform.__data );
  9414. }
  9415. }
  9416. }
  9417. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  9418. }
  9419. function hasUniformChanged( uniform, index, indexArray, cache ) {
  9420. const value = uniform.value;
  9421. const indexString = index + '_' + indexArray;
  9422. if ( cache[ indexString ] === undefined ) {
  9423. // cache entry does not exist so far
  9424. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  9425. cache[ indexString ] = value;
  9426. } else {
  9427. cache[ indexString ] = value.clone();
  9428. }
  9429. return true;
  9430. } else {
  9431. const cachedObject = cache[ indexString ];
  9432. // compare current value with cached entry
  9433. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  9434. if ( cachedObject !== value ) {
  9435. cache[ indexString ] = value;
  9436. return true;
  9437. }
  9438. } else {
  9439. if ( cachedObject.equals( value ) === false ) {
  9440. cachedObject.copy( value );
  9441. return true;
  9442. }
  9443. }
  9444. }
  9445. return false;
  9446. }
  9447. function prepareUniformsGroup( uniformsGroup ) {
  9448. // determine total buffer size according to the STD140 layout
  9449. // Hint: STD140 is the only supported layout in WebGL 2
  9450. const uniforms = uniformsGroup.uniforms;
  9451. let offset = 0; // global buffer offset in bytes
  9452. const chunkSize = 16; // size of a chunk in bytes
  9453. for ( let i = 0, l = uniforms.length; i < l; i ++ ) {
  9454. const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
  9455. for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
  9456. const uniform = uniformArray[ j ];
  9457. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  9458. for ( let k = 0, kl = values.length; k < kl; k ++ ) {
  9459. const value = values[ k ];
  9460. const info = getUniformSize( value );
  9461. const chunkOffset = offset % chunkSize; // offset in the current chunk
  9462. const chunkPadding = chunkOffset % info.boundary; // required padding to match boundary
  9463. const chunkStart = chunkOffset + chunkPadding; // the start position in the current chunk for the data
  9464. offset += chunkPadding;
  9465. // Check for chunk overflow
  9466. if ( chunkStart !== 0 && ( chunkSize - chunkStart ) < info.storage ) {
  9467. // Add padding and adjust offset
  9468. offset += ( chunkSize - chunkStart );
  9469. }
  9470. // the following two properties will be used for partial buffer updates
  9471. uniform.__data = new Float32Array( info.storage / Float32Array.BYTES_PER_ELEMENT );
  9472. uniform.__offset = offset;
  9473. // Update the global offset
  9474. offset += info.storage;
  9475. }
  9476. }
  9477. }
  9478. // ensure correct final padding
  9479. const chunkOffset = offset % chunkSize;
  9480. if ( chunkOffset > 0 ) offset += ( chunkSize - chunkOffset );
  9481. //
  9482. uniformsGroup.__size = offset;
  9483. uniformsGroup.__cache = {};
  9484. return this;
  9485. }
  9486. function getUniformSize( value ) {
  9487. const info = {
  9488. boundary: 0, // bytes
  9489. storage: 0 // bytes
  9490. };
  9491. // determine sizes according to STD140
  9492. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  9493. // float/int/bool
  9494. info.boundary = 4;
  9495. info.storage = 4;
  9496. } else if ( value.isVector2 ) {
  9497. // vec2
  9498. info.boundary = 8;
  9499. info.storage = 8;
  9500. } else if ( value.isVector3 || value.isColor ) {
  9501. // vec3
  9502. info.boundary = 16;
  9503. info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes
  9504. } else if ( value.isVector4 ) {
  9505. // vec4
  9506. info.boundary = 16;
  9507. info.storage = 16;
  9508. } else if ( value.isMatrix3 ) {
  9509. // mat3 (in STD140 a 3x3 matrix is represented as 3x4)
  9510. info.boundary = 48;
  9511. info.storage = 48;
  9512. } else if ( value.isMatrix4 ) {
  9513. // mat4
  9514. info.boundary = 64;
  9515. info.storage = 64;
  9516. } else if ( value.isTexture ) {
  9517. warn( 'WebGLRenderer: Texture samplers can not be part of an uniforms group.' );
  9518. } else {
  9519. warn( 'WebGLRenderer: Unsupported uniform value type.', value );
  9520. }
  9521. return info;
  9522. }
  9523. function onUniformsGroupsDispose( event ) {
  9524. const uniformsGroup = event.target;
  9525. uniformsGroup.removeEventListener( 'dispose', onUniformsGroupsDispose );
  9526. const index = allocatedBindingPoints.indexOf( uniformsGroup.__bindingPointIndex );
  9527. allocatedBindingPoints.splice( index, 1 );
  9528. gl.deleteBuffer( buffers[ uniformsGroup.id ] );
  9529. delete buffers[ uniformsGroup.id ];
  9530. delete updateList[ uniformsGroup.id ];
  9531. }
  9532. function dispose() {
  9533. for ( const id in buffers ) {
  9534. gl.deleteBuffer( buffers[ id ] );
  9535. }
  9536. allocatedBindingPoints = [];
  9537. buffers = {};
  9538. updateList = {};
  9539. }
  9540. return {
  9541. bind: bind,
  9542. update: update,
  9543. dispose: dispose
  9544. };
  9545. }
  9546. /**
  9547. * Precomputed DFG LUT for Image-Based Lighting
  9548. * Resolution: 16x16
  9549. * Samples: 4096 per texel
  9550. * Format: RG16F (2 half floats per texel: scale, bias)
  9551. */
  9552. const DATA = new Uint16Array( [
  9553. 0x30b5, 0x3ad1, 0x314c, 0x3a4d, 0x33d2, 0x391c, 0x35ef, 0x3828, 0x37f3, 0x36a6, 0x38d1, 0x3539, 0x3979, 0x3410, 0x39f8, 0x3252, 0x3a53, 0x30f0, 0x3a94, 0x2fc9, 0x3abf, 0x2e35, 0x3ada, 0x2d05, 0x3ae8, 0x2c1f, 0x3aed, 0x2ae0, 0x3aea, 0x29d1, 0x3ae1, 0x28ff,
  9554. 0x3638, 0x38e4, 0x364a, 0x38ce, 0x3699, 0x385e, 0x374e, 0x372c, 0x3839, 0x35a4, 0x38dc, 0x3462, 0x396e, 0x32c4, 0x39de, 0x3134, 0x3a2b, 0x3003, 0x3a59, 0x2e3a, 0x3a6d, 0x2ce1, 0x3a6e, 0x2bba, 0x3a5f, 0x2a33, 0x3a49, 0x290a, 0x3a2d, 0x2826, 0x3a0a, 0x26e8,
  9555. 0x3894, 0x36d7, 0x3897, 0x36c9, 0x38a3, 0x3675, 0x38bc, 0x35ac, 0x38ee, 0x349c, 0x393e, 0x3332, 0x3997, 0x3186, 0x39e2, 0x3038, 0x3a13, 0x2e75, 0x3a29, 0x2cf5, 0x3a2d, 0x2bac, 0x3a21, 0x29ff, 0x3a04, 0x28bc, 0x39dc, 0x2790, 0x39ad, 0x261a, 0x3978, 0x24fa,
  9556. 0x39ac, 0x34a8, 0x39ac, 0x34a3, 0x39ae, 0x3480, 0x39ae, 0x3423, 0x39b1, 0x330e, 0x39c2, 0x31a9, 0x39e0, 0x3063, 0x39fc, 0x2eb5, 0x3a0c, 0x2d1d, 0x3a14, 0x2bcf, 0x3a07, 0x29ff, 0x39e9, 0x28a3, 0x39be, 0x273c, 0x3989, 0x25b3, 0x394a, 0x2488, 0x3907, 0x2345,
  9557. 0x3a77, 0x3223, 0x3a76, 0x321f, 0x3a73, 0x3204, 0x3a6a, 0x31b3, 0x3a58, 0x3114, 0x3a45, 0x303b, 0x3a34, 0x2eb6, 0x3a26, 0x2d31, 0x3a1e, 0x2bef, 0x3a0b, 0x2a0d, 0x39ec, 0x28a1, 0x39c0, 0x271b, 0x3987, 0x2580, 0x3944, 0x2449, 0x38fa, 0x22bd, 0x38ac, 0x2155,
  9558. 0x3b07, 0x2fca, 0x3b06, 0x2fca, 0x3b00, 0x2fb8, 0x3af4, 0x2f7c, 0x3adb, 0x2eea, 0x3ab4, 0x2e00, 0x3a85, 0x2cec, 0x3a5e, 0x2bc5, 0x3a36, 0x2a00, 0x3a0d, 0x2899, 0x39dc, 0x2707, 0x39a0, 0x2562, 0x395a, 0x2424, 0x390b, 0x2268, 0x38b7, 0x20fd, 0x385f, 0x1fd1,
  9559. 0x3b69, 0x2cb9, 0x3b68, 0x2cbb, 0x3b62, 0x2cbb, 0x3b56, 0x2cae, 0x3b3b, 0x2c78, 0x3b0d, 0x2c0a, 0x3acf, 0x2ae3, 0x3a92, 0x2998, 0x3a54, 0x2867, 0x3a17, 0x26d0, 0x39d3, 0x253c, 0x3989, 0x2402, 0x3935, 0x2226, 0x38dc, 0x20bd, 0x387d, 0x1f54, 0x381d, 0x1db3,
  9560. 0x3ba9, 0x296b, 0x3ba8, 0x296f, 0x3ba3, 0x297b, 0x3b98, 0x2987, 0x3b7f, 0x2976, 0x3b4e, 0x2927, 0x3b0e, 0x2895, 0x3ac2, 0x27b7, 0x3a73, 0x263b, 0x3a23, 0x24e7, 0x39d0, 0x239b, 0x3976, 0x21d9, 0x3917, 0x207e, 0x38b2, 0x1ee7, 0x384b, 0x1d53, 0x37c7, 0x1c1e,
  9561. 0x3bd2, 0x25cb, 0x3bd1, 0x25d3, 0x3bcd, 0x25f0, 0x3bc2, 0x261f, 0x3bad, 0x2645, 0x3b7d, 0x262d, 0x3b3e, 0x25c4, 0x3aec, 0x250f, 0x3a93, 0x243a, 0x3a32, 0x22ce, 0x39d0, 0x215b, 0x3969, 0x202a, 0x38fe, 0x1e6e, 0x388f, 0x1cf1, 0x381f, 0x1b9b, 0x3762, 0x19dd,
  9562. 0x3be9, 0x21ab, 0x3be9, 0x21b7, 0x3be5, 0x21e5, 0x3bdd, 0x2241, 0x3bc9, 0x22a7, 0x3ba0, 0x22ec, 0x3b62, 0x22cd, 0x3b0f, 0x2247, 0x3aae, 0x2175, 0x3a44, 0x2088, 0x39d4, 0x1f49, 0x3960, 0x1dbe, 0x38e9, 0x1c77, 0x3870, 0x1ae8, 0x37f1, 0x1953, 0x3708, 0x181b,
  9563. 0x3bf6, 0x1cea, 0x3bf6, 0x1cfb, 0x3bf3, 0x1d38, 0x3bec, 0x1dbd, 0x3bda, 0x1e7c, 0x3bb7, 0x1f25, 0x3b7d, 0x1f79, 0x3b2c, 0x1f4c, 0x3ac6, 0x1ea6, 0x3a55, 0x1dbb, 0x39da, 0x1cbd, 0x395a, 0x1b9d, 0x38d8, 0x1a00, 0x3855, 0x18ac, 0x37ab, 0x173c, 0x36b7, 0x1598,
  9564. 0x3bfc, 0x1736, 0x3bfc, 0x1759, 0x3bf9, 0x17e7, 0x3bf4, 0x1896, 0x3be4, 0x1997, 0x3bc6, 0x1aa8, 0x3b91, 0x1b84, 0x3b43, 0x1bd2, 0x3ade, 0x1b8a, 0x3a65, 0x1acd, 0x39e2, 0x19d3, 0x3957, 0x18cd, 0x38ca, 0x17b3, 0x383e, 0x1613, 0x376d, 0x14bf, 0x366f, 0x135e,
  9565. 0x3bff, 0x101b, 0x3bff, 0x1039, 0x3bfc, 0x10c8, 0x3bf9, 0x1226, 0x3bea, 0x1428, 0x3bcf, 0x1584, 0x3b9f, 0x16c5, 0x3b54, 0x179a, 0x3af0, 0x17ce, 0x3a76, 0x1771, 0x39ea, 0x16a4, 0x3956, 0x15a7, 0x38bf, 0x14a7, 0x3829, 0x1379, 0x3735, 0x11ea, 0x362d, 0x10a1,
  9566. 0x3c00, 0x061b, 0x3c00, 0x066a, 0x3bfe, 0x081c, 0x3bfa, 0x0a4c, 0x3bed, 0x0d16, 0x3bd5, 0x0fb3, 0x3ba9, 0x114d, 0x3b63, 0x127c, 0x3b01, 0x132f, 0x3a85, 0x1344, 0x39f4, 0x12d2, 0x3957, 0x120d, 0x38b5, 0x1122, 0x3817, 0x103c, 0x3703, 0x0ed3, 0x35f0, 0x0d6d,
  9567. 0x3c00, 0x007a, 0x3c00, 0x0089, 0x3bfe, 0x011d, 0x3bfb, 0x027c, 0x3bf0, 0x04fa, 0x3bda, 0x0881, 0x3bb1, 0x0acd, 0x3b6f, 0x0c97, 0x3b10, 0x0d7b, 0x3a93, 0x0df1, 0x39fe, 0x0def, 0x3959, 0x0d8a, 0x38af, 0x0ce9, 0x3808, 0x0c31, 0x36d5, 0x0af0, 0x35b9, 0x09a3,
  9568. 0x3c00, 0x0000, 0x3c00, 0x0001, 0x3bff, 0x0015, 0x3bfb, 0x0059, 0x3bf2, 0x00fd, 0x3bdd, 0x01df, 0x3bb7, 0x031c, 0x3b79, 0x047c, 0x3b1d, 0x05d4, 0x3aa0, 0x06d5, 0x3a08, 0x075a, 0x395d, 0x075e, 0x38aa, 0x06f7, 0x37f4, 0x0648, 0x36ac, 0x0576, 0x3586, 0x049f
  9569. ] );
  9570. let lut = null;
  9571. function getDFGLUT() {
  9572. if ( lut === null ) {
  9573. lut = new DataTexture( DATA, 16, 16, RGFormat, HalfFloatType );
  9574. lut.name = 'DFG_LUT';
  9575. lut.minFilter = LinearFilter;
  9576. lut.magFilter = LinearFilter;
  9577. lut.wrapS = ClampToEdgeWrapping;
  9578. lut.wrapT = ClampToEdgeWrapping;
  9579. lut.generateMipmaps = false;
  9580. lut.needsUpdate = true;
  9581. }
  9582. return lut;
  9583. }
  9584. /**
  9585. * This renderer uses WebGL 2 to display scenes.
  9586. *
  9587. * WebGL 1 is not supported since `r163`.
  9588. */
  9589. class WebGLRenderer {
  9590. /**
  9591. * Constructs a new WebGL renderer.
  9592. *
  9593. * @param {WebGLRenderer~Options} [parameters] - The configuration parameter.
  9594. */
  9595. constructor( parameters = {} ) {
  9596. const {
  9597. canvas = createCanvasElement(),
  9598. context = null,
  9599. depth = true,
  9600. stencil = false,
  9601. alpha = false,
  9602. antialias = false,
  9603. premultipliedAlpha = true,
  9604. preserveDrawingBuffer = false,
  9605. powerPreference = 'default',
  9606. failIfMajorPerformanceCaveat = false,
  9607. reversedDepthBuffer = false,
  9608. outputBufferType = UnsignedByteType,
  9609. } = parameters;
  9610. /**
  9611. * This flag can be used for type testing.
  9612. *
  9613. * @type {boolean}
  9614. * @readonly
  9615. * @default true
  9616. */
  9617. this.isWebGLRenderer = true;
  9618. let _alpha;
  9619. if ( context !== null ) {
  9620. if ( typeof WebGLRenderingContext !== 'undefined' && context instanceof WebGLRenderingContext ) {
  9621. throw new Error( 'THREE.WebGLRenderer: WebGL 1 is not supported since r163.' );
  9622. }
  9623. _alpha = context.getContextAttributes().alpha;
  9624. } else {
  9625. _alpha = alpha;
  9626. }
  9627. const _outputBufferType = outputBufferType;
  9628. const INTEGER_FORMATS = new Set( [
  9629. RGBAIntegerFormat,
  9630. RGIntegerFormat,
  9631. RedIntegerFormat
  9632. ] );
  9633. const UNSIGNED_TYPES = new Set( [
  9634. UnsignedByteType,
  9635. UnsignedIntType,
  9636. UnsignedShortType,
  9637. UnsignedInt248Type,
  9638. UnsignedShort4444Type,
  9639. UnsignedShort5551Type
  9640. ] );
  9641. const uintClearColor = new Uint32Array( 4 );
  9642. const intClearColor = new Int32Array( 4 );
  9643. let currentRenderList = null;
  9644. let currentRenderState = null;
  9645. // render() can be called from within a callback triggered by another render.
  9646. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  9647. const renderListStack = [];
  9648. const renderStateStack = [];
  9649. // internal render target for non-UnsignedByteType color buffer
  9650. let output = null;
  9651. // public properties
  9652. /**
  9653. * A canvas where the renderer draws its output.This is automatically created by the renderer
  9654. * in the constructor (if not provided already); you just need to add it to your page like so:
  9655. * ```js
  9656. * document.body.appendChild( renderer.domElement );
  9657. * ```
  9658. *
  9659. * @type {HTMLCanvasElement|OffscreenCanvas}
  9660. */
  9661. this.domElement = canvas;
  9662. /**
  9663. * A object with debug configuration settings.
  9664. *
  9665. * - `checkShaderErrors`: If it is `true`, defines whether material shader programs are
  9666. * checked for errors during compilation and linkage process. It may be useful to disable
  9667. * this check in production for performance gain. It is strongly recommended to keep these
  9668. * checks enabled during development. If the shader does not compile and link - it will not
  9669. * work and associated material will not render.
  9670. * - `onShaderError(gl, program, glVertexShader,glFragmentShader)`: A callback function that
  9671. * can be used for custom error reporting. The callback receives the WebGL context, an instance
  9672. * of WebGLProgram as well two instances of WebGLShader representing the vertex and fragment shader.
  9673. * Assigning a custom function disables the default error reporting.
  9674. *
  9675. * @type {Object}
  9676. */
  9677. this.debug = {
  9678. /**
  9679. * Enables error checking and reporting when shader programs are being compiled.
  9680. * @type {boolean}
  9681. */
  9682. checkShaderErrors: true,
  9683. /**
  9684. * Callback for custom error reporting.
  9685. * @type {?Function}
  9686. */
  9687. onShaderError: null
  9688. };
  9689. // clearing
  9690. /**
  9691. * Whether the renderer should automatically clear its output before rendering a frame or not.
  9692. *
  9693. * @type {boolean}
  9694. * @default true
  9695. */
  9696. this.autoClear = true;
  9697. /**
  9698. * If {@link WebGLRenderer#autoClear} set to `true`, whether the renderer should clear
  9699. * the color buffer or not.
  9700. *
  9701. * @type {boolean}
  9702. * @default true
  9703. */
  9704. this.autoClearColor = true;
  9705. /**
  9706. * If {@link WebGLRenderer#autoClear} set to `true`, whether the renderer should clear
  9707. * the depth buffer or not.
  9708. *
  9709. * @type {boolean}
  9710. * @default true
  9711. */
  9712. this.autoClearDepth = true;
  9713. /**
  9714. * If {@link WebGLRenderer#autoClear} set to `true`, whether the renderer should clear
  9715. * the stencil buffer or not.
  9716. *
  9717. * @type {boolean}
  9718. * @default true
  9719. */
  9720. this.autoClearStencil = true;
  9721. // scene graph
  9722. /**
  9723. * Whether the renderer should sort objects or not.
  9724. *
  9725. * Note: Sorting is used to attempt to properly render objects that have some
  9726. * degree of transparency. By definition, sorting objects may not work in all
  9727. * cases. Depending on the needs of application, it may be necessary to turn
  9728. * off sorting and use other methods to deal with transparency rendering e.g.
  9729. * manually determining each object's rendering order.
  9730. *
  9731. * @type {boolean}
  9732. * @default true
  9733. */
  9734. this.sortObjects = true;
  9735. // user-defined clipping
  9736. /**
  9737. * User-defined clipping planes specified in world space. These planes apply globally.
  9738. * Points in space whose dot product with the plane is negative are cut away.
  9739. *
  9740. * @type {Array<Plane>}
  9741. */
  9742. this.clippingPlanes = [];
  9743. /**
  9744. * Whether the renderer respects object-level clipping planes or not.
  9745. *
  9746. * @type {boolean}
  9747. * @default false
  9748. */
  9749. this.localClippingEnabled = false;
  9750. // tone mapping
  9751. /**
  9752. * The tone mapping technique of the renderer.
  9753. *
  9754. * @type {(NoToneMapping|LinearToneMapping|ReinhardToneMapping|CineonToneMapping|ACESFilmicToneMapping|CustomToneMapping|AgXToneMapping|NeutralToneMapping)}
  9755. * @default NoToneMapping
  9756. */
  9757. this.toneMapping = NoToneMapping;
  9758. /**
  9759. * Exposure level of tone mapping.
  9760. *
  9761. * @type {number}
  9762. * @default 1
  9763. */
  9764. this.toneMappingExposure = 1.0;
  9765. // transmission
  9766. /**
  9767. * The normalized resolution scale for the transmission render target, measured in percentage
  9768. * of viewport dimensions. Lowering this value can result in significant performance improvements
  9769. * when using {@link MeshPhysicalMaterial#transmission}.
  9770. *
  9771. * @type {number}
  9772. * @default 1
  9773. */
  9774. this.transmissionResolutionScale = 1.0;
  9775. // internal properties
  9776. const _this = this;
  9777. let _isContextLost = false;
  9778. // internal state cache
  9779. this._outputColorSpace = SRGBColorSpace;
  9780. let _currentActiveCubeFace = 0;
  9781. let _currentActiveMipmapLevel = 0;
  9782. let _currentRenderTarget = null;
  9783. let _currentMaterialId = -1;
  9784. let _currentCamera = null;
  9785. const _currentViewport = new Vector4();
  9786. const _currentScissor = new Vector4();
  9787. let _currentScissorTest = null;
  9788. const _currentClearColor = new Color( 0x000000 );
  9789. let _currentClearAlpha = 0;
  9790. //
  9791. let _width = canvas.width;
  9792. let _height = canvas.height;
  9793. let _pixelRatio = 1;
  9794. let _opaqueSort = null;
  9795. let _transparentSort = null;
  9796. const _viewport = new Vector4( 0, 0, _width, _height );
  9797. const _scissor = new Vector4( 0, 0, _width, _height );
  9798. let _scissorTest = false;
  9799. // frustum
  9800. const _frustum = new Frustum();
  9801. // clipping
  9802. let _clippingEnabled = false;
  9803. let _localClippingEnabled = false;
  9804. // camera matrices cache
  9805. const _projScreenMatrix = new Matrix4();
  9806. const _vector3 = new Vector3();
  9807. const _vector4 = new Vector4();
  9808. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  9809. let _renderBackground = false;
  9810. function getTargetPixelRatio() {
  9811. return _currentRenderTarget === null ? _pixelRatio : 1;
  9812. }
  9813. // initialize
  9814. let _gl = context;
  9815. function getContext( contextName, contextAttributes ) {
  9816. return canvas.getContext( contextName, contextAttributes );
  9817. }
  9818. try {
  9819. const contextAttributes = {
  9820. alpha: true,
  9821. depth,
  9822. stencil,
  9823. antialias,
  9824. premultipliedAlpha,
  9825. preserveDrawingBuffer,
  9826. powerPreference,
  9827. failIfMajorPerformanceCaveat,
  9828. };
  9829. // OffscreenCanvas does not have setAttribute, see #22811
  9830. if ( 'setAttribute' in canvas ) canvas.setAttribute( 'data-engine', `three.js r${REVISION}` );
  9831. // event listeners must be registered before WebGL context is created, see #12753
  9832. canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  9833. canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  9834. canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  9835. if ( _gl === null ) {
  9836. const contextName = 'webgl2';
  9837. _gl = getContext( contextName, contextAttributes );
  9838. if ( _gl === null ) {
  9839. if ( getContext( contextName ) ) {
  9840. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  9841. } else {
  9842. throw new Error( 'Error creating WebGL context.' );
  9843. }
  9844. }
  9845. }
  9846. } catch ( e ) {
  9847. error( 'WebGLRenderer: ' + e.message );
  9848. throw e;
  9849. }
  9850. let extensions, capabilities, state, info;
  9851. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  9852. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  9853. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  9854. let utils, bindingStates, uniformsGroups;
  9855. function initGLContext() {
  9856. extensions = new WebGLExtensions( _gl );
  9857. extensions.init();
  9858. utils = new WebGLUtils( _gl, extensions );
  9859. capabilities = new WebGLCapabilities( _gl, extensions, parameters, utils );
  9860. state = new WebGLState( _gl, extensions );
  9861. if ( capabilities.reversedDepthBuffer && reversedDepthBuffer ) {
  9862. state.buffers.depth.setReversed( true );
  9863. }
  9864. info = new WebGLInfo( _gl );
  9865. properties = new WebGLProperties();
  9866. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  9867. cubemaps = new WebGLCubeMaps( _this );
  9868. cubeuvmaps = new WebGLCubeUVMaps( _this );
  9869. attributes = new WebGLAttributes( _gl );
  9870. bindingStates = new WebGLBindingStates( _gl, attributes );
  9871. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  9872. objects = new WebGLObjects( _gl, geometries, attributes, bindingStates, info );
  9873. morphtargets = new WebGLMorphtargets( _gl, capabilities, textures );
  9874. clipping = new WebGLClipping( properties );
  9875. programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping );
  9876. materials = new WebGLMaterials( _this, properties );
  9877. renderLists = new WebGLRenderLists();
  9878. renderStates = new WebGLRenderStates( extensions );
  9879. background = new WebGLBackground( _this, cubemaps, cubeuvmaps, state, objects, _alpha, premultipliedAlpha );
  9880. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  9881. uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state );
  9882. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info );
  9883. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info );
  9884. info.programs = programCache.programs;
  9885. /**
  9886. * Holds details about the capabilities of the current rendering context.
  9887. *
  9888. * @name WebGLRenderer#capabilities
  9889. * @type {WebGLRenderer~Capabilities}
  9890. */
  9891. _this.capabilities = capabilities;
  9892. /**
  9893. * Provides methods for retrieving and testing WebGL extensions.
  9894. *
  9895. * - `get(extensionName:string)`: Used to check whether a WebGL extension is supported
  9896. * and return the extension object if available.
  9897. * - `has(extensionName:string)`: returns `true` if the extension is supported.
  9898. *
  9899. * @name WebGLRenderer#extensions
  9900. * @type {Object}
  9901. */
  9902. _this.extensions = extensions;
  9903. /**
  9904. * Used to track properties of other objects like native WebGL objects.
  9905. *
  9906. * @name WebGLRenderer#properties
  9907. * @type {Object}
  9908. */
  9909. _this.properties = properties;
  9910. /**
  9911. * Manages the render lists of the renderer.
  9912. *
  9913. * @name WebGLRenderer#renderLists
  9914. * @type {Object}
  9915. */
  9916. _this.renderLists = renderLists;
  9917. /**
  9918. * Interface for managing shadows.
  9919. *
  9920. * @name WebGLRenderer#shadowMap
  9921. * @type {WebGLRenderer~ShadowMap}
  9922. */
  9923. _this.shadowMap = shadowMap;
  9924. /**
  9925. * Interface for managing the WebGL state.
  9926. *
  9927. * @name WebGLRenderer#state
  9928. * @type {Object}
  9929. */
  9930. _this.state = state;
  9931. /**
  9932. * Holds a series of statistical information about the GPU memory
  9933. * and the rendering process. Useful for debugging and monitoring.
  9934. *
  9935. * By default these data are reset at each render call but when having
  9936. * multiple render passes per frame (e.g. when using post processing) it can
  9937. * be preferred to reset with a custom pattern. First, set `autoReset` to
  9938. * `false`.
  9939. * ```js
  9940. * renderer.info.autoReset = false;
  9941. * ```
  9942. * Call `reset()` whenever you have finished to render a single frame.
  9943. * ```js
  9944. * renderer.info.reset();
  9945. * ```
  9946. *
  9947. * @name WebGLRenderer#info
  9948. * @type {WebGLRenderer~Info}
  9949. */
  9950. _this.info = info;
  9951. }
  9952. initGLContext();
  9953. // initialize internal render target for non-UnsignedByteType color buffer
  9954. if ( _outputBufferType !== UnsignedByteType ) {
  9955. output = new WebGLOutput( _outputBufferType, canvas.width, canvas.height, depth, stencil );
  9956. }
  9957. // xr
  9958. const xr = new WebXRManager( _this, _gl );
  9959. /**
  9960. * A reference to the XR manager.
  9961. *
  9962. * @type {WebXRManager}
  9963. */
  9964. this.xr = xr;
  9965. /**
  9966. * Returns the rendering context.
  9967. *
  9968. * @return {WebGL2RenderingContext} The rendering context.
  9969. */
  9970. this.getContext = function () {
  9971. return _gl;
  9972. };
  9973. /**
  9974. * Returns the rendering context attributes.
  9975. *
  9976. * @return {WebGLContextAttributes} The rendering context attributes.
  9977. */
  9978. this.getContextAttributes = function () {
  9979. return _gl.getContextAttributes();
  9980. };
  9981. /**
  9982. * Simulates a loss of the WebGL context. This requires support for the `WEBGL_lose_context` extension.
  9983. */
  9984. this.forceContextLoss = function () {
  9985. const extension = extensions.get( 'WEBGL_lose_context' );
  9986. if ( extension ) extension.loseContext();
  9987. };
  9988. /**
  9989. * Simulates a restore of the WebGL context. This requires support for the `WEBGL_lose_context` extension.
  9990. */
  9991. this.forceContextRestore = function () {
  9992. const extension = extensions.get( 'WEBGL_lose_context' );
  9993. if ( extension ) extension.restoreContext();
  9994. };
  9995. /**
  9996. * Returns the pixel ratio.
  9997. *
  9998. * @return {number} The pixel ratio.
  9999. */
  10000. this.getPixelRatio = function () {
  10001. return _pixelRatio;
  10002. };
  10003. /**
  10004. * Sets the given pixel ratio and resizes the canvas if necessary.
  10005. *
  10006. * @param {number} value - The pixel ratio.
  10007. */
  10008. this.setPixelRatio = function ( value ) {
  10009. if ( value === undefined ) return;
  10010. _pixelRatio = value;
  10011. this.setSize( _width, _height, false );
  10012. };
  10013. /**
  10014. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  10015. *
  10016. * @param {Vector2} target - The method writes the result in this target object.
  10017. * @return {Vector2} The renderer's size in logical pixels.
  10018. */
  10019. this.getSize = function ( target ) {
  10020. return target.set( _width, _height );
  10021. };
  10022. /**
  10023. * Resizes the output canvas to (width, height) with device pixel ratio taken
  10024. * into account, and also sets the viewport to fit that size, starting in (0,
  10025. * 0). Setting `updateStyle` to false prevents any style changes to the output canvas.
  10026. *
  10027. * @param {number} width - The width in logical pixels.
  10028. * @param {number} height - The height in logical pixels.
  10029. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  10030. */
  10031. this.setSize = function ( width, height, updateStyle = true ) {
  10032. if ( xr.isPresenting ) {
  10033. warn( 'WebGLRenderer: Can\'t change size while VR device is presenting.' );
  10034. return;
  10035. }
  10036. _width = width;
  10037. _height = height;
  10038. canvas.width = Math.floor( width * _pixelRatio );
  10039. canvas.height = Math.floor( height * _pixelRatio );
  10040. if ( updateStyle === true ) {
  10041. canvas.style.width = width + 'px';
  10042. canvas.style.height = height + 'px';
  10043. }
  10044. if ( output !== null ) {
  10045. output.setSize( canvas.width, canvas.height );
  10046. }
  10047. this.setViewport( 0, 0, width, height );
  10048. };
  10049. /**
  10050. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  10051. *
  10052. * @param {Vector2} target - The method writes the result in this target object.
  10053. * @return {Vector2} The drawing buffer size.
  10054. */
  10055. this.getDrawingBufferSize = function ( target ) {
  10056. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  10057. };
  10058. /**
  10059. * This method allows to define the drawing buffer size by specifying
  10060. * width, height and pixel ratio all at once. The size of the drawing
  10061. * buffer is computed with this formula:
  10062. * ```js
  10063. * size.x = width * pixelRatio;
  10064. * size.y = height * pixelRatio;
  10065. * ```
  10066. *
  10067. * @param {number} width - The width in logical pixels.
  10068. * @param {number} height - The height in logical pixels.
  10069. * @param {number} pixelRatio - The pixel ratio.
  10070. */
  10071. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  10072. _width = width;
  10073. _height = height;
  10074. _pixelRatio = pixelRatio;
  10075. canvas.width = Math.floor( width * pixelRatio );
  10076. canvas.height = Math.floor( height * pixelRatio );
  10077. this.setViewport( 0, 0, width, height );
  10078. };
  10079. /**
  10080. * Sets the post-processing effects to be applied after rendering.
  10081. *
  10082. * @param {Array} effects - An array of post-processing effects.
  10083. */
  10084. this.setEffects = function ( effects ) {
  10085. if ( _outputBufferType === UnsignedByteType ) {
  10086. console.error( 'THREE.WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.' );
  10087. return;
  10088. }
  10089. if ( effects ) {
  10090. for ( let i = 0; i < effects.length; i ++ ) {
  10091. if ( effects[ i ].isOutputPass === true ) {
  10092. console.warn( 'THREE.WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.' );
  10093. break;
  10094. }
  10095. }
  10096. }
  10097. output.setEffects( effects || [] );
  10098. };
  10099. /**
  10100. * Returns the current viewport definition.
  10101. *
  10102. * @param {Vector2} target - The method writes the result in this target object.
  10103. * @return {Vector2} The current viewport definition.
  10104. */
  10105. this.getCurrentViewport = function ( target ) {
  10106. return target.copy( _currentViewport );
  10107. };
  10108. /**
  10109. * Returns the viewport definition.
  10110. *
  10111. * @param {Vector4} target - The method writes the result in this target object.
  10112. * @return {Vector4} The viewport definition.
  10113. */
  10114. this.getViewport = function ( target ) {
  10115. return target.copy( _viewport );
  10116. };
  10117. /**
  10118. * Sets the viewport to render from `(x, y)` to `(x + width, y + height)`.
  10119. *
  10120. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  10121. * Or alternatively a four-component vector specifying all the parameters of the viewport.
  10122. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  10123. * @param {number} width - The width of the viewport in logical pixel unit.
  10124. * @param {number} height - The height of the viewport in logical pixel unit.
  10125. */
  10126. this.setViewport = function ( x, y, width, height ) {
  10127. if ( x.isVector4 ) {
  10128. _viewport.set( x.x, x.y, x.z, x.w );
  10129. } else {
  10130. _viewport.set( x, y, width, height );
  10131. }
  10132. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).round() );
  10133. };
  10134. /**
  10135. * Returns the scissor region.
  10136. *
  10137. * @param {Vector4} target - The method writes the result in this target object.
  10138. * @return {Vector4} The scissor region.
  10139. */
  10140. this.getScissor = function ( target ) {
  10141. return target.copy( _scissor );
  10142. };
  10143. /**
  10144. * Sets the scissor region to render from `(x, y)` to `(x + width, y + height)`.
  10145. *
  10146. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the scissor region origin in logical pixel unit.
  10147. * Or alternatively a four-component vector specifying all the parameters of the scissor region.
  10148. * @param {number} y - The vertical coordinate for the lower left corner of the scissor region origin in logical pixel unit.
  10149. * @param {number} width - The width of the scissor region in logical pixel unit.
  10150. * @param {number} height - The height of the scissor region in logical pixel unit.
  10151. */
  10152. this.setScissor = function ( x, y, width, height ) {
  10153. if ( x.isVector4 ) {
  10154. _scissor.set( x.x, x.y, x.z, x.w );
  10155. } else {
  10156. _scissor.set( x, y, width, height );
  10157. }
  10158. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).round() );
  10159. };
  10160. /**
  10161. * Returns `true` if the scissor test is enabled.
  10162. *
  10163. * @return {boolean} Whether the scissor test is enabled or not.
  10164. */
  10165. this.getScissorTest = function () {
  10166. return _scissorTest;
  10167. };
  10168. /**
  10169. * Enable or disable the scissor test. When this is enabled, only the pixels
  10170. * within the defined scissor area will be affected by further renderer
  10171. * actions.
  10172. *
  10173. * @param {boolean} boolean - Whether the scissor test is enabled or not.
  10174. */
  10175. this.setScissorTest = function ( boolean ) {
  10176. state.setScissorTest( _scissorTest = boolean );
  10177. };
  10178. /**
  10179. * Sets a custom opaque sort function for the render lists. Pass `null`
  10180. * to use the default `painterSortStable` function.
  10181. *
  10182. * @param {?Function} method - The opaque sort function.
  10183. */
  10184. this.setOpaqueSort = function ( method ) {
  10185. _opaqueSort = method;
  10186. };
  10187. /**
  10188. * Sets a custom transparent sort function for the render lists. Pass `null`
  10189. * to use the default `reversePainterSortStable` function.
  10190. *
  10191. * @param {?Function} method - The opaque sort function.
  10192. */
  10193. this.setTransparentSort = function ( method ) {
  10194. _transparentSort = method;
  10195. };
  10196. // Clearing
  10197. /**
  10198. * Returns the clear color.
  10199. *
  10200. * @param {Color} target - The method writes the result in this target object.
  10201. * @return {Color} The clear color.
  10202. */
  10203. this.getClearColor = function ( target ) {
  10204. return target.copy( background.getClearColor() );
  10205. };
  10206. /**
  10207. * Sets the clear color and alpha.
  10208. *
  10209. * @param {Color} color - The clear color.
  10210. * @param {number} [alpha=1] - The clear alpha.
  10211. */
  10212. this.setClearColor = function () {
  10213. background.setClearColor( ...arguments );
  10214. };
  10215. /**
  10216. * Returns the clear alpha. Ranges within `[0,1]`.
  10217. *
  10218. * @return {number} The clear alpha.
  10219. */
  10220. this.getClearAlpha = function () {
  10221. return background.getClearAlpha();
  10222. };
  10223. /**
  10224. * Sets the clear alpha.
  10225. *
  10226. * @param {number} alpha - The clear alpha.
  10227. */
  10228. this.setClearAlpha = function () {
  10229. background.setClearAlpha( ...arguments );
  10230. };
  10231. /**
  10232. * Tells the renderer to clear its color, depth or stencil drawing buffer(s).
  10233. * This method initializes the buffers to the current clear color values.
  10234. *
  10235. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  10236. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  10237. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  10238. */
  10239. this.clear = function ( color = true, depth = true, stencil = true ) {
  10240. let bits = 0;
  10241. if ( color ) {
  10242. // check if we're trying to clear an integer target
  10243. let isIntegerFormat = false;
  10244. if ( _currentRenderTarget !== null ) {
  10245. const targetFormat = _currentRenderTarget.texture.format;
  10246. isIntegerFormat = INTEGER_FORMATS.has( targetFormat );
  10247. }
  10248. // use the appropriate clear functions to clear the target if it's a signed
  10249. // or unsigned integer target
  10250. if ( isIntegerFormat ) {
  10251. const targetType = _currentRenderTarget.texture.type;
  10252. const isUnsignedType = UNSIGNED_TYPES.has( targetType );
  10253. const clearColor = background.getClearColor();
  10254. const a = background.getClearAlpha();
  10255. const r = clearColor.r;
  10256. const g = clearColor.g;
  10257. const b = clearColor.b;
  10258. if ( isUnsignedType ) {
  10259. uintClearColor[ 0 ] = r;
  10260. uintClearColor[ 1 ] = g;
  10261. uintClearColor[ 2 ] = b;
  10262. uintClearColor[ 3 ] = a;
  10263. _gl.clearBufferuiv( _gl.COLOR, 0, uintClearColor );
  10264. } else {
  10265. intClearColor[ 0 ] = r;
  10266. intClearColor[ 1 ] = g;
  10267. intClearColor[ 2 ] = b;
  10268. intClearColor[ 3 ] = a;
  10269. _gl.clearBufferiv( _gl.COLOR, 0, intClearColor );
  10270. }
  10271. } else {
  10272. bits |= _gl.COLOR_BUFFER_BIT;
  10273. }
  10274. }
  10275. if ( depth ) {
  10276. bits |= _gl.DEPTH_BUFFER_BIT;
  10277. }
  10278. if ( stencil ) {
  10279. bits |= _gl.STENCIL_BUFFER_BIT;
  10280. this.state.buffers.stencil.setMask( 0xffffffff );
  10281. }
  10282. _gl.clear( bits );
  10283. };
  10284. /**
  10285. * Clears the color buffer. Equivalent to calling `renderer.clear( true, false, false )`.
  10286. */
  10287. this.clearColor = function () {
  10288. this.clear( true, false, false );
  10289. };
  10290. /**
  10291. * Clears the depth buffer. Equivalent to calling `renderer.clear( false, true, false )`.
  10292. */
  10293. this.clearDepth = function () {
  10294. this.clear( false, true, false );
  10295. };
  10296. /**
  10297. * Clears the stencil buffer. Equivalent to calling `renderer.clear( false, false, true )`.
  10298. */
  10299. this.clearStencil = function () {
  10300. this.clear( false, false, true );
  10301. };
  10302. /**
  10303. * Frees the GPU-related resources allocated by this instance. Call this
  10304. * method whenever this instance is no longer used in your app.
  10305. */
  10306. this.dispose = function () {
  10307. canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  10308. canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  10309. canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  10310. background.dispose();
  10311. renderLists.dispose();
  10312. renderStates.dispose();
  10313. properties.dispose();
  10314. cubemaps.dispose();
  10315. cubeuvmaps.dispose();
  10316. objects.dispose();
  10317. bindingStates.dispose();
  10318. uniformsGroups.dispose();
  10319. programCache.dispose();
  10320. xr.dispose();
  10321. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  10322. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  10323. animation.stop();
  10324. };
  10325. // Events
  10326. function onContextLost( event ) {
  10327. event.preventDefault();
  10328. log( 'WebGLRenderer: Context Lost.' );
  10329. _isContextLost = true;
  10330. }
  10331. function onContextRestore( /* event */ ) {
  10332. log( 'WebGLRenderer: Context Restored.' );
  10333. _isContextLost = false;
  10334. const infoAutoReset = info.autoReset;
  10335. const shadowMapEnabled = shadowMap.enabled;
  10336. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  10337. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  10338. const shadowMapType = shadowMap.type;
  10339. initGLContext();
  10340. info.autoReset = infoAutoReset;
  10341. shadowMap.enabled = shadowMapEnabled;
  10342. shadowMap.autoUpdate = shadowMapAutoUpdate;
  10343. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  10344. shadowMap.type = shadowMapType;
  10345. }
  10346. function onContextCreationError( event ) {
  10347. error( 'WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage );
  10348. }
  10349. function onMaterialDispose( event ) {
  10350. const material = event.target;
  10351. material.removeEventListener( 'dispose', onMaterialDispose );
  10352. deallocateMaterial( material );
  10353. }
  10354. // Buffer deallocation
  10355. function deallocateMaterial( material ) {
  10356. releaseMaterialProgramReferences( material );
  10357. properties.remove( material );
  10358. }
  10359. function releaseMaterialProgramReferences( material ) {
  10360. const programs = properties.get( material ).programs;
  10361. if ( programs !== undefined ) {
  10362. programs.forEach( function ( program ) {
  10363. programCache.releaseProgram( program );
  10364. } );
  10365. if ( material.isShaderMaterial ) {
  10366. programCache.releaseShaderCache( material );
  10367. }
  10368. }
  10369. }
  10370. // Buffer rendering
  10371. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  10372. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  10373. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  10374. const program = setProgram( camera, scene, geometry, material, object );
  10375. state.setMaterial( material, frontFaceCW );
  10376. //
  10377. let index = geometry.index;
  10378. let rangeFactor = 1;
  10379. if ( material.wireframe === true ) {
  10380. index = geometries.getWireframeAttribute( geometry );
  10381. if ( index === undefined ) return;
  10382. rangeFactor = 2;
  10383. }
  10384. //
  10385. const drawRange = geometry.drawRange;
  10386. const position = geometry.attributes.position;
  10387. let drawStart = drawRange.start * rangeFactor;
  10388. let drawEnd = ( drawRange.start + drawRange.count ) * rangeFactor;
  10389. if ( group !== null ) {
  10390. drawStart = Math.max( drawStart, group.start * rangeFactor );
  10391. drawEnd = Math.min( drawEnd, ( group.start + group.count ) * rangeFactor );
  10392. }
  10393. if ( index !== null ) {
  10394. drawStart = Math.max( drawStart, 0 );
  10395. drawEnd = Math.min( drawEnd, index.count );
  10396. } else if ( position !== undefined && position !== null ) {
  10397. drawStart = Math.max( drawStart, 0 );
  10398. drawEnd = Math.min( drawEnd, position.count );
  10399. }
  10400. const drawCount = drawEnd - drawStart;
  10401. if ( drawCount < 0 || drawCount === Infinity ) return;
  10402. //
  10403. bindingStates.setup( object, material, program, geometry, index );
  10404. let attribute;
  10405. let renderer = bufferRenderer;
  10406. if ( index !== null ) {
  10407. attribute = attributes.get( index );
  10408. renderer = indexedBufferRenderer;
  10409. renderer.setIndex( attribute );
  10410. }
  10411. //
  10412. if ( object.isMesh ) {
  10413. if ( material.wireframe === true ) {
  10414. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  10415. renderer.setMode( _gl.LINES );
  10416. } else {
  10417. renderer.setMode( _gl.TRIANGLES );
  10418. }
  10419. } else if ( object.isLine ) {
  10420. let lineWidth = material.linewidth;
  10421. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  10422. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  10423. if ( object.isLineSegments ) {
  10424. renderer.setMode( _gl.LINES );
  10425. } else if ( object.isLineLoop ) {
  10426. renderer.setMode( _gl.LINE_LOOP );
  10427. } else {
  10428. renderer.setMode( _gl.LINE_STRIP );
  10429. }
  10430. } else if ( object.isPoints ) {
  10431. renderer.setMode( _gl.POINTS );
  10432. } else if ( object.isSprite ) {
  10433. renderer.setMode( _gl.TRIANGLES );
  10434. }
  10435. if ( object.isBatchedMesh ) {
  10436. if ( object._multiDrawInstances !== null ) {
  10437. // @deprecated, r174
  10438. warnOnce( 'WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  10439. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  10440. } else {
  10441. if ( ! extensions.get( 'WEBGL_multi_draw' ) ) {
  10442. const starts = object._multiDrawStarts;
  10443. const counts = object._multiDrawCounts;
  10444. const drawCount = object._multiDrawCount;
  10445. const bytesPerElement = index ? attributes.get( index ).bytesPerElement : 1;
  10446. const uniforms = properties.get( material ).currentProgram.getUniforms();
  10447. for ( let i = 0; i < drawCount; i ++ ) {
  10448. uniforms.setValue( _gl, '_gl_DrawID', i );
  10449. renderer.render( starts[ i ] / bytesPerElement, counts[ i ] );
  10450. }
  10451. } else {
  10452. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  10453. }
  10454. }
  10455. } else if ( object.isInstancedMesh ) {
  10456. renderer.renderInstances( drawStart, drawCount, object.count );
  10457. } else if ( geometry.isInstancedBufferGeometry ) {
  10458. const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity;
  10459. const instanceCount = Math.min( geometry.instanceCount, maxInstanceCount );
  10460. renderer.renderInstances( drawStart, drawCount, instanceCount );
  10461. } else {
  10462. renderer.render( drawStart, drawCount );
  10463. }
  10464. };
  10465. // Compile
  10466. function prepareMaterial( material, scene, object ) {
  10467. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  10468. material.side = BackSide;
  10469. material.needsUpdate = true;
  10470. getProgram( material, scene, object );
  10471. material.side = FrontSide;
  10472. material.needsUpdate = true;
  10473. getProgram( material, scene, object );
  10474. material.side = DoubleSide;
  10475. } else {
  10476. getProgram( material, scene, object );
  10477. }
  10478. }
  10479. /**
  10480. * Compiles all materials in the scene with the camera. This is useful to precompile shaders
  10481. * before the first rendering. If you want to add a 3D object to an existing scene, use the third
  10482. * optional parameter for applying the target scene.
  10483. *
  10484. * Note that the (target) scene's lighting and environment must be configured before calling this method.
  10485. *
  10486. * @param {Object3D} scene - The scene or another type of 3D object to precompile.
  10487. * @param {Camera} camera - The camera.
  10488. * @param {?Scene} [targetScene=null] - The target scene.
  10489. * @return {Set<Material>} The precompiled materials.
  10490. */
  10491. this.compile = function ( scene, camera, targetScene = null ) {
  10492. if ( targetScene === null ) targetScene = scene;
  10493. currentRenderState = renderStates.get( targetScene );
  10494. currentRenderState.init( camera );
  10495. renderStateStack.push( currentRenderState );
  10496. // gather lights from both the target scene and the new object that will be added to the scene.
  10497. targetScene.traverseVisible( function ( object ) {
  10498. if ( object.isLight && object.layers.test( camera.layers ) ) {
  10499. currentRenderState.pushLight( object );
  10500. if ( object.castShadow ) {
  10501. currentRenderState.pushShadow( object );
  10502. }
  10503. }
  10504. } );
  10505. if ( scene !== targetScene ) {
  10506. scene.traverseVisible( function ( object ) {
  10507. if ( object.isLight && object.layers.test( camera.layers ) ) {
  10508. currentRenderState.pushLight( object );
  10509. if ( object.castShadow ) {
  10510. currentRenderState.pushShadow( object );
  10511. }
  10512. }
  10513. } );
  10514. }
  10515. currentRenderState.setupLights();
  10516. // Only initialize materials in the new scene, not the targetScene.
  10517. const materials = new Set();
  10518. scene.traverse( function ( object ) {
  10519. if ( ! ( object.isMesh || object.isPoints || object.isLine || object.isSprite ) ) {
  10520. return;
  10521. }
  10522. const material = object.material;
  10523. if ( material ) {
  10524. if ( Array.isArray( material ) ) {
  10525. for ( let i = 0; i < material.length; i ++ ) {
  10526. const material2 = material[ i ];
  10527. prepareMaterial( material2, targetScene, object );
  10528. materials.add( material2 );
  10529. }
  10530. } else {
  10531. prepareMaterial( material, targetScene, object );
  10532. materials.add( material );
  10533. }
  10534. }
  10535. } );
  10536. currentRenderState = renderStateStack.pop();
  10537. return materials;
  10538. };
  10539. // compileAsync
  10540. /**
  10541. * Asynchronous version of {@link WebGLRenderer#compile}.
  10542. *
  10543. * This method makes use of the `KHR_parallel_shader_compile` WebGL extension. Hence,
  10544. * it is recommended to use this version of `compile()` whenever possible.
  10545. *
  10546. * @async
  10547. * @param {Object3D} scene - The scene or another type of 3D object to precompile.
  10548. * @param {Camera} camera - The camera.
  10549. * @param {?Scene} [targetScene=null] - The target scene.
  10550. * @return {Promise} A Promise that resolves when the given scene can be rendered without unnecessary stalling due to shader compilation.
  10551. */
  10552. this.compileAsync = function ( scene, camera, targetScene = null ) {
  10553. const materials = this.compile( scene, camera, targetScene );
  10554. // Wait for all the materials in the new object to indicate that they're
  10555. // ready to be used before resolving the promise.
  10556. return new Promise( ( resolve ) => {
  10557. function checkMaterialsReady() {
  10558. materials.forEach( function ( material ) {
  10559. const materialProperties = properties.get( material );
  10560. const program = materialProperties.currentProgram;
  10561. if ( program.isReady() ) {
  10562. // remove any programs that report they're ready to use from the list
  10563. materials.delete( material );
  10564. }
  10565. } );
  10566. // once the list of compiling materials is empty, call the callback
  10567. if ( materials.size === 0 ) {
  10568. resolve( scene );
  10569. return;
  10570. }
  10571. // if some materials are still not ready, wait a bit and check again
  10572. setTimeout( checkMaterialsReady, 10 );
  10573. }
  10574. if ( extensions.get( 'KHR_parallel_shader_compile' ) !== null ) {
  10575. // If we can check the compilation status of the materials without
  10576. // blocking then do so right away.
  10577. checkMaterialsReady();
  10578. } else {
  10579. // Otherwise start by waiting a bit to give the materials we just
  10580. // initialized a chance to finish.
  10581. setTimeout( checkMaterialsReady, 10 );
  10582. }
  10583. } );
  10584. };
  10585. // Animation Loop
  10586. let onAnimationFrameCallback = null;
  10587. function onAnimationFrame( time ) {
  10588. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  10589. }
  10590. function onXRSessionStart() {
  10591. animation.stop();
  10592. }
  10593. function onXRSessionEnd() {
  10594. animation.start();
  10595. }
  10596. const animation = new WebGLAnimation();
  10597. animation.setAnimationLoop( onAnimationFrame );
  10598. if ( typeof self !== 'undefined' ) animation.setContext( self );
  10599. /**
  10600. * Applications are advised to always define the animation loop
  10601. * with this method and not manually with `requestAnimationFrame()`
  10602. * for best compatibility.
  10603. *
  10604. * @param {?onAnimationCallback} callback - The application's animation loop.
  10605. */
  10606. this.setAnimationLoop = function ( callback ) {
  10607. onAnimationFrameCallback = callback;
  10608. xr.setAnimationLoop( callback );
  10609. ( callback === null ) ? animation.stop() : animation.start();
  10610. };
  10611. xr.addEventListener( 'sessionstart', onXRSessionStart );
  10612. xr.addEventListener( 'sessionend', onXRSessionEnd );
  10613. // Rendering
  10614. /**
  10615. * Renders the given scene (or other type of 3D object) using the given camera.
  10616. *
  10617. * The render is done to a previously specified render target set by calling {@link WebGLRenderer#setRenderTarget}
  10618. * or to the canvas as usual.
  10619. *
  10620. * By default render buffers are cleared before rendering but you can prevent
  10621. * this by setting the property `autoClear` to `false`. If you want to prevent
  10622. * only certain buffers being cleared you can `autoClearColor`, `autoClearDepth`
  10623. * or `autoClearStencil` to `false`. To force a clear, use {@link WebGLRenderer#clear}.
  10624. *
  10625. * @param {Object3D} scene - The scene to render.
  10626. * @param {Camera} camera - The camera.
  10627. */
  10628. this.render = function ( scene, camera ) {
  10629. if ( camera !== undefined && camera.isCamera !== true ) {
  10630. error( 'WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  10631. return;
  10632. }
  10633. if ( _isContextLost === true ) return;
  10634. // use internal render target for HalfFloatType color buffer (only when tone mapping is enabled)
  10635. const isXRPresenting = xr.enabled === true && xr.isPresenting === true;
  10636. const useOutput = output !== null && ( _currentRenderTarget === null || isXRPresenting ) && output.begin( _this, _currentRenderTarget );
  10637. // update scene graph
  10638. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  10639. // update camera matrices and frustum
  10640. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  10641. if ( xr.enabled === true && xr.isPresenting === true && ( output === null || output.isCompositing() === false ) ) {
  10642. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  10643. camera = xr.getCamera(); // use XR camera for rendering
  10644. }
  10645. //
  10646. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  10647. currentRenderState = renderStates.get( scene, renderStateStack.length );
  10648. currentRenderState.init( camera );
  10649. renderStateStack.push( currentRenderState );
  10650. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  10651. _frustum.setFromProjectionMatrix( _projScreenMatrix, WebGLCoordinateSystem, camera.reversedDepth );
  10652. _localClippingEnabled = this.localClippingEnabled;
  10653. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled );
  10654. currentRenderList = renderLists.get( scene, renderListStack.length );
  10655. currentRenderList.init();
  10656. renderListStack.push( currentRenderList );
  10657. if ( xr.enabled === true && xr.isPresenting === true ) {
  10658. const depthSensingMesh = _this.xr.getDepthSensingMesh();
  10659. if ( depthSensingMesh !== null ) {
  10660. projectObject( depthSensingMesh, camera, - Infinity, _this.sortObjects );
  10661. }
  10662. }
  10663. projectObject( scene, camera, 0, _this.sortObjects );
  10664. currentRenderList.finish();
  10665. if ( _this.sortObjects === true ) {
  10666. currentRenderList.sort( _opaqueSort, _transparentSort );
  10667. }
  10668. _renderBackground = xr.enabled === false || xr.isPresenting === false || xr.hasDepthSensing() === false;
  10669. if ( _renderBackground ) {
  10670. background.addToRenderList( currentRenderList, scene );
  10671. }
  10672. //
  10673. this.info.render.frame ++;
  10674. if ( _clippingEnabled === true ) clipping.beginShadows();
  10675. const shadowsArray = currentRenderState.state.shadowsArray;
  10676. shadowMap.render( shadowsArray, scene, camera );
  10677. if ( _clippingEnabled === true ) clipping.endShadows();
  10678. //
  10679. if ( this.info.autoReset === true ) this.info.reset();
  10680. // render scene (skip if first effect is a render pass - it will render the scene itself)
  10681. const skipSceneRender = useOutput && output.hasRenderPass();
  10682. if ( skipSceneRender === false ) {
  10683. const opaqueObjects = currentRenderList.opaque;
  10684. const transmissiveObjects = currentRenderList.transmissive;
  10685. currentRenderState.setupLights();
  10686. if ( camera.isArrayCamera ) {
  10687. const cameras = camera.cameras;
  10688. if ( transmissiveObjects.length > 0 ) {
  10689. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  10690. const camera2 = cameras[ i ];
  10691. renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera2 );
  10692. }
  10693. }
  10694. if ( _renderBackground ) background.render( scene );
  10695. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  10696. const camera2 = cameras[ i ];
  10697. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  10698. }
  10699. } else {
  10700. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera );
  10701. if ( _renderBackground ) background.render( scene );
  10702. renderScene( currentRenderList, scene, camera );
  10703. }
  10704. }
  10705. //
  10706. if ( _currentRenderTarget !== null && _currentActiveMipmapLevel === 0 ) {
  10707. // resolve multisample renderbuffers to a single-sample texture if necessary
  10708. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  10709. // Generate mipmap if we're using any kind of mipmap filtering
  10710. textures.updateRenderTargetMipmap( _currentRenderTarget );
  10711. }
  10712. // copy from internal render target to canvas using fullscreen quad
  10713. if ( useOutput ) {
  10714. output.end( _this );
  10715. }
  10716. //
  10717. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  10718. // _gl.finish();
  10719. bindingStates.resetDefaultState();
  10720. _currentMaterialId = -1;
  10721. _currentCamera = null;
  10722. renderStateStack.pop();
  10723. if ( renderStateStack.length > 0 ) {
  10724. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  10725. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, currentRenderState.state.camera );
  10726. } else {
  10727. currentRenderState = null;
  10728. }
  10729. renderListStack.pop();
  10730. if ( renderListStack.length > 0 ) {
  10731. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  10732. } else {
  10733. currentRenderList = null;
  10734. }
  10735. };
  10736. function projectObject( object, camera, groupOrder, sortObjects ) {
  10737. if ( object.visible === false ) return;
  10738. const visible = object.layers.test( camera.layers );
  10739. if ( visible ) {
  10740. if ( object.isGroup ) {
  10741. groupOrder = object.renderOrder;
  10742. } else if ( object.isLOD ) {
  10743. if ( object.autoUpdate === true ) object.update( camera );
  10744. } else if ( object.isLight ) {
  10745. currentRenderState.pushLight( object );
  10746. if ( object.castShadow ) {
  10747. currentRenderState.pushShadow( object );
  10748. }
  10749. } else if ( object.isSprite ) {
  10750. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  10751. if ( sortObjects ) {
  10752. _vector4.setFromMatrixPosition( object.matrixWorld )
  10753. .applyMatrix4( _projScreenMatrix );
  10754. }
  10755. const geometry = objects.update( object );
  10756. const material = object.material;
  10757. if ( material.visible ) {
  10758. currentRenderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  10759. }
  10760. }
  10761. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  10762. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  10763. const geometry = objects.update( object );
  10764. const material = object.material;
  10765. if ( sortObjects ) {
  10766. if ( object.boundingSphere !== undefined ) {
  10767. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  10768. _vector4.copy( object.boundingSphere.center );
  10769. } else {
  10770. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  10771. _vector4.copy( geometry.boundingSphere.center );
  10772. }
  10773. _vector4
  10774. .applyMatrix4( object.matrixWorld )
  10775. .applyMatrix4( _projScreenMatrix );
  10776. }
  10777. if ( Array.isArray( material ) ) {
  10778. const groups = geometry.groups;
  10779. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  10780. const group = groups[ i ];
  10781. const groupMaterial = material[ group.materialIndex ];
  10782. if ( groupMaterial && groupMaterial.visible ) {
  10783. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group );
  10784. }
  10785. }
  10786. } else if ( material.visible ) {
  10787. currentRenderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  10788. }
  10789. }
  10790. }
  10791. }
  10792. const children = object.children;
  10793. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10794. projectObject( children[ i ], camera, groupOrder, sortObjects );
  10795. }
  10796. }
  10797. function renderScene( currentRenderList, scene, camera, viewport ) {
  10798. const { opaque: opaqueObjects, transmissive: transmissiveObjects, transparent: transparentObjects } = currentRenderList;
  10799. currentRenderState.setupLightsView( camera );
  10800. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  10801. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  10802. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  10803. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  10804. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  10805. // Ensure depth buffer writing is enabled so it can be cleared on next render
  10806. state.buffers.depth.setTest( true );
  10807. state.buffers.depth.setMask( true );
  10808. state.buffers.color.setMask( true );
  10809. state.setPolygonOffset( false );
  10810. }
  10811. function renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera ) {
  10812. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  10813. if ( overrideMaterial !== null ) {
  10814. return;
  10815. }
  10816. if ( currentRenderState.state.transmissionRenderTarget[ camera.id ] === undefined ) {
  10817. const hasHalfFloatSupport = extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' );
  10818. currentRenderState.state.transmissionRenderTarget[ camera.id ] = new WebGLRenderTarget( 1, 1, {
  10819. generateMipmaps: true,
  10820. type: hasHalfFloatSupport ? HalfFloatType : UnsignedByteType,
  10821. minFilter: LinearMipmapLinearFilter,
  10822. samples: capabilities.samples,
  10823. stencilBuffer: stencil,
  10824. resolveDepthBuffer: false,
  10825. resolveStencilBuffer: false,
  10826. colorSpace: ColorManagement.workingColorSpace,
  10827. } );
  10828. // debug
  10829. /*
  10830. const geometry = new PlaneGeometry();
  10831. const material = new MeshBasicMaterial( { map: _transmissionRenderTarget.texture } );
  10832. const mesh = new Mesh( geometry, material );
  10833. scene.add( mesh );
  10834. */
  10835. }
  10836. const transmissionRenderTarget = currentRenderState.state.transmissionRenderTarget[ camera.id ];
  10837. const activeViewport = camera.viewport || _currentViewport;
  10838. transmissionRenderTarget.setSize( activeViewport.z * _this.transmissionResolutionScale, activeViewport.w * _this.transmissionResolutionScale );
  10839. //
  10840. const currentRenderTarget = _this.getRenderTarget();
  10841. const currentActiveCubeFace = _this.getActiveCubeFace();
  10842. const currentActiveMipmapLevel = _this.getActiveMipmapLevel();
  10843. _this.setRenderTarget( transmissionRenderTarget );
  10844. _this.getClearColor( _currentClearColor );
  10845. _currentClearAlpha = _this.getClearAlpha();
  10846. if ( _currentClearAlpha < 1 ) _this.setClearColor( 0xffffff, 0.5 );
  10847. _this.clear();
  10848. if ( _renderBackground ) background.render( scene );
  10849. // Turn off the features which can affect the frag color for opaque objects pass.
  10850. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  10851. const currentToneMapping = _this.toneMapping;
  10852. _this.toneMapping = NoToneMapping;
  10853. // Remove viewport from camera to avoid nested render calls resetting viewport to it (e.g Reflector).
  10854. // Transmission render pass requires viewport to match the transmissionRenderTarget.
  10855. const currentCameraViewport = camera.viewport;
  10856. if ( camera.viewport !== undefined ) camera.viewport = undefined;
  10857. currentRenderState.setupLightsView( camera );
  10858. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  10859. renderObjects( opaqueObjects, scene, camera );
  10860. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  10861. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  10862. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === false ) { // see #28131
  10863. let renderTargetNeedsUpdate = false;
  10864. for ( let i = 0, l = transmissiveObjects.length; i < l; i ++ ) {
  10865. const renderItem = transmissiveObjects[ i ];
  10866. const { object, geometry, material, group } = renderItem;
  10867. if ( material.side === DoubleSide && object.layers.test( camera.layers ) ) {
  10868. const currentSide = material.side;
  10869. material.side = BackSide;
  10870. material.needsUpdate = true;
  10871. renderObject( object, scene, camera, geometry, material, group );
  10872. material.side = currentSide;
  10873. material.needsUpdate = true;
  10874. renderTargetNeedsUpdate = true;
  10875. }
  10876. }
  10877. if ( renderTargetNeedsUpdate === true ) {
  10878. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  10879. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  10880. }
  10881. }
  10882. _this.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  10883. _this.setClearColor( _currentClearColor, _currentClearAlpha );
  10884. if ( currentCameraViewport !== undefined ) camera.viewport = currentCameraViewport;
  10885. _this.toneMapping = currentToneMapping;
  10886. }
  10887. function renderObjects( renderList, scene, camera ) {
  10888. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  10889. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  10890. const renderItem = renderList[ i ];
  10891. const { object, geometry, group } = renderItem;
  10892. let material = renderItem.material;
  10893. if ( material.allowOverride === true && overrideMaterial !== null ) {
  10894. material = overrideMaterial;
  10895. }
  10896. if ( object.layers.test( camera.layers ) ) {
  10897. renderObject( object, scene, camera, geometry, material, group );
  10898. }
  10899. }
  10900. }
  10901. function renderObject( object, scene, camera, geometry, material, group ) {
  10902. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  10903. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  10904. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  10905. material.onBeforeRender( _this, scene, camera, geometry, object, group );
  10906. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  10907. material.side = BackSide;
  10908. material.needsUpdate = true;
  10909. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  10910. material.side = FrontSide;
  10911. material.needsUpdate = true;
  10912. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  10913. material.side = DoubleSide;
  10914. } else {
  10915. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  10916. }
  10917. object.onAfterRender( _this, scene, camera, geometry, material, group );
  10918. }
  10919. function getProgram( material, scene, object ) {
  10920. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  10921. const materialProperties = properties.get( material );
  10922. const lights = currentRenderState.state.lights;
  10923. const shadowsArray = currentRenderState.state.shadowsArray;
  10924. const lightsStateVersion = lights.state.version;
  10925. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  10926. const programCacheKey = programCache.getProgramCacheKey( parameters );
  10927. let programs = materialProperties.programs;
  10928. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  10929. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  10930. materialProperties.fog = scene.fog;
  10931. materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment );
  10932. materialProperties.envMapRotation = ( materialProperties.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  10933. if ( programs === undefined ) {
  10934. // new material
  10935. material.addEventListener( 'dispose', onMaterialDispose );
  10936. programs = new Map();
  10937. materialProperties.programs = programs;
  10938. }
  10939. let program = programs.get( programCacheKey );
  10940. if ( program !== undefined ) {
  10941. // early out if program and light state is identical
  10942. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  10943. updateCommonMaterialProperties( material, parameters );
  10944. return program;
  10945. }
  10946. } else {
  10947. parameters.uniforms = programCache.getUniforms( material );
  10948. material.onBeforeCompile( parameters, _this );
  10949. program = programCache.acquireProgram( parameters, programCacheKey );
  10950. programs.set( programCacheKey, program );
  10951. materialProperties.uniforms = parameters.uniforms;
  10952. }
  10953. const uniforms = materialProperties.uniforms;
  10954. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  10955. uniforms.clippingPlanes = clipping.uniform;
  10956. }
  10957. updateCommonMaterialProperties( material, parameters );
  10958. // store the light setup it was created for
  10959. materialProperties.needsLights = materialNeedsLights( material );
  10960. materialProperties.lightsStateVersion = lightsStateVersion;
  10961. if ( materialProperties.needsLights ) {
  10962. // wire up the material to this renderer's lighting state
  10963. uniforms.ambientLightColor.value = lights.state.ambient;
  10964. uniforms.lightProbe.value = lights.state.probe;
  10965. uniforms.directionalLights.value = lights.state.directional;
  10966. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  10967. uniforms.spotLights.value = lights.state.spot;
  10968. uniforms.spotLightShadows.value = lights.state.spotShadow;
  10969. uniforms.rectAreaLights.value = lights.state.rectArea;
  10970. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  10971. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  10972. uniforms.pointLights.value = lights.state.point;
  10973. uniforms.pointLightShadows.value = lights.state.pointShadow;
  10974. uniforms.hemisphereLights.value = lights.state.hemi;
  10975. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  10976. uniforms.spotLightMatrix.value = lights.state.spotLightMatrix;
  10977. uniforms.spotLightMap.value = lights.state.spotLightMap;
  10978. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  10979. // TODO (abelnation): add area lights shadow info to uniforms
  10980. }
  10981. materialProperties.currentProgram = program;
  10982. materialProperties.uniformsList = null;
  10983. return program;
  10984. }
  10985. function getUniformList( materialProperties ) {
  10986. if ( materialProperties.uniformsList === null ) {
  10987. const progUniforms = materialProperties.currentProgram.getUniforms();
  10988. materialProperties.uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, materialProperties.uniforms );
  10989. }
  10990. return materialProperties.uniformsList;
  10991. }
  10992. function updateCommonMaterialProperties( material, parameters ) {
  10993. const materialProperties = properties.get( material );
  10994. materialProperties.outputColorSpace = parameters.outputColorSpace;
  10995. materialProperties.batching = parameters.batching;
  10996. materialProperties.batchingColor = parameters.batchingColor;
  10997. materialProperties.instancing = parameters.instancing;
  10998. materialProperties.instancingColor = parameters.instancingColor;
  10999. materialProperties.instancingMorph = parameters.instancingMorph;
  11000. materialProperties.skinning = parameters.skinning;
  11001. materialProperties.morphTargets = parameters.morphTargets;
  11002. materialProperties.morphNormals = parameters.morphNormals;
  11003. materialProperties.morphColors = parameters.morphColors;
  11004. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  11005. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  11006. materialProperties.numIntersection = parameters.numClipIntersection;
  11007. materialProperties.vertexAlphas = parameters.vertexAlphas;
  11008. materialProperties.vertexTangents = parameters.vertexTangents;
  11009. materialProperties.toneMapping = parameters.toneMapping;
  11010. }
  11011. function setProgram( camera, scene, geometry, material, object ) {
  11012. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  11013. textures.resetTextureUnits();
  11014. const fog = scene.fog;
  11015. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  11016. const colorSpace = ( _currentRenderTarget === null ) ? _this.outputColorSpace : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace );
  11017. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  11018. const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  11019. const vertexTangents = !! geometry.attributes.tangent && ( !! material.normalMap || material.anisotropy > 0 );
  11020. const morphTargets = !! geometry.morphAttributes.position;
  11021. const morphNormals = !! geometry.morphAttributes.normal;
  11022. const morphColors = !! geometry.morphAttributes.color;
  11023. let toneMapping = NoToneMapping;
  11024. if ( material.toneMapped ) {
  11025. if ( _currentRenderTarget === null || _currentRenderTarget.isXRRenderTarget === true ) {
  11026. toneMapping = _this.toneMapping;
  11027. }
  11028. }
  11029. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  11030. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  11031. const materialProperties = properties.get( material );
  11032. const lights = currentRenderState.state.lights;
  11033. if ( _clippingEnabled === true ) {
  11034. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  11035. const useCache =
  11036. camera === _currentCamera &&
  11037. material.id === _currentMaterialId;
  11038. // we might want to call this function with some ClippingGroup
  11039. // object instead of the material, once it becomes feasible
  11040. // (#8465, #8379)
  11041. clipping.setState( material, camera, useCache );
  11042. }
  11043. }
  11044. //
  11045. let needsProgramChange = false;
  11046. if ( material.version === materialProperties.__version ) {
  11047. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  11048. needsProgramChange = true;
  11049. } else if ( materialProperties.outputColorSpace !== colorSpace ) {
  11050. needsProgramChange = true;
  11051. } else if ( object.isBatchedMesh && materialProperties.batching === false ) {
  11052. needsProgramChange = true;
  11053. } else if ( ! object.isBatchedMesh && materialProperties.batching === true ) {
  11054. needsProgramChange = true;
  11055. } else if ( object.isBatchedMesh && materialProperties.batchingColor === true && object.colorTexture === null ) {
  11056. needsProgramChange = true;
  11057. } else if ( object.isBatchedMesh && materialProperties.batchingColor === false && object.colorTexture !== null ) {
  11058. needsProgramChange = true;
  11059. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  11060. needsProgramChange = true;
  11061. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  11062. needsProgramChange = true;
  11063. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  11064. needsProgramChange = true;
  11065. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  11066. needsProgramChange = true;
  11067. } else if ( object.isInstancedMesh && materialProperties.instancingColor === true && object.instanceColor === null ) {
  11068. needsProgramChange = true;
  11069. } else if ( object.isInstancedMesh && materialProperties.instancingColor === false && object.instanceColor !== null ) {
  11070. needsProgramChange = true;
  11071. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === true && object.morphTexture === null ) {
  11072. needsProgramChange = true;
  11073. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === false && object.morphTexture !== null ) {
  11074. needsProgramChange = true;
  11075. } else if ( materialProperties.envMap !== envMap ) {
  11076. needsProgramChange = true;
  11077. } else if ( material.fog === true && materialProperties.fog !== fog ) {
  11078. needsProgramChange = true;
  11079. } else if ( materialProperties.numClippingPlanes !== undefined &&
  11080. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  11081. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  11082. needsProgramChange = true;
  11083. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  11084. needsProgramChange = true;
  11085. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  11086. needsProgramChange = true;
  11087. } else if ( materialProperties.morphTargets !== morphTargets ) {
  11088. needsProgramChange = true;
  11089. } else if ( materialProperties.morphNormals !== morphNormals ) {
  11090. needsProgramChange = true;
  11091. } else if ( materialProperties.morphColors !== morphColors ) {
  11092. needsProgramChange = true;
  11093. } else if ( materialProperties.toneMapping !== toneMapping ) {
  11094. needsProgramChange = true;
  11095. } else if ( materialProperties.morphTargetsCount !== morphTargetsCount ) {
  11096. needsProgramChange = true;
  11097. }
  11098. } else {
  11099. needsProgramChange = true;
  11100. materialProperties.__version = material.version;
  11101. }
  11102. //
  11103. let program = materialProperties.currentProgram;
  11104. if ( needsProgramChange === true ) {
  11105. program = getProgram( material, scene, object );
  11106. }
  11107. let refreshProgram = false;
  11108. let refreshMaterial = false;
  11109. let refreshLights = false;
  11110. const p_uniforms = program.getUniforms(),
  11111. m_uniforms = materialProperties.uniforms;
  11112. if ( state.useProgram( program.program ) ) {
  11113. refreshProgram = true;
  11114. refreshMaterial = true;
  11115. refreshLights = true;
  11116. }
  11117. if ( material.id !== _currentMaterialId ) {
  11118. _currentMaterialId = material.id;
  11119. refreshMaterial = true;
  11120. }
  11121. if ( refreshProgram || _currentCamera !== camera ) {
  11122. // common camera uniforms
  11123. const reversedDepthBuffer = state.buffers.depth.getReversed();
  11124. if ( reversedDepthBuffer && camera.reversedDepth !== true ) {
  11125. camera._reversedDepth = true;
  11126. camera.updateProjectionMatrix();
  11127. }
  11128. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  11129. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  11130. const uCamPos = p_uniforms.map.cameraPosition;
  11131. if ( uCamPos !== undefined ) {
  11132. uCamPos.setValue( _gl, _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  11133. }
  11134. if ( capabilities.logarithmicDepthBuffer ) {
  11135. p_uniforms.setValue( _gl, 'logDepthBufFC',
  11136. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  11137. }
  11138. // consider moving isOrthographic to UniformLib and WebGLMaterials, see https://github.com/mrdoob/three.js/pull/26467#issuecomment-1645185067
  11139. if ( material.isMeshPhongMaterial ||
  11140. material.isMeshToonMaterial ||
  11141. material.isMeshLambertMaterial ||
  11142. material.isMeshBasicMaterial ||
  11143. material.isMeshStandardMaterial ||
  11144. material.isShaderMaterial ) {
  11145. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  11146. }
  11147. if ( _currentCamera !== camera ) {
  11148. _currentCamera = camera;
  11149. // lighting uniforms depend on the camera so enforce an update
  11150. // now, in case this material supports lights - or later, when
  11151. // the next material that does gets activated:
  11152. refreshMaterial = true; // set to true on material change
  11153. refreshLights = true; // remains set until update done
  11154. }
  11155. }
  11156. // Pre-allocate texture units for shadow samplers before setting data textures
  11157. if ( materialProperties.needsLights ) {
  11158. // Set shadow map uniforms first to ensure they get the first texture units
  11159. if ( lights.state.directionalShadowMap.length > 0 ) {
  11160. p_uniforms.setValue( _gl, 'directionalShadowMap', lights.state.directionalShadowMap, textures );
  11161. }
  11162. if ( lights.state.spotShadowMap.length > 0 ) {
  11163. p_uniforms.setValue( _gl, 'spotShadowMap', lights.state.spotShadowMap, textures );
  11164. }
  11165. if ( lights.state.pointShadowMap.length > 0 ) {
  11166. p_uniforms.setValue( _gl, 'pointShadowMap', lights.state.pointShadowMap, textures );
  11167. }
  11168. }
  11169. // skinning and morph target uniforms must be set even if material didn't change
  11170. // auto-setting of texture unit for bone and morph texture must go before other textures
  11171. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  11172. if ( object.isSkinnedMesh ) {
  11173. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  11174. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  11175. const skeleton = object.skeleton;
  11176. if ( skeleton ) {
  11177. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  11178. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  11179. }
  11180. }
  11181. if ( object.isBatchedMesh ) {
  11182. p_uniforms.setOptional( _gl, object, 'batchingTexture' );
  11183. p_uniforms.setValue( _gl, 'batchingTexture', object._matricesTexture, textures );
  11184. p_uniforms.setOptional( _gl, object, 'batchingIdTexture' );
  11185. p_uniforms.setValue( _gl, 'batchingIdTexture', object._indirectTexture, textures );
  11186. p_uniforms.setOptional( _gl, object, 'batchingColorTexture' );
  11187. if ( object._colorsTexture !== null ) {
  11188. p_uniforms.setValue( _gl, 'batchingColorTexture', object._colorsTexture, textures );
  11189. }
  11190. }
  11191. const morphAttributes = geometry.morphAttributes;
  11192. if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined ) ) {
  11193. morphtargets.update( object, geometry, program );
  11194. }
  11195. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  11196. materialProperties.receiveShadow = object.receiveShadow;
  11197. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  11198. }
  11199. if ( material.isMeshStandardMaterial && material.envMap === null && scene.environment !== null ) {
  11200. m_uniforms.envMapIntensity.value = scene.environmentIntensity;
  11201. }
  11202. // Set DFG LUT for physically-based materials
  11203. if ( m_uniforms.dfgLUT !== undefined ) {
  11204. m_uniforms.dfgLUT.value = getDFGLUT();
  11205. }
  11206. if ( refreshMaterial ) {
  11207. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  11208. if ( materialProperties.needsLights ) {
  11209. // the current material requires lighting info
  11210. // note: all lighting uniforms are always set correctly
  11211. // they simply reference the renderer's state for their
  11212. // values
  11213. //
  11214. // use the current material's .needsUpdate flags to set
  11215. // the GL state when required
  11216. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  11217. }
  11218. // refresh uniforms common to several materials
  11219. if ( fog && material.fog === true ) {
  11220. materials.refreshFogUniforms( m_uniforms, fog );
  11221. }
  11222. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, currentRenderState.state.transmissionRenderTarget[ camera.id ] );
  11223. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  11224. }
  11225. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  11226. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  11227. material.uniformsNeedUpdate = false;
  11228. }
  11229. if ( material.isSpriteMaterial ) {
  11230. p_uniforms.setValue( _gl, 'center', object.center );
  11231. }
  11232. // common matrices
  11233. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  11234. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  11235. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  11236. // UBOs
  11237. if ( material.isShaderMaterial || material.isRawShaderMaterial ) {
  11238. const groups = material.uniformsGroups;
  11239. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  11240. const group = groups[ i ];
  11241. uniformsGroups.update( group, program );
  11242. uniformsGroups.bind( group, program );
  11243. }
  11244. }
  11245. return program;
  11246. }
  11247. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  11248. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  11249. uniforms.ambientLightColor.needsUpdate = value;
  11250. uniforms.lightProbe.needsUpdate = value;
  11251. uniforms.directionalLights.needsUpdate = value;
  11252. uniforms.directionalLightShadows.needsUpdate = value;
  11253. uniforms.pointLights.needsUpdate = value;
  11254. uniforms.pointLightShadows.needsUpdate = value;
  11255. uniforms.spotLights.needsUpdate = value;
  11256. uniforms.spotLightShadows.needsUpdate = value;
  11257. uniforms.rectAreaLights.needsUpdate = value;
  11258. uniforms.hemisphereLights.needsUpdate = value;
  11259. }
  11260. function materialNeedsLights( material ) {
  11261. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  11262. material.isMeshStandardMaterial || material.isShadowMaterial ||
  11263. ( material.isShaderMaterial && material.lights === true );
  11264. }
  11265. /**
  11266. * Returns the active cube face.
  11267. *
  11268. * @return {number} The active cube face.
  11269. */
  11270. this.getActiveCubeFace = function () {
  11271. return _currentActiveCubeFace;
  11272. };
  11273. /**
  11274. * Returns the active mipmap level.
  11275. *
  11276. * @return {number} The active mipmap level.
  11277. */
  11278. this.getActiveMipmapLevel = function () {
  11279. return _currentActiveMipmapLevel;
  11280. };
  11281. /**
  11282. * Returns the active render target.
  11283. *
  11284. * @return {?WebGLRenderTarget} The active render target. Returns `null` if no render target
  11285. * is currently set.
  11286. */
  11287. this.getRenderTarget = function () {
  11288. return _currentRenderTarget;
  11289. };
  11290. this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) {
  11291. const renderTargetProperties = properties.get( renderTarget );
  11292. renderTargetProperties.__autoAllocateDepthBuffer = renderTarget.resolveDepthBuffer === false;
  11293. if ( renderTargetProperties.__autoAllocateDepthBuffer === false ) {
  11294. // The multisample_render_to_texture extension doesn't work properly if there
  11295. // are midframe flushes and an external depth buffer. Disable use of the extension.
  11296. renderTargetProperties.__useRenderToTexture = false;
  11297. }
  11298. properties.get( renderTarget.texture ).__webglTexture = colorTexture;
  11299. properties.get( renderTarget.depthTexture ).__webglTexture = renderTargetProperties.__autoAllocateDepthBuffer ? undefined : depthTexture;
  11300. renderTargetProperties.__hasExternalTextures = true;
  11301. };
  11302. this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) {
  11303. const renderTargetProperties = properties.get( renderTarget );
  11304. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  11305. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  11306. };
  11307. const _scratchFrameBuffer = _gl.createFramebuffer();
  11308. /**
  11309. * Sets the active rendertarget.
  11310. *
  11311. * @param {?WebGLRenderTarget} renderTarget - The render target to set. When `null` is given,
  11312. * the canvas is set as the active render target instead.
  11313. * @param {number} [activeCubeFace=0] - The active cube face when using a cube render target.
  11314. * Indicates the z layer to render in to when using 3D or array render targets.
  11315. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  11316. */
  11317. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  11318. _currentRenderTarget = renderTarget;
  11319. _currentActiveCubeFace = activeCubeFace;
  11320. _currentActiveMipmapLevel = activeMipmapLevel;
  11321. let framebuffer = null;
  11322. let isCube = false;
  11323. let isRenderTarget3D = false;
  11324. if ( renderTarget ) {
  11325. const renderTargetProperties = properties.get( renderTarget );
  11326. if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) {
  11327. // Externally-managed framebuffer (e.g. XR)
  11328. // Bind to the stored framebuffer (may be null for default, or a WebGLFramebuffer)
  11329. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  11330. _currentViewport.copy( renderTarget.viewport );
  11331. _currentScissor.copy( renderTarget.scissor );
  11332. _currentScissorTest = renderTarget.scissorTest;
  11333. state.viewport( _currentViewport );
  11334. state.scissor( _currentScissor );
  11335. state.setScissorTest( _currentScissorTest );
  11336. _currentMaterialId = -1;
  11337. return;
  11338. } else if ( renderTargetProperties.__webglFramebuffer === undefined ) {
  11339. textures.setupRenderTarget( renderTarget );
  11340. } else if ( renderTargetProperties.__hasExternalTextures ) {
  11341. // Color and depth texture must be rebound in order for the swapchain to update.
  11342. textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture );
  11343. } else if ( renderTarget.depthBuffer ) {
  11344. // check if the depth texture is already bound to the frame buffer and that it's been initialized
  11345. const depthTexture = renderTarget.depthTexture;
  11346. if ( renderTargetProperties.__boundDepthTexture !== depthTexture ) {
  11347. // check if the depth texture is compatible
  11348. if (
  11349. depthTexture !== null &&
  11350. properties.has( depthTexture ) &&
  11351. ( renderTarget.width !== depthTexture.image.width || renderTarget.height !== depthTexture.image.height )
  11352. ) {
  11353. throw new Error( 'WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.' );
  11354. }
  11355. // Swap the depth buffer to the currently attached one
  11356. textures.setupDepthRenderbuffer( renderTarget );
  11357. }
  11358. }
  11359. const texture = renderTarget.texture;
  11360. if ( texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  11361. isRenderTarget3D = true;
  11362. }
  11363. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  11364. if ( renderTarget.isWebGLCubeRenderTarget ) {
  11365. if ( Array.isArray( __webglFramebuffer[ activeCubeFace ] ) ) {
  11366. framebuffer = __webglFramebuffer[ activeCubeFace ][ activeMipmapLevel ];
  11367. } else {
  11368. framebuffer = __webglFramebuffer[ activeCubeFace ];
  11369. }
  11370. isCube = true;
  11371. } else if ( ( renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) {
  11372. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  11373. } else {
  11374. if ( Array.isArray( __webglFramebuffer ) ) {
  11375. framebuffer = __webglFramebuffer[ activeMipmapLevel ];
  11376. } else {
  11377. framebuffer = __webglFramebuffer;
  11378. }
  11379. }
  11380. _currentViewport.copy( renderTarget.viewport );
  11381. _currentScissor.copy( renderTarget.scissor );
  11382. _currentScissorTest = renderTarget.scissorTest;
  11383. } else {
  11384. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  11385. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  11386. _currentScissorTest = _scissorTest;
  11387. }
  11388. // Use a scratch frame buffer if rendering to a mip level to avoid depth buffers
  11389. // being bound that are different sizes.
  11390. if ( activeMipmapLevel !== 0 ) {
  11391. framebuffer = _scratchFrameBuffer;
  11392. }
  11393. const framebufferBound = state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  11394. if ( framebufferBound ) {
  11395. state.drawBuffers( renderTarget, framebuffer );
  11396. }
  11397. state.viewport( _currentViewport );
  11398. state.scissor( _currentScissor );
  11399. state.setScissorTest( _currentScissorTest );
  11400. if ( isCube ) {
  11401. const textureProperties = properties.get( renderTarget.texture );
  11402. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  11403. } else if ( isRenderTarget3D ) {
  11404. const layer = activeCubeFace;
  11405. for ( let i = 0; i < renderTarget.textures.length; i ++ ) {
  11406. const textureProperties = properties.get( renderTarget.textures[ i ] );
  11407. _gl.framebufferTextureLayer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, textureProperties.__webglTexture, activeMipmapLevel, layer );
  11408. }
  11409. } else if ( renderTarget !== null && activeMipmapLevel !== 0 ) {
  11410. // Only bind the frame buffer if we are using a scratch frame buffer to render to a mipmap.
  11411. // If we rebind the texture when using a multi sample buffer then an error about inconsistent samples will be thrown.
  11412. const textureProperties = properties.get( renderTarget.texture );
  11413. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, textureProperties.__webglTexture, activeMipmapLevel );
  11414. }
  11415. _currentMaterialId = -1; // reset current material to ensure correct uniform bindings
  11416. };
  11417. /**
  11418. * Reads the pixel data from the given render target into the given buffer.
  11419. *
  11420. * @param {WebGLRenderTarget} renderTarget - The render target to read from.
  11421. * @param {number} x - The `x` coordinate of the copy region's origin.
  11422. * @param {number} y - The `y` coordinate of the copy region's origin.
  11423. * @param {number} width - The width of the copy region.
  11424. * @param {number} height - The height of the copy region.
  11425. * @param {TypedArray} buffer - The result buffer.
  11426. * @param {number} [activeCubeFaceIndex] - The active cube face index.
  11427. * @param {number} [textureIndex=0] - The texture index of an MRT render target.
  11428. */
  11429. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex, textureIndex = 0 ) {
  11430. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  11431. error( 'WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  11432. return;
  11433. }
  11434. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  11435. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  11436. framebuffer = framebuffer[ activeCubeFaceIndex ];
  11437. }
  11438. if ( framebuffer ) {
  11439. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  11440. try {
  11441. const texture = renderTarget.textures[ textureIndex ];
  11442. const textureFormat = texture.format;
  11443. const textureType = texture.type;
  11444. // when using MRT, select the correct color buffer for the subsequent read command
  11445. if ( renderTarget.textures.length > 1 ) _gl.readBuffer( _gl.COLOR_ATTACHMENT0 + textureIndex );
  11446. if ( ! capabilities.textureFormatReadable( textureFormat ) ) {
  11447. error( 'WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  11448. return;
  11449. }
  11450. if ( ! capabilities.textureTypeReadable( textureType ) ) {
  11451. error( 'WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  11452. return;
  11453. }
  11454. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  11455. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  11456. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  11457. }
  11458. } finally {
  11459. // restore framebuffer of current render target if necessary
  11460. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  11461. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  11462. }
  11463. }
  11464. };
  11465. /**
  11466. * Asynchronous, non-blocking version of {@link WebGLRenderer#readRenderTargetPixels}.
  11467. *
  11468. * It is recommended to use this version of `readRenderTargetPixels()` whenever possible.
  11469. *
  11470. * @async
  11471. * @param {WebGLRenderTarget} renderTarget - The render target to read from.
  11472. * @param {number} x - The `x` coordinate of the copy region's origin.
  11473. * @param {number} y - The `y` coordinate of the copy region's origin.
  11474. * @param {number} width - The width of the copy region.
  11475. * @param {number} height - The height of the copy region.
  11476. * @param {TypedArray} buffer - The result buffer.
  11477. * @param {number} [activeCubeFaceIndex] - The active cube face index.
  11478. * @param {number} [textureIndex=0] - The texture index of an MRT render target.
  11479. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  11480. */
  11481. this.readRenderTargetPixelsAsync = async function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex, textureIndex = 0 ) {
  11482. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  11483. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  11484. }
  11485. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  11486. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  11487. framebuffer = framebuffer[ activeCubeFaceIndex ];
  11488. }
  11489. if ( framebuffer ) {
  11490. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  11491. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  11492. // set the active frame buffer to the one we want to read
  11493. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  11494. const texture = renderTarget.textures[ textureIndex ];
  11495. const textureFormat = texture.format;
  11496. const textureType = texture.type;
  11497. // when using MRT, select the correct color buffer for the subsequent read command
  11498. if ( renderTarget.textures.length > 1 ) _gl.readBuffer( _gl.COLOR_ATTACHMENT0 + textureIndex );
  11499. if ( ! capabilities.textureFormatReadable( textureFormat ) ) {
  11500. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.' );
  11501. }
  11502. if ( ! capabilities.textureTypeReadable( textureType ) ) {
  11503. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.' );
  11504. }
  11505. const glBuffer = _gl.createBuffer();
  11506. _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer );
  11507. _gl.bufferData( _gl.PIXEL_PACK_BUFFER, buffer.byteLength, _gl.STREAM_READ );
  11508. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), 0 );
  11509. // reset the frame buffer to the currently set buffer before waiting
  11510. const currFramebuffer = _currentRenderTarget !== null ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  11511. state.bindFramebuffer( _gl.FRAMEBUFFER, currFramebuffer );
  11512. // check if the commands have finished every 8 ms
  11513. const sync = _gl.fenceSync( _gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  11514. _gl.flush();
  11515. await probeAsync( _gl, sync, 4 );
  11516. // read the data and delete the buffer
  11517. _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer );
  11518. _gl.getBufferSubData( _gl.PIXEL_PACK_BUFFER, 0, buffer );
  11519. _gl.deleteBuffer( glBuffer );
  11520. _gl.deleteSync( sync );
  11521. return buffer;
  11522. } else {
  11523. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.' );
  11524. }
  11525. }
  11526. };
  11527. /**
  11528. * Copies pixels from the current bound framebuffer into the given texture.
  11529. *
  11530. * @param {FramebufferTexture} texture - The texture.
  11531. * @param {?Vector2} [position=null] - The start position of the copy operation.
  11532. * @param {number} [level=0] - The mip level. The default represents the base mip.
  11533. */
  11534. this.copyFramebufferToTexture = function ( texture, position = null, level = 0 ) {
  11535. const levelScale = Math.pow( 2, - level );
  11536. const width = Math.floor( texture.image.width * levelScale );
  11537. const height = Math.floor( texture.image.height * levelScale );
  11538. const x = position !== null ? position.x : 0;
  11539. const y = position !== null ? position.y : 0;
  11540. textures.setTexture2D( texture, 0 );
  11541. _gl.copyTexSubImage2D( _gl.TEXTURE_2D, level, 0, 0, x, y, width, height );
  11542. state.unbindTexture();
  11543. };
  11544. const _srcFramebuffer = _gl.createFramebuffer();
  11545. const _dstFramebuffer = _gl.createFramebuffer();
  11546. /**
  11547. * Copies data of the given source texture into a destination texture.
  11548. *
  11549. * When using render target textures as `srcTexture` and `dstTexture`, you must make sure both render targets are initialized
  11550. * {@link WebGLRenderer#initRenderTarget}.
  11551. *
  11552. * @param {Texture} srcTexture - The source texture.
  11553. * @param {Texture} dstTexture - The destination texture.
  11554. * @param {?(Box2|Box3)} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  11555. * @param {?(Vector2|Vector3)} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  11556. * @param {number} [srcLevel=0] - The source mipmap level to copy.
  11557. * @param {?number} [dstLevel=0] - The destination mipmap level.
  11558. */
  11559. this.copyTextureToTexture = function ( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  11560. // gather the necessary dimensions to copy
  11561. let width, height, depth, minX, minY, minZ;
  11562. let dstX, dstY, dstZ;
  11563. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image;
  11564. if ( srcRegion !== null ) {
  11565. width = srcRegion.max.x - srcRegion.min.x;
  11566. height = srcRegion.max.y - srcRegion.min.y;
  11567. depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1;
  11568. minX = srcRegion.min.x;
  11569. minY = srcRegion.min.y;
  11570. minZ = srcRegion.isBox3 ? srcRegion.min.z : 0;
  11571. } else {
  11572. const levelScale = Math.pow( 2, - srcLevel );
  11573. width = Math.floor( image.width * levelScale );
  11574. height = Math.floor( image.height * levelScale );
  11575. if ( srcTexture.isDataArrayTexture ) {
  11576. depth = image.depth;
  11577. } else if ( srcTexture.isData3DTexture ) {
  11578. depth = Math.floor( image.depth * levelScale );
  11579. } else {
  11580. depth = 1;
  11581. }
  11582. minX = 0;
  11583. minY = 0;
  11584. minZ = 0;
  11585. }
  11586. if ( dstPosition !== null ) {
  11587. dstX = dstPosition.x;
  11588. dstY = dstPosition.y;
  11589. dstZ = dstPosition.z;
  11590. } else {
  11591. dstX = 0;
  11592. dstY = 0;
  11593. dstZ = 0;
  11594. }
  11595. // Set up the destination target
  11596. const glFormat = utils.convert( dstTexture.format );
  11597. const glType = utils.convert( dstTexture.type );
  11598. let glTarget;
  11599. if ( dstTexture.isData3DTexture ) {
  11600. textures.setTexture3D( dstTexture, 0 );
  11601. glTarget = _gl.TEXTURE_3D;
  11602. } else if ( dstTexture.isDataArrayTexture || dstTexture.isCompressedArrayTexture ) {
  11603. textures.setTexture2DArray( dstTexture, 0 );
  11604. glTarget = _gl.TEXTURE_2D_ARRAY;
  11605. } else {
  11606. textures.setTexture2D( dstTexture, 0 );
  11607. glTarget = _gl.TEXTURE_2D;
  11608. }
  11609. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  11610. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  11611. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  11612. // used for copying data from cpu
  11613. const currentUnpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  11614. const currentUnpackImageHeight = _gl.getParameter( _gl.UNPACK_IMAGE_HEIGHT );
  11615. const currentUnpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  11616. const currentUnpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  11617. const currentUnpackSkipImages = _gl.getParameter( _gl.UNPACK_SKIP_IMAGES );
  11618. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  11619. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, image.height );
  11620. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, minX );
  11621. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, minY );
  11622. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, minZ );
  11623. // set up the src texture
  11624. const isSrc3D = srcTexture.isDataArrayTexture || srcTexture.isData3DTexture;
  11625. const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture;
  11626. if ( srcTexture.isDepthTexture ) {
  11627. const srcTextureProperties = properties.get( srcTexture );
  11628. const dstTextureProperties = properties.get( dstTexture );
  11629. const srcRenderTargetProperties = properties.get( srcTextureProperties.__renderTarget );
  11630. const dstRenderTargetProperties = properties.get( dstTextureProperties.__renderTarget );
  11631. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, srcRenderTargetProperties.__webglFramebuffer );
  11632. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, dstRenderTargetProperties.__webglFramebuffer );
  11633. for ( let i = 0; i < depth; i ++ ) {
  11634. // if the source or destination are a 3d target then a layer needs to be bound
  11635. if ( isSrc3D ) {
  11636. _gl.framebufferTextureLayer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get( srcTexture ).__webglTexture, srcLevel, minZ + i );
  11637. _gl.framebufferTextureLayer( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get( dstTexture ).__webglTexture, dstLevel, dstZ + i );
  11638. }
  11639. _gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, _gl.DEPTH_BUFFER_BIT, _gl.NEAREST );
  11640. }
  11641. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  11642. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  11643. } else if ( srcLevel !== 0 || srcTexture.isRenderTargetTexture || properties.has( srcTexture ) ) {
  11644. // get the appropriate frame buffers
  11645. const srcTextureProperties = properties.get( srcTexture );
  11646. const dstTextureProperties = properties.get( dstTexture );
  11647. // bind the frame buffer targets
  11648. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, _srcFramebuffer );
  11649. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, _dstFramebuffer );
  11650. for ( let i = 0; i < depth; i ++ ) {
  11651. // assign the correct layers and mip maps to the frame buffers
  11652. if ( isSrc3D ) {
  11653. _gl.framebufferTextureLayer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, srcTextureProperties.__webglTexture, srcLevel, minZ + i );
  11654. } else {
  11655. _gl.framebufferTexture2D( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, srcTextureProperties.__webglTexture, srcLevel );
  11656. }
  11657. if ( isDst3D ) {
  11658. _gl.framebufferTextureLayer( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, dstTextureProperties.__webglTexture, dstLevel, dstZ + i );
  11659. } else {
  11660. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, dstTextureProperties.__webglTexture, dstLevel );
  11661. }
  11662. // copy the data using the fastest function that can achieve the copy
  11663. if ( srcLevel !== 0 ) {
  11664. _gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, _gl.COLOR_BUFFER_BIT, _gl.NEAREST );
  11665. } else if ( isDst3D ) {
  11666. _gl.copyTexSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ + i, minX, minY, width, height );
  11667. } else {
  11668. _gl.copyTexSubImage2D( glTarget, dstLevel, dstX, dstY, minX, minY, width, height );
  11669. }
  11670. }
  11671. // unbind read, draw buffers
  11672. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  11673. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  11674. } else {
  11675. if ( isDst3D ) {
  11676. // copy data into the 3d texture
  11677. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  11678. _gl.texSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  11679. } else if ( dstTexture.isCompressedArrayTexture ) {
  11680. _gl.compressedTexSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  11681. } else {
  11682. _gl.texSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  11683. }
  11684. } else {
  11685. // copy data into the 2d texture
  11686. if ( srcTexture.isDataTexture ) {
  11687. _gl.texSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data );
  11688. } else if ( srcTexture.isCompressedTexture ) {
  11689. _gl.compressedTexSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data );
  11690. } else {
  11691. _gl.texSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image );
  11692. }
  11693. }
  11694. }
  11695. // reset values
  11696. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  11697. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  11698. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  11699. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  11700. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  11701. // Generate mipmaps only when copying level 0
  11702. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  11703. _gl.generateMipmap( glTarget );
  11704. }
  11705. state.unbindTexture();
  11706. };
  11707. /**
  11708. * Initializes the given WebGLRenderTarget memory. Useful for initializing a render target so data
  11709. * can be copied into it using {@link WebGLRenderer#copyTextureToTexture} before it has been
  11710. * rendered to.
  11711. *
  11712. * @param {WebGLRenderTarget} target - The render target.
  11713. */
  11714. this.initRenderTarget = function ( target ) {
  11715. if ( properties.get( target ).__webglFramebuffer === undefined ) {
  11716. textures.setupRenderTarget( target );
  11717. }
  11718. };
  11719. /**
  11720. * Initializes the given texture. Useful for preloading a texture rather than waiting until first
  11721. * render (which can cause noticeable lags due to decode and GPU upload overhead).
  11722. *
  11723. * @param {Texture} texture - The texture.
  11724. */
  11725. this.initTexture = function ( texture ) {
  11726. if ( texture.isCubeTexture ) {
  11727. textures.setTextureCube( texture, 0 );
  11728. } else if ( texture.isData3DTexture ) {
  11729. textures.setTexture3D( texture, 0 );
  11730. } else if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  11731. textures.setTexture2DArray( texture, 0 );
  11732. } else {
  11733. textures.setTexture2D( texture, 0 );
  11734. }
  11735. state.unbindTexture();
  11736. };
  11737. /**
  11738. * Can be used to reset the internal WebGL state. This method is mostly
  11739. * relevant for applications which share a single WebGL context across
  11740. * multiple WebGL libraries.
  11741. */
  11742. this.resetState = function () {
  11743. _currentActiveCubeFace = 0;
  11744. _currentActiveMipmapLevel = 0;
  11745. _currentRenderTarget = null;
  11746. state.reset();
  11747. bindingStates.reset();
  11748. };
  11749. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  11750. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  11751. }
  11752. }
  11753. /**
  11754. * Defines the coordinate system of the renderer.
  11755. *
  11756. * In `WebGLRenderer`, the value is always `WebGLCoordinateSystem`.
  11757. *
  11758. * @type {WebGLCoordinateSystem|WebGPUCoordinateSystem}
  11759. * @default WebGLCoordinateSystem
  11760. * @readonly
  11761. */
  11762. get coordinateSystem() {
  11763. return WebGLCoordinateSystem;
  11764. }
  11765. /**
  11766. * Defines the output color space of the renderer.
  11767. *
  11768. * @type {SRGBColorSpace|LinearSRGBColorSpace}
  11769. * @default SRGBColorSpace
  11770. */
  11771. get outputColorSpace() {
  11772. return this._outputColorSpace;
  11773. }
  11774. set outputColorSpace( colorSpace ) {
  11775. this._outputColorSpace = colorSpace;
  11776. const gl = this.getContext();
  11777. gl.drawingBufferColorSpace = ColorManagement._getDrawingBufferColorSpace( colorSpace );
  11778. gl.unpackColorSpace = ColorManagement._getUnpackColorSpace();
  11779. }
  11780. }
  11781. export { ACESFilmicToneMapping, AddEquation, AddOperation, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, ArrayCamera, BackSide, BoxGeometry, BufferAttribute, BufferGeometry, ByteType, CineonToneMapping, ClampToEdgeWrapping, Color, ColorManagement, ConstantAlphaFactor, ConstantColorFactor, CubeDepthTexture, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeUVReflectionMapping, CullFaceBack, CullFaceFront, CullFaceNone, CustomBlending, CustomToneMapping, Data3DTexture, DataArrayTexture, DataTexture, DepthFormat, DepthStencilFormat, DepthTexture, DoubleSide, DstAlphaFactor, DstColorFactor, EqualCompare, EqualDepth, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExternalTexture, Float32BufferAttribute, FloatType, FrontSide, Frustum, GLSL3, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, HalfFloatType, IntType, Layers, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LinearFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, LinearTransfer, Matrix3, Matrix4, MaxEquation, Mesh, MeshBasicMaterial, MeshDepthMaterial, MeshDistanceMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NoBlending, NoColorSpace, NoToneMapping, NormalBlending, NotEqualCompare, NotEqualDepth, ObjectSpaceNormalMap, OneFactor, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, PCFShadowMap, PCFSoftShadowMap, PMREMGenerator, PerspectiveCamera, Plane, PlaneGeometry, R11_EAC_Format, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RG11_EAC_Format, 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, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RawShaderMaterial, RedFormat, RedIntegerFormat, ReinhardToneMapping, RepeatWrapping, ReverseSubtractEquation, SIGNED_R11_EAC_Format, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SIGNED_RG11_EAC_Format, SRGBColorSpace, SRGBTransfer, ShaderChunk, ShaderLib, ShaderMaterial, ShortType, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, SubtractEquation, SubtractiveBlending, TangentSpaceNormalMap, Texture, Uint16BufferAttribute, Uint32BufferAttribute, UniformsLib, UniformsUtils, UnsignedByteType, UnsignedInt101111Type, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, VSMShadowMap, Vector2, Vector3, Vector4, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGLRenderTarget, WebGLRenderer, WebGLUtils, WebXRController, ZeroFactor, createCanvasElement, error, log, warn, warnOnce };
粤ICP备19079148号