rasterizer_scene_gles3.cpp 206 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401
  1. /*************************************************************************/
  2. /* rasterizer_scene_gles3.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "rasterizer_scene_gles3.h"
  31. #include "core/math/math_funcs.h"
  32. #include "core/os/os.h"
  33. #include "core/project_settings.h"
  34. #include "rasterizer_canvas_gles3.h"
  35. #include "servers/camera/camera_feed.h"
  36. #include "servers/visual/visual_server_raster.h"
  37. #ifndef GLES_OVER_GL
  38. #define glClearDepth glClearDepthf
  39. #endif
  40. static const GLenum _cube_side_enum[6] = {
  41. GL_TEXTURE_CUBE_MAP_NEGATIVE_X,
  42. GL_TEXTURE_CUBE_MAP_POSITIVE_X,
  43. GL_TEXTURE_CUBE_MAP_NEGATIVE_Y,
  44. GL_TEXTURE_CUBE_MAP_POSITIVE_Y,
  45. GL_TEXTURE_CUBE_MAP_NEGATIVE_Z,
  46. GL_TEXTURE_CUBE_MAP_POSITIVE_Z,
  47. };
  48. static _FORCE_INLINE_ void store_transform(const Transform &p_mtx, float *p_array) {
  49. p_array[0] = p_mtx.basis.elements[0][0];
  50. p_array[1] = p_mtx.basis.elements[1][0];
  51. p_array[2] = p_mtx.basis.elements[2][0];
  52. p_array[3] = 0;
  53. p_array[4] = p_mtx.basis.elements[0][1];
  54. p_array[5] = p_mtx.basis.elements[1][1];
  55. p_array[6] = p_mtx.basis.elements[2][1];
  56. p_array[7] = 0;
  57. p_array[8] = p_mtx.basis.elements[0][2];
  58. p_array[9] = p_mtx.basis.elements[1][2];
  59. p_array[10] = p_mtx.basis.elements[2][2];
  60. p_array[11] = 0;
  61. p_array[12] = p_mtx.origin.x;
  62. p_array[13] = p_mtx.origin.y;
  63. p_array[14] = p_mtx.origin.z;
  64. p_array[15] = 1;
  65. }
  66. static _FORCE_INLINE_ void store_camera(const CameraMatrix &p_mtx, float *p_array) {
  67. for (int i = 0; i < 4; i++) {
  68. for (int j = 0; j < 4; j++) {
  69. p_array[i * 4 + j] = p_mtx.matrix[i][j];
  70. }
  71. }
  72. }
  73. /* SHADOW ATLAS API */
  74. RID RasterizerSceneGLES3::shadow_atlas_create() {
  75. ShadowAtlas *shadow_atlas = memnew(ShadowAtlas);
  76. shadow_atlas->fbo = 0;
  77. shadow_atlas->depth = 0;
  78. shadow_atlas->size = 0;
  79. shadow_atlas->smallest_subdiv = 0;
  80. for (int i = 0; i < 4; i++) {
  81. shadow_atlas->size_order[i] = i;
  82. }
  83. return shadow_atlas_owner.make_rid(shadow_atlas);
  84. }
  85. void RasterizerSceneGLES3::shadow_atlas_set_size(RID p_atlas, int p_size) {
  86. ShadowAtlas *shadow_atlas = shadow_atlas_owner.getornull(p_atlas);
  87. ERR_FAIL_COND(!shadow_atlas);
  88. ERR_FAIL_COND(p_size < 0);
  89. p_size = next_power_of_2(p_size);
  90. if (p_size == shadow_atlas->size)
  91. return;
  92. // erasing atlas
  93. if (shadow_atlas->fbo) {
  94. glDeleteTextures(1, &shadow_atlas->depth);
  95. glDeleteFramebuffers(1, &shadow_atlas->fbo);
  96. shadow_atlas->depth = 0;
  97. shadow_atlas->fbo = 0;
  98. }
  99. for (int i = 0; i < 4; i++) {
  100. //clear subdivisions
  101. shadow_atlas->quadrants[i].shadows.resize(0);
  102. shadow_atlas->quadrants[i].shadows.resize(1 << shadow_atlas->quadrants[i].subdivision);
  103. }
  104. //erase shadow atlas reference from lights
  105. for (Map<RID, uint32_t>::Element *E = shadow_atlas->shadow_owners.front(); E; E = E->next()) {
  106. LightInstance *li = light_instance_owner.getornull(E->key());
  107. ERR_CONTINUE(!li);
  108. li->shadow_atlases.erase(p_atlas);
  109. }
  110. //clear owners
  111. shadow_atlas->shadow_owners.clear();
  112. shadow_atlas->size = p_size;
  113. if (shadow_atlas->size) {
  114. glGenFramebuffers(1, &shadow_atlas->fbo);
  115. glBindFramebuffer(GL_FRAMEBUFFER, shadow_atlas->fbo);
  116. // Create a texture for storing the depth
  117. glActiveTexture(GL_TEXTURE0);
  118. glGenTextures(1, &shadow_atlas->depth);
  119. glBindTexture(GL_TEXTURE_2D, shadow_atlas->depth);
  120. glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, shadow_atlas->size, shadow_atlas->size, 0,
  121. GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL);
  122. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  123. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  124. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  125. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  126. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
  127. GL_TEXTURE_2D, shadow_atlas->depth, 0);
  128. glViewport(0, 0, shadow_atlas->size, shadow_atlas->size);
  129. glClearDepth(0.0f);
  130. glClear(GL_DEPTH_BUFFER_BIT);
  131. glBindFramebuffer(GL_FRAMEBUFFER, 0);
  132. }
  133. }
  134. void RasterizerSceneGLES3::shadow_atlas_set_quadrant_subdivision(RID p_atlas, int p_quadrant, int p_subdivision) {
  135. ShadowAtlas *shadow_atlas = shadow_atlas_owner.getornull(p_atlas);
  136. ERR_FAIL_COND(!shadow_atlas);
  137. ERR_FAIL_INDEX(p_quadrant, 4);
  138. ERR_FAIL_INDEX(p_subdivision, 16384);
  139. uint32_t subdiv = next_power_of_2(p_subdivision);
  140. if (subdiv & 0xaaaaaaaa) { //sqrt(subdiv) must be integer
  141. subdiv <<= 1;
  142. }
  143. subdiv = int(Math::sqrt((float)subdiv));
  144. //obtain the number that will be x*x
  145. if (shadow_atlas->quadrants[p_quadrant].subdivision == subdiv)
  146. return;
  147. //erase all data from quadrant
  148. for (int i = 0; i < shadow_atlas->quadrants[p_quadrant].shadows.size(); i++) {
  149. if (shadow_atlas->quadrants[p_quadrant].shadows[i].owner.is_valid()) {
  150. shadow_atlas->shadow_owners.erase(shadow_atlas->quadrants[p_quadrant].shadows[i].owner);
  151. LightInstance *li = light_instance_owner.getornull(shadow_atlas->quadrants[p_quadrant].shadows[i].owner);
  152. ERR_CONTINUE(!li);
  153. li->shadow_atlases.erase(p_atlas);
  154. }
  155. }
  156. shadow_atlas->quadrants[p_quadrant].shadows.resize(0);
  157. shadow_atlas->quadrants[p_quadrant].shadows.resize(subdiv * subdiv);
  158. shadow_atlas->quadrants[p_quadrant].subdivision = subdiv;
  159. //cache the smallest subdiv (for faster allocation in light update)
  160. shadow_atlas->smallest_subdiv = 1 << 30;
  161. for (int i = 0; i < 4; i++) {
  162. if (shadow_atlas->quadrants[i].subdivision) {
  163. shadow_atlas->smallest_subdiv = MIN(shadow_atlas->smallest_subdiv, shadow_atlas->quadrants[i].subdivision);
  164. }
  165. }
  166. if (shadow_atlas->smallest_subdiv == 1 << 30) {
  167. shadow_atlas->smallest_subdiv = 0;
  168. }
  169. //resort the size orders, simple bublesort for 4 elements..
  170. int swaps = 0;
  171. do {
  172. swaps = 0;
  173. for (int i = 0; i < 3; i++) {
  174. if (shadow_atlas->quadrants[shadow_atlas->size_order[i]].subdivision < shadow_atlas->quadrants[shadow_atlas->size_order[i + 1]].subdivision) {
  175. SWAP(shadow_atlas->size_order[i], shadow_atlas->size_order[i + 1]);
  176. swaps++;
  177. }
  178. }
  179. } while (swaps > 0);
  180. }
  181. bool RasterizerSceneGLES3::_shadow_atlas_find_shadow(ShadowAtlas *shadow_atlas, int *p_in_quadrants, int p_quadrant_count, int p_current_subdiv, uint64_t p_tick, int &r_quadrant, int &r_shadow) {
  182. for (int i = p_quadrant_count - 1; i >= 0; i--) {
  183. int qidx = p_in_quadrants[i];
  184. if (shadow_atlas->quadrants[qidx].subdivision == (uint32_t)p_current_subdiv) {
  185. return false;
  186. }
  187. //look for an empty space
  188. int sc = shadow_atlas->quadrants[qidx].shadows.size();
  189. ShadowAtlas::Quadrant::Shadow *sarr = shadow_atlas->quadrants[qidx].shadows.ptrw();
  190. int found_free_idx = -1; //found a free one
  191. int found_used_idx = -1; //found existing one, must steal it
  192. uint64_t min_pass = 0; // pass of the existing one, try to use the least recently used one (LRU fashion)
  193. for (int j = 0; j < sc; j++) {
  194. if (!sarr[j].owner.is_valid()) {
  195. found_free_idx = j;
  196. break;
  197. }
  198. LightInstance *sli = light_instance_owner.getornull(sarr[j].owner);
  199. ERR_CONTINUE(!sli);
  200. if (sli->last_scene_pass != scene_pass) {
  201. //was just allocated, don't kill it so soon, wait a bit..
  202. if (p_tick - sarr[j].alloc_tick < shadow_atlas_realloc_tolerance_msec)
  203. continue;
  204. if (found_used_idx == -1 || sli->last_scene_pass < min_pass) {
  205. found_used_idx = j;
  206. min_pass = sli->last_scene_pass;
  207. }
  208. }
  209. }
  210. if (found_free_idx == -1 && found_used_idx == -1)
  211. continue; //nothing found
  212. if (found_free_idx == -1 && found_used_idx != -1) {
  213. found_free_idx = found_used_idx;
  214. }
  215. r_quadrant = qidx;
  216. r_shadow = found_free_idx;
  217. return true;
  218. }
  219. return false;
  220. }
  221. bool RasterizerSceneGLES3::shadow_atlas_update_light(RID p_atlas, RID p_light_intance, float p_coverage, uint64_t p_light_version) {
  222. ShadowAtlas *shadow_atlas = shadow_atlas_owner.getornull(p_atlas);
  223. ERR_FAIL_COND_V(!shadow_atlas, false);
  224. LightInstance *li = light_instance_owner.getornull(p_light_intance);
  225. ERR_FAIL_COND_V(!li, false);
  226. if (shadow_atlas->size == 0 || shadow_atlas->smallest_subdiv == 0) {
  227. return false;
  228. }
  229. uint32_t quad_size = shadow_atlas->size >> 1;
  230. int desired_fit = MIN(quad_size / shadow_atlas->smallest_subdiv, next_power_of_2(quad_size * p_coverage));
  231. int valid_quadrants[4];
  232. int valid_quadrant_count = 0;
  233. int best_size = -1; //best size found
  234. int best_subdiv = -1; //subdiv for the best size
  235. //find the quadrants this fits into, and the best possible size it can fit into
  236. for (int i = 0; i < 4; i++) {
  237. int q = shadow_atlas->size_order[i];
  238. int sd = shadow_atlas->quadrants[q].subdivision;
  239. if (sd == 0)
  240. continue; //unused
  241. int max_fit = quad_size / sd;
  242. if (best_size != -1 && max_fit > best_size)
  243. break; //too large
  244. valid_quadrants[valid_quadrant_count++] = q;
  245. best_subdiv = sd;
  246. if (max_fit >= desired_fit) {
  247. best_size = max_fit;
  248. }
  249. }
  250. ERR_FAIL_COND_V(valid_quadrant_count == 0, false);
  251. uint64_t tick = OS::get_singleton()->get_ticks_msec();
  252. //see if it already exists
  253. if (shadow_atlas->shadow_owners.has(p_light_intance)) {
  254. //it does!
  255. uint32_t key = shadow_atlas->shadow_owners[p_light_intance];
  256. uint32_t q = (key >> ShadowAtlas::QUADRANT_SHIFT) & 0x3;
  257. uint32_t s = key & ShadowAtlas::SHADOW_INDEX_MASK;
  258. bool should_realloc = shadow_atlas->quadrants[q].subdivision != (uint32_t)best_subdiv && (shadow_atlas->quadrants[q].shadows[s].alloc_tick - tick > shadow_atlas_realloc_tolerance_msec);
  259. bool should_redraw = shadow_atlas->quadrants[q].shadows[s].version != p_light_version;
  260. if (!should_realloc) {
  261. shadow_atlas->quadrants[q].shadows.write[s].version = p_light_version;
  262. //already existing, see if it should redraw or it's just OK
  263. return should_redraw;
  264. }
  265. int new_quadrant, new_shadow;
  266. //find a better place
  267. if (_shadow_atlas_find_shadow(shadow_atlas, valid_quadrants, valid_quadrant_count, shadow_atlas->quadrants[q].subdivision, tick, new_quadrant, new_shadow)) {
  268. //found a better place!
  269. ShadowAtlas::Quadrant::Shadow *sh = &shadow_atlas->quadrants[new_quadrant].shadows.write[new_shadow];
  270. if (sh->owner.is_valid()) {
  271. //is taken, but is invalid, erasing it
  272. shadow_atlas->shadow_owners.erase(sh->owner);
  273. LightInstance *sli = light_instance_owner.get(sh->owner);
  274. sli->shadow_atlases.erase(p_atlas);
  275. }
  276. //erase previous
  277. shadow_atlas->quadrants[q].shadows.write[s].version = 0;
  278. shadow_atlas->quadrants[q].shadows.write[s].owner = RID();
  279. sh->owner = p_light_intance;
  280. sh->alloc_tick = tick;
  281. sh->version = p_light_version;
  282. li->shadow_atlases.insert(p_atlas);
  283. //make new key
  284. key = new_quadrant << ShadowAtlas::QUADRANT_SHIFT;
  285. key |= new_shadow;
  286. //update it in map
  287. shadow_atlas->shadow_owners[p_light_intance] = key;
  288. //make it dirty, as it should redraw anyway
  289. return true;
  290. }
  291. //no better place for this shadow found, keep current
  292. //already existing, see if it should redraw or it's just OK
  293. shadow_atlas->quadrants[q].shadows.write[s].version = p_light_version;
  294. return should_redraw;
  295. }
  296. int new_quadrant, new_shadow;
  297. //find a better place
  298. if (_shadow_atlas_find_shadow(shadow_atlas, valid_quadrants, valid_quadrant_count, -1, tick, new_quadrant, new_shadow)) {
  299. //found a better place!
  300. ShadowAtlas::Quadrant::Shadow *sh = &shadow_atlas->quadrants[new_quadrant].shadows.write[new_shadow];
  301. if (sh->owner.is_valid()) {
  302. //is taken, but is invalid, erasing it
  303. shadow_atlas->shadow_owners.erase(sh->owner);
  304. LightInstance *sli = light_instance_owner.get(sh->owner);
  305. sli->shadow_atlases.erase(p_atlas);
  306. }
  307. sh->owner = p_light_intance;
  308. sh->alloc_tick = tick;
  309. sh->version = p_light_version;
  310. li->shadow_atlases.insert(p_atlas);
  311. //make new key
  312. uint32_t key = new_quadrant << ShadowAtlas::QUADRANT_SHIFT;
  313. key |= new_shadow;
  314. //update it in map
  315. shadow_atlas->shadow_owners[p_light_intance] = key;
  316. //make it dirty, as it should redraw anyway
  317. return true;
  318. }
  319. //no place to allocate this light, apologies
  320. return false;
  321. }
  322. void RasterizerSceneGLES3::set_directional_shadow_count(int p_count) {
  323. directional_shadow.light_count = p_count;
  324. directional_shadow.current_light = 0;
  325. }
  326. int RasterizerSceneGLES3::get_directional_light_shadow_size(RID p_light_intance) {
  327. ERR_FAIL_COND_V(directional_shadow.light_count == 0, 0);
  328. int shadow_size;
  329. if (directional_shadow.light_count == 1) {
  330. shadow_size = directional_shadow.size;
  331. } else {
  332. shadow_size = directional_shadow.size / 2; //more than 4 not supported anyway
  333. }
  334. LightInstance *light_instance = light_instance_owner.getornull(p_light_intance);
  335. ERR_FAIL_COND_V(!light_instance, 0);
  336. switch (light_instance->light_ptr->directional_shadow_mode) {
  337. case VS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL:
  338. break; //none
  339. case VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS:
  340. case VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS: shadow_size /= 2; break;
  341. }
  342. return shadow_size;
  343. }
  344. //////////////////////////////////////////////////////
  345. RID RasterizerSceneGLES3::reflection_atlas_create() {
  346. ReflectionAtlas *reflection_atlas = memnew(ReflectionAtlas);
  347. reflection_atlas->subdiv = 0;
  348. reflection_atlas->color = 0;
  349. reflection_atlas->size = 0;
  350. for (int i = 0; i < 6; i++) {
  351. reflection_atlas->fbo[i] = 0;
  352. }
  353. return reflection_atlas_owner.make_rid(reflection_atlas);
  354. }
  355. void RasterizerSceneGLES3::reflection_atlas_set_size(RID p_ref_atlas, int p_size) {
  356. ReflectionAtlas *reflection_atlas = reflection_atlas_owner.getornull(p_ref_atlas);
  357. ERR_FAIL_COND(!reflection_atlas);
  358. int size = next_power_of_2(p_size);
  359. if (size == reflection_atlas->size)
  360. return;
  361. if (reflection_atlas->size) {
  362. for (int i = 0; i < 6; i++) {
  363. glDeleteFramebuffers(1, &reflection_atlas->fbo[i]);
  364. reflection_atlas->fbo[i] = 0;
  365. }
  366. glDeleteTextures(1, &reflection_atlas->color);
  367. reflection_atlas->color = 0;
  368. }
  369. reflection_atlas->size = size;
  370. for (int i = 0; i < reflection_atlas->reflections.size(); i++) {
  371. //erase probes reference to this
  372. if (reflection_atlas->reflections[i].owner.is_valid()) {
  373. ReflectionProbeInstance *reflection_probe_instance = reflection_probe_instance_owner.getornull(reflection_atlas->reflections[i].owner);
  374. reflection_atlas->reflections.write[i].owner = RID();
  375. ERR_CONTINUE(!reflection_probe_instance);
  376. reflection_probe_instance->reflection_atlas_index = -1;
  377. reflection_probe_instance->atlas = RID();
  378. reflection_probe_instance->render_step = -1;
  379. }
  380. }
  381. if (reflection_atlas->size) {
  382. bool use_float = true;
  383. GLenum internal_format = use_float ? GL_RGBA16F : GL_RGB10_A2;
  384. GLenum format = GL_RGBA;
  385. GLenum type = use_float ? GL_HALF_FLOAT : GL_UNSIGNED_INT_2_10_10_10_REV;
  386. // Create a texture for storing the color
  387. glActiveTexture(GL_TEXTURE0);
  388. glGenTextures(1, &reflection_atlas->color);
  389. glBindTexture(GL_TEXTURE_2D, reflection_atlas->color);
  390. int mmsize = reflection_atlas->size;
  391. glTexStorage2DCustom(GL_TEXTURE_2D, 6, internal_format, mmsize, mmsize, format, type);
  392. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
  393. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  394. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  395. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  396. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
  397. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 5);
  398. for (int i = 0; i < 6; i++) {
  399. glGenFramebuffers(1, &reflection_atlas->fbo[i]);
  400. glBindFramebuffer(GL_FRAMEBUFFER, reflection_atlas->fbo[i]);
  401. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, reflection_atlas->color, i);
  402. GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
  403. ERR_CONTINUE(status != GL_FRAMEBUFFER_COMPLETE);
  404. glDisable(GL_SCISSOR_TEST);
  405. glViewport(0, 0, mmsize, mmsize);
  406. glClearColor(0, 0, 0, 0);
  407. glClear(GL_COLOR_BUFFER_BIT); //it needs to be cleared, to avoid generating garbage
  408. mmsize >>= 1;
  409. }
  410. }
  411. }
  412. void RasterizerSceneGLES3::reflection_atlas_set_subdivision(RID p_ref_atlas, int p_subdiv) {
  413. ReflectionAtlas *reflection_atlas = reflection_atlas_owner.getornull(p_ref_atlas);
  414. ERR_FAIL_COND(!reflection_atlas);
  415. int subdiv = next_power_of_2(p_subdiv);
  416. if (subdiv & 0xaaaaaaaa) { //sqrt(subdiv) must be integer
  417. subdiv <<= 1;
  418. }
  419. subdiv = int(Math::sqrt((float)subdiv));
  420. if (reflection_atlas->subdiv == subdiv)
  421. return;
  422. if (subdiv) {
  423. for (int i = 0; i < reflection_atlas->reflections.size(); i++) {
  424. //erase probes reference to this
  425. if (reflection_atlas->reflections[i].owner.is_valid()) {
  426. ReflectionProbeInstance *reflection_probe_instance = reflection_probe_instance_owner.getornull(reflection_atlas->reflections[i].owner);
  427. reflection_atlas->reflections.write[i].owner = RID();
  428. ERR_CONTINUE(!reflection_probe_instance);
  429. reflection_probe_instance->reflection_atlas_index = -1;
  430. reflection_probe_instance->atlas = RID();
  431. reflection_probe_instance->render_step = -1;
  432. }
  433. }
  434. }
  435. reflection_atlas->subdiv = subdiv;
  436. reflection_atlas->reflections.resize(subdiv * subdiv);
  437. }
  438. ////////////////////////////////////////////////////
  439. RID RasterizerSceneGLES3::reflection_probe_instance_create(RID p_probe) {
  440. RasterizerStorageGLES3::ReflectionProbe *probe = storage->reflection_probe_owner.getornull(p_probe);
  441. ERR_FAIL_COND_V(!probe, RID());
  442. ReflectionProbeInstance *rpi = memnew(ReflectionProbeInstance);
  443. rpi->probe_ptr = probe;
  444. rpi->self = reflection_probe_instance_owner.make_rid(rpi);
  445. rpi->probe = p_probe;
  446. rpi->reflection_atlas_index = -1;
  447. rpi->render_step = -1;
  448. rpi->last_pass = 0;
  449. return rpi->self;
  450. }
  451. void RasterizerSceneGLES3::reflection_probe_instance_set_transform(RID p_instance, const Transform &p_transform) {
  452. ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance);
  453. ERR_FAIL_COND(!rpi);
  454. rpi->transform = p_transform;
  455. }
  456. void RasterizerSceneGLES3::reflection_probe_release_atlas_index(RID p_instance) {
  457. ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance);
  458. ERR_FAIL_COND(!rpi);
  459. if (rpi->reflection_atlas_index == -1)
  460. return;
  461. ReflectionAtlas *reflection_atlas = reflection_atlas_owner.getornull(rpi->atlas);
  462. ERR_FAIL_COND(!reflection_atlas);
  463. ERR_FAIL_INDEX(rpi->reflection_atlas_index, reflection_atlas->reflections.size());
  464. ERR_FAIL_COND(reflection_atlas->reflections[rpi->reflection_atlas_index].owner != rpi->self);
  465. reflection_atlas->reflections.write[rpi->reflection_atlas_index].owner = RID();
  466. rpi->reflection_atlas_index = -1;
  467. rpi->atlas = RID();
  468. rpi->render_step = -1;
  469. }
  470. bool RasterizerSceneGLES3::reflection_probe_instance_needs_redraw(RID p_instance) {
  471. ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance);
  472. ERR_FAIL_COND_V(!rpi, false);
  473. return rpi->reflection_atlas_index == -1 || rpi->probe_ptr->update_mode == VS::REFLECTION_PROBE_UPDATE_ALWAYS;
  474. }
  475. bool RasterizerSceneGLES3::reflection_probe_instance_has_reflection(RID p_instance) {
  476. ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance);
  477. ERR_FAIL_COND_V(!rpi, false);
  478. return rpi->reflection_atlas_index != -1;
  479. }
  480. bool RasterizerSceneGLES3::reflection_probe_instance_begin_render(RID p_instance, RID p_reflection_atlas) {
  481. ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance);
  482. ERR_FAIL_COND_V(!rpi, false);
  483. rpi->render_step = 0;
  484. if (rpi->reflection_atlas_index != -1) {
  485. return true; //got one already
  486. }
  487. ReflectionAtlas *reflection_atlas = reflection_atlas_owner.getornull(p_reflection_atlas);
  488. ERR_FAIL_COND_V(!reflection_atlas, false);
  489. if (reflection_atlas->size == 0 || reflection_atlas->subdiv == 0) {
  490. return false;
  491. }
  492. int best_free = -1;
  493. int best_used = -1;
  494. uint64_t best_used_frame = 0;
  495. for (int i = 0; i < reflection_atlas->reflections.size(); i++) {
  496. if (reflection_atlas->reflections[i].owner == RID()) {
  497. best_free = i;
  498. break;
  499. }
  500. if (rpi->render_step < 0 && reflection_atlas->reflections[i].last_frame < storage->frame.count &&
  501. (best_used == -1 || reflection_atlas->reflections[i].last_frame < best_used_frame)) {
  502. best_used = i;
  503. best_used_frame = reflection_atlas->reflections[i].last_frame;
  504. }
  505. }
  506. if (best_free == -1 && best_used == -1) {
  507. return false; // sorry, can not do. Try again next frame.
  508. }
  509. if (best_free == -1) {
  510. //find best from what is used
  511. best_free = best_used;
  512. ReflectionProbeInstance *victim_rpi = reflection_probe_instance_owner.getornull(reflection_atlas->reflections[best_free].owner);
  513. ERR_FAIL_COND_V(!victim_rpi, false);
  514. victim_rpi->atlas = RID();
  515. victim_rpi->reflection_atlas_index = -1;
  516. }
  517. reflection_atlas->reflections.write[best_free].owner = p_instance;
  518. reflection_atlas->reflections.write[best_free].last_frame = storage->frame.count;
  519. rpi->reflection_atlas_index = best_free;
  520. rpi->atlas = p_reflection_atlas;
  521. rpi->render_step = 0;
  522. return true;
  523. }
  524. bool RasterizerSceneGLES3::reflection_probe_instance_postprocess_step(RID p_instance) {
  525. ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance);
  526. ERR_FAIL_COND_V(!rpi, true);
  527. ReflectionAtlas *reflection_atlas = reflection_atlas_owner.getornull(rpi->atlas);
  528. ERR_FAIL_COND_V(!reflection_atlas, false);
  529. ERR_FAIL_COND_V(rpi->render_step >= 6, true);
  530. glBindFramebuffer(GL_FRAMEBUFFER, reflection_atlas->fbo[rpi->render_step]);
  531. state.cube_to_dp_shader.bind();
  532. int target_size = reflection_atlas->size / reflection_atlas->subdiv;
  533. int cubemap_index = reflection_cubemaps.size() - 1;
  534. for (int i = reflection_cubemaps.size() - 1; i >= 0; i--) {
  535. //find appropriate cubemap to render to
  536. if (reflection_cubemaps[i].size > target_size * 2)
  537. break;
  538. cubemap_index = i;
  539. }
  540. glDisable(GL_BLEND);
  541. glActiveTexture(GL_TEXTURE0);
  542. glBindTexture(GL_TEXTURE_CUBE_MAP, reflection_cubemaps[cubemap_index].cubemap);
  543. glDisable(GL_CULL_FACE);
  544. storage->shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::USE_DUAL_PARABOLOID, true);
  545. storage->shaders.cubemap_filter.bind();
  546. int cell_size = reflection_atlas->size / reflection_atlas->subdiv;
  547. for (int i = 0; i < rpi->render_step; i++) {
  548. cell_size >>= 1; //mipmaps!
  549. }
  550. int x = (rpi->reflection_atlas_index % reflection_atlas->subdiv) * cell_size;
  551. int y = (rpi->reflection_atlas_index / reflection_atlas->subdiv) * cell_size;
  552. int width = cell_size;
  553. int height = cell_size;
  554. storage->shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::USE_DIRECT_WRITE, rpi->render_step == 0);
  555. storage->shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::LOW_QUALITY, rpi->probe_ptr->update_mode == VS::REFLECTION_PROBE_UPDATE_ALWAYS);
  556. for (int i = 0; i < 2; i++) {
  557. storage->shaders.cubemap_filter.set_uniform(CubemapFilterShaderGLES3::Z_FLIP, i == 0);
  558. storage->shaders.cubemap_filter.set_uniform(CubemapFilterShaderGLES3::ROUGHNESS, rpi->render_step / 5.0);
  559. uint32_t local_width = width, local_height = height;
  560. uint32_t local_x = x, local_y = y;
  561. local_height /= 2;
  562. local_y += i * local_height;
  563. glViewport(local_x, local_y, local_width, local_height);
  564. _copy_screen();
  565. }
  566. storage->shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::USE_DIRECT_WRITE, false);
  567. storage->shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::LOW_QUALITY, false);
  568. rpi->render_step++;
  569. return rpi->render_step == 6;
  570. }
  571. /* ENVIRONMENT API */
  572. RID RasterizerSceneGLES3::environment_create() {
  573. Environment *env = memnew(Environment);
  574. return environment_owner.make_rid(env);
  575. }
  576. void RasterizerSceneGLES3::environment_set_background(RID p_env, VS::EnvironmentBG p_bg) {
  577. Environment *env = environment_owner.getornull(p_env);
  578. ERR_FAIL_COND(!env);
  579. env->bg_mode = p_bg;
  580. }
  581. void RasterizerSceneGLES3::environment_set_sky(RID p_env, RID p_sky) {
  582. Environment *env = environment_owner.getornull(p_env);
  583. ERR_FAIL_COND(!env);
  584. env->sky = p_sky;
  585. }
  586. void RasterizerSceneGLES3::environment_set_sky_custom_fov(RID p_env, float p_scale) {
  587. Environment *env = environment_owner.getornull(p_env);
  588. ERR_FAIL_COND(!env);
  589. env->sky_custom_fov = p_scale;
  590. }
  591. void RasterizerSceneGLES3::environment_set_sky_orientation(RID p_env, const Basis &p_orientation) {
  592. Environment *env = environment_owner.getornull(p_env);
  593. ERR_FAIL_COND(!env);
  594. env->sky_orientation = p_orientation;
  595. }
  596. void RasterizerSceneGLES3::environment_set_bg_color(RID p_env, const Color &p_color) {
  597. Environment *env = environment_owner.getornull(p_env);
  598. ERR_FAIL_COND(!env);
  599. env->bg_color = p_color;
  600. }
  601. void RasterizerSceneGLES3::environment_set_bg_energy(RID p_env, float p_energy) {
  602. Environment *env = environment_owner.getornull(p_env);
  603. ERR_FAIL_COND(!env);
  604. env->bg_energy = p_energy;
  605. }
  606. void RasterizerSceneGLES3::environment_set_canvas_max_layer(RID p_env, int p_max_layer) {
  607. Environment *env = environment_owner.getornull(p_env);
  608. ERR_FAIL_COND(!env);
  609. env->canvas_max_layer = p_max_layer;
  610. }
  611. void RasterizerSceneGLES3::environment_set_ambient_light(RID p_env, const Color &p_color, float p_energy, float p_sky_contribution) {
  612. Environment *env = environment_owner.getornull(p_env);
  613. ERR_FAIL_COND(!env);
  614. env->ambient_color = p_color;
  615. env->ambient_energy = p_energy;
  616. env->ambient_sky_contribution = p_sky_contribution;
  617. }
  618. void RasterizerSceneGLES3::environment_set_camera_feed_id(RID p_env, int p_camera_feed_id) {
  619. Environment *env = environment_owner.getornull(p_env);
  620. ERR_FAIL_COND(!env);
  621. env->camera_feed_id = p_camera_feed_id;
  622. }
  623. void RasterizerSceneGLES3::environment_set_dof_blur_far(RID p_env, bool p_enable, float p_distance, float p_transition, float p_amount, VS::EnvironmentDOFBlurQuality p_quality) {
  624. Environment *env = environment_owner.getornull(p_env);
  625. ERR_FAIL_COND(!env);
  626. env->dof_blur_far_enabled = p_enable;
  627. env->dof_blur_far_distance = p_distance;
  628. env->dof_blur_far_transition = p_transition;
  629. env->dof_blur_far_amount = p_amount;
  630. env->dof_blur_far_quality = p_quality;
  631. }
  632. void RasterizerSceneGLES3::environment_set_dof_blur_near(RID p_env, bool p_enable, float p_distance, float p_transition, float p_amount, VS::EnvironmentDOFBlurQuality p_quality) {
  633. Environment *env = environment_owner.getornull(p_env);
  634. ERR_FAIL_COND(!env);
  635. env->dof_blur_near_enabled = p_enable;
  636. env->dof_blur_near_distance = p_distance;
  637. env->dof_blur_near_transition = p_transition;
  638. env->dof_blur_near_amount = p_amount;
  639. env->dof_blur_near_quality = p_quality;
  640. }
  641. void RasterizerSceneGLES3::environment_set_glow(RID p_env, bool p_enable, int p_level_flags, float p_intensity, float p_strength, float p_bloom_threshold, VS::EnvironmentGlowBlendMode p_blend_mode, float p_hdr_bleed_threshold, float p_hdr_bleed_scale, float p_hdr_luminance_cap, bool p_bicubic_upscale) {
  642. Environment *env = environment_owner.getornull(p_env);
  643. ERR_FAIL_COND(!env);
  644. env->glow_enabled = p_enable;
  645. env->glow_levels = p_level_flags;
  646. env->glow_intensity = p_intensity;
  647. env->glow_strength = p_strength;
  648. env->glow_bloom = p_bloom_threshold;
  649. env->glow_blend_mode = p_blend_mode;
  650. env->glow_hdr_bleed_threshold = p_hdr_bleed_threshold;
  651. env->glow_hdr_bleed_scale = p_hdr_bleed_scale;
  652. env->glow_hdr_luminance_cap = p_hdr_luminance_cap;
  653. env->glow_bicubic_upscale = p_bicubic_upscale;
  654. }
  655. void RasterizerSceneGLES3::environment_set_fog(RID p_env, bool p_enable, float p_begin, float p_end, RID p_gradient_texture) {
  656. }
  657. void RasterizerSceneGLES3::environment_set_ssr(RID p_env, bool p_enable, int p_max_steps, float p_fade_in, float p_fade_out, float p_depth_tolerance, bool p_roughness) {
  658. Environment *env = environment_owner.getornull(p_env);
  659. ERR_FAIL_COND(!env);
  660. env->ssr_enabled = p_enable;
  661. env->ssr_max_steps = p_max_steps;
  662. env->ssr_fade_in = p_fade_in;
  663. env->ssr_fade_out = p_fade_out;
  664. env->ssr_depth_tolerance = p_depth_tolerance;
  665. env->ssr_roughness = p_roughness;
  666. }
  667. void RasterizerSceneGLES3::environment_set_ssao(RID p_env, bool p_enable, float p_radius, float p_intensity, float p_radius2, float p_intensity2, float p_bias, float p_light_affect, float p_ao_channel_affect, const Color &p_color, VS::EnvironmentSSAOQuality p_quality, VisualServer::EnvironmentSSAOBlur p_blur, float p_bilateral_sharpness) {
  668. Environment *env = environment_owner.getornull(p_env);
  669. ERR_FAIL_COND(!env);
  670. env->ssao_enabled = p_enable;
  671. env->ssao_radius = p_radius;
  672. env->ssao_intensity = p_intensity;
  673. env->ssao_radius2 = p_radius2;
  674. env->ssao_intensity2 = p_intensity2;
  675. env->ssao_bias = p_bias;
  676. env->ssao_light_affect = p_light_affect;
  677. env->ssao_ao_channel_affect = p_ao_channel_affect;
  678. env->ssao_color = p_color;
  679. env->ssao_filter = p_blur;
  680. env->ssao_quality = p_quality;
  681. env->ssao_bilateral_sharpness = p_bilateral_sharpness;
  682. }
  683. void RasterizerSceneGLES3::environment_set_tonemap(RID p_env, VS::EnvironmentToneMapper p_tone_mapper, float p_exposure, float p_white, bool p_auto_exposure, float p_min_luminance, float p_max_luminance, float p_auto_exp_speed, float p_auto_exp_scale) {
  684. Environment *env = environment_owner.getornull(p_env);
  685. ERR_FAIL_COND(!env);
  686. env->tone_mapper = p_tone_mapper;
  687. env->tone_mapper_exposure = p_exposure;
  688. env->tone_mapper_exposure_white = p_white;
  689. env->auto_exposure = p_auto_exposure;
  690. env->auto_exposure_speed = p_auto_exp_speed;
  691. env->auto_exposure_min = p_min_luminance;
  692. env->auto_exposure_max = p_max_luminance;
  693. env->auto_exposure_grey = p_auto_exp_scale;
  694. }
  695. void RasterizerSceneGLES3::environment_set_adjustment(RID p_env, bool p_enable, float p_brightness, float p_contrast, float p_saturation, RID p_ramp) {
  696. Environment *env = environment_owner.getornull(p_env);
  697. ERR_FAIL_COND(!env);
  698. env->adjustments_enabled = p_enable;
  699. env->adjustments_brightness = p_brightness;
  700. env->adjustments_contrast = p_contrast;
  701. env->adjustments_saturation = p_saturation;
  702. env->color_correction = p_ramp;
  703. }
  704. void RasterizerSceneGLES3::environment_set_fog(RID p_env, bool p_enable, const Color &p_color, const Color &p_sun_color, float p_sun_amount) {
  705. Environment *env = environment_owner.getornull(p_env);
  706. ERR_FAIL_COND(!env);
  707. env->fog_enabled = p_enable;
  708. env->fog_color = p_color;
  709. env->fog_sun_color = p_sun_color;
  710. env->fog_sun_amount = p_sun_amount;
  711. }
  712. void RasterizerSceneGLES3::environment_set_fog_depth(RID p_env, bool p_enable, float p_depth_begin, float p_depth_end, float p_depth_curve, bool p_transmit, float p_transmit_curve) {
  713. Environment *env = environment_owner.getornull(p_env);
  714. ERR_FAIL_COND(!env);
  715. env->fog_depth_enabled = p_enable;
  716. env->fog_depth_begin = p_depth_begin;
  717. env->fog_depth_end = p_depth_end;
  718. env->fog_depth_curve = p_depth_curve;
  719. env->fog_transmit_enabled = p_transmit;
  720. env->fog_transmit_curve = p_transmit_curve;
  721. }
  722. void RasterizerSceneGLES3::environment_set_fog_height(RID p_env, bool p_enable, float p_min_height, float p_max_height, float p_height_curve) {
  723. Environment *env = environment_owner.getornull(p_env);
  724. ERR_FAIL_COND(!env);
  725. env->fog_height_enabled = p_enable;
  726. env->fog_height_min = p_min_height;
  727. env->fog_height_max = p_max_height;
  728. env->fog_height_curve = p_height_curve;
  729. }
  730. bool RasterizerSceneGLES3::is_environment(RID p_env) {
  731. return environment_owner.owns(p_env);
  732. }
  733. VS::EnvironmentBG RasterizerSceneGLES3::environment_get_background(RID p_env) {
  734. const Environment *env = environment_owner.getornull(p_env);
  735. ERR_FAIL_COND_V(!env, VS::ENV_BG_MAX);
  736. return env->bg_mode;
  737. }
  738. int RasterizerSceneGLES3::environment_get_canvas_max_layer(RID p_env) {
  739. const Environment *env = environment_owner.getornull(p_env);
  740. ERR_FAIL_COND_V(!env, -1);
  741. return env->canvas_max_layer;
  742. }
  743. RID RasterizerSceneGLES3::light_instance_create(RID p_light) {
  744. LightInstance *light_instance = memnew(LightInstance);
  745. light_instance->last_pass = 0;
  746. light_instance->last_scene_pass = 0;
  747. light_instance->last_scene_shadow_pass = 0;
  748. light_instance->light = p_light;
  749. light_instance->light_ptr = storage->light_owner.getornull(p_light);
  750. if (!light_instance->light_ptr) {
  751. memdelete(light_instance);
  752. ERR_FAIL_V_MSG(RID(), "Condition ' !light_instance->light_ptr ' is true.");
  753. }
  754. light_instance->self = light_instance_owner.make_rid(light_instance);
  755. return light_instance->self;
  756. }
  757. void RasterizerSceneGLES3::light_instance_set_transform(RID p_light_instance, const Transform &p_transform) {
  758. LightInstance *light_instance = light_instance_owner.getornull(p_light_instance);
  759. ERR_FAIL_COND(!light_instance);
  760. light_instance->transform = p_transform;
  761. }
  762. void RasterizerSceneGLES3::light_instance_set_shadow_transform(RID p_light_instance, const CameraMatrix &p_projection, const Transform &p_transform, float p_far, float p_split, int p_pass, float p_bias_scale) {
  763. LightInstance *light_instance = light_instance_owner.getornull(p_light_instance);
  764. ERR_FAIL_COND(!light_instance);
  765. if (light_instance->light_ptr->type != VS::LIGHT_DIRECTIONAL) {
  766. p_pass = 0;
  767. }
  768. ERR_FAIL_INDEX(p_pass, 4);
  769. light_instance->shadow_transform[p_pass].camera = p_projection;
  770. light_instance->shadow_transform[p_pass].transform = p_transform;
  771. light_instance->shadow_transform[p_pass].farplane = p_far;
  772. light_instance->shadow_transform[p_pass].split = p_split;
  773. light_instance->shadow_transform[p_pass].bias_scale = p_bias_scale;
  774. }
  775. void RasterizerSceneGLES3::light_instance_mark_visible(RID p_light_instance) {
  776. LightInstance *light_instance = light_instance_owner.getornull(p_light_instance);
  777. ERR_FAIL_COND(!light_instance);
  778. light_instance->last_scene_pass = scene_pass;
  779. }
  780. //////////////////////
  781. RID RasterizerSceneGLES3::gi_probe_instance_create() {
  782. GIProbeInstance *gipi = memnew(GIProbeInstance);
  783. return gi_probe_instance_owner.make_rid(gipi);
  784. }
  785. void RasterizerSceneGLES3::gi_probe_instance_set_light_data(RID p_probe, RID p_base, RID p_data) {
  786. GIProbeInstance *gipi = gi_probe_instance_owner.getornull(p_probe);
  787. ERR_FAIL_COND(!gipi);
  788. gipi->data = p_data;
  789. gipi->probe = storage->gi_probe_owner.getornull(p_base);
  790. if (p_data.is_valid()) {
  791. RasterizerStorageGLES3::GIProbeData *gipd = storage->gi_probe_data_owner.getornull(p_data);
  792. ERR_FAIL_COND(!gipd);
  793. gipi->tex_cache = gipd->tex_id;
  794. gipi->cell_size_cache.x = 1.0 / gipd->width;
  795. gipi->cell_size_cache.y = 1.0 / gipd->height;
  796. gipi->cell_size_cache.z = 1.0 / gipd->depth;
  797. }
  798. }
  799. void RasterizerSceneGLES3::gi_probe_instance_set_transform_to_data(RID p_probe, const Transform &p_xform) {
  800. GIProbeInstance *gipi = gi_probe_instance_owner.getornull(p_probe);
  801. ERR_FAIL_COND(!gipi);
  802. gipi->transform_to_data = p_xform;
  803. }
  804. void RasterizerSceneGLES3::gi_probe_instance_set_bounds(RID p_probe, const Vector3 &p_bounds) {
  805. GIProbeInstance *gipi = gi_probe_instance_owner.getornull(p_probe);
  806. ERR_FAIL_COND(!gipi);
  807. gipi->bounds = p_bounds;
  808. }
  809. ////////////////////////////
  810. ////////////////////////////
  811. ////////////////////////////
  812. bool RasterizerSceneGLES3::_setup_material(RasterizerStorageGLES3::Material *p_material, bool p_depth_pass, bool p_alpha_pass) {
  813. /* this is handled outside
  814. if (p_material->shader->spatial.cull_mode == RasterizerStorageGLES3::Shader::Spatial::CULL_MODE_DISABLED) {
  815. glDisable(GL_CULL_FACE);
  816. } else {
  817. glEnable(GL_CULL_FACE);
  818. } */
  819. if (state.current_line_width != p_material->line_width) {
  820. //glLineWidth(MAX(p_material->line_width,1.0));
  821. state.current_line_width = p_material->line_width;
  822. }
  823. if (state.current_depth_test != (!p_material->shader->spatial.no_depth_test)) {
  824. if (p_material->shader->spatial.no_depth_test) {
  825. glDisable(GL_DEPTH_TEST);
  826. } else {
  827. glEnable(GL_DEPTH_TEST);
  828. }
  829. state.current_depth_test = !p_material->shader->spatial.no_depth_test;
  830. }
  831. if (state.current_depth_draw != p_material->shader->spatial.depth_draw_mode) {
  832. switch (p_material->shader->spatial.depth_draw_mode) {
  833. case RasterizerStorageGLES3::Shader::Spatial::DEPTH_DRAW_ALPHA_PREPASS: {
  834. glDepthMask(p_depth_pass);
  835. // If some transparent objects write to depth, we need to re-copy depth texture when we need it
  836. if (p_alpha_pass && !state.used_depth_prepass) {
  837. state.prepared_depth_texture = false;
  838. }
  839. } break;
  840. case RasterizerStorageGLES3::Shader::Spatial::DEPTH_DRAW_OPAQUE: {
  841. glDepthMask(!p_alpha_pass);
  842. } break;
  843. case RasterizerStorageGLES3::Shader::Spatial::DEPTH_DRAW_ALWAYS: {
  844. glDepthMask(GL_TRUE);
  845. // If some transparent objects write to depth, we need to re-copy depth texture when we need it
  846. if (p_alpha_pass) {
  847. state.prepared_depth_texture = false;
  848. }
  849. } break;
  850. case RasterizerStorageGLES3::Shader::Spatial::DEPTH_DRAW_NEVER: {
  851. glDepthMask(GL_FALSE);
  852. } break;
  853. }
  854. state.current_depth_draw = p_material->shader->spatial.depth_draw_mode;
  855. }
  856. //material parameters
  857. state.scene_shader.set_custom_shader(p_material->shader->custom_code_id);
  858. bool rebind = state.scene_shader.bind();
  859. if (p_material->ubo_id) {
  860. glBindBufferBase(GL_UNIFORM_BUFFER, 1, p_material->ubo_id);
  861. }
  862. int tc = p_material->textures.size();
  863. RID *textures = p_material->textures.ptrw();
  864. ShaderLanguage::ShaderNode::Uniform::Hint *texture_hints = p_material->shader->texture_hints.ptrw();
  865. const ShaderLanguage::DataType *texture_types = p_material->shader->texture_types.ptr();
  866. state.current_main_tex = 0;
  867. for (int i = 0; i < tc; i++) {
  868. glActiveTexture(GL_TEXTURE0 + i);
  869. GLenum target = GL_TEXTURE_2D;
  870. GLuint tex = 0;
  871. RasterizerStorageGLES3::Texture *t = storage->texture_owner.getptr(textures[i]);
  872. if (t) {
  873. if (t->redraw_if_visible) { //must check before proxy because this is often used with proxies
  874. VisualServerRaster::redraw_request();
  875. }
  876. t = t->get_ptr(); //resolve for proxies
  877. #ifdef TOOLS_ENABLED
  878. if (t->detect_3d) {
  879. t->detect_3d(t->detect_3d_ud);
  880. }
  881. #endif
  882. #ifdef TOOLS_ENABLED
  883. if (t->detect_normal && texture_hints[i] == ShaderLanguage::ShaderNode::Uniform::HINT_NORMAL) {
  884. t->detect_normal(t->detect_normal_ud);
  885. }
  886. #endif
  887. if (t->render_target)
  888. t->render_target->used_in_frame = true;
  889. target = t->target;
  890. tex = t->tex_id;
  891. } else {
  892. switch (texture_types[i]) {
  893. case ShaderLanguage::TYPE_ISAMPLER2D:
  894. case ShaderLanguage::TYPE_USAMPLER2D:
  895. case ShaderLanguage::TYPE_SAMPLER2D: {
  896. target = GL_TEXTURE_2D;
  897. switch (texture_hints[i]) {
  898. case ShaderLanguage::ShaderNode::Uniform::HINT_BLACK_ALBEDO:
  899. case ShaderLanguage::ShaderNode::Uniform::HINT_BLACK: {
  900. tex = storage->resources.black_tex;
  901. } break;
  902. case ShaderLanguage::ShaderNode::Uniform::HINT_ANISO: {
  903. tex = storage->resources.aniso_tex;
  904. } break;
  905. case ShaderLanguage::ShaderNode::Uniform::HINT_NORMAL: {
  906. tex = storage->resources.normal_tex;
  907. } break;
  908. default: {
  909. tex = storage->resources.white_tex;
  910. } break;
  911. }
  912. } break;
  913. case ShaderLanguage::TYPE_SAMPLERCUBE: {
  914. // TODO
  915. } break;
  916. case ShaderLanguage::TYPE_ISAMPLER3D:
  917. case ShaderLanguage::TYPE_USAMPLER3D:
  918. case ShaderLanguage::TYPE_SAMPLER3D: {
  919. target = GL_TEXTURE_3D;
  920. tex = storage->resources.white_tex_3d;
  921. //switch (texture_hints[i]) {
  922. // TODO
  923. //}
  924. } break;
  925. case ShaderLanguage::TYPE_ISAMPLER2DARRAY:
  926. case ShaderLanguage::TYPE_USAMPLER2DARRAY:
  927. case ShaderLanguage::TYPE_SAMPLER2DARRAY: {
  928. target = GL_TEXTURE_2D_ARRAY;
  929. tex = storage->resources.white_tex_array;
  930. //switch (texture_hints[i]) {
  931. // TODO
  932. //}
  933. } break;
  934. default: {
  935. }
  936. }
  937. }
  938. glBindTexture(target, tex);
  939. if (t && storage->config.srgb_decode_supported) {
  940. //if SRGB decode extension is present, simply switch the texture to whathever is needed
  941. bool must_srgb = false;
  942. if (t->srgb && (texture_hints[i] == ShaderLanguage::ShaderNode::Uniform::HINT_ALBEDO || texture_hints[i] == ShaderLanguage::ShaderNode::Uniform::HINT_BLACK_ALBEDO)) {
  943. must_srgb = true;
  944. }
  945. if (t->using_srgb != must_srgb) {
  946. if (must_srgb) {
  947. glTexParameteri(t->target, _TEXTURE_SRGB_DECODE_EXT, _DECODE_EXT);
  948. #ifdef TOOLS_ENABLED
  949. if (t->detect_srgb) {
  950. t->detect_srgb(t->detect_srgb_ud);
  951. }
  952. #endif
  953. } else {
  954. glTexParameteri(t->target, _TEXTURE_SRGB_DECODE_EXT, _SKIP_DECODE_EXT);
  955. }
  956. t->using_srgb = must_srgb;
  957. }
  958. }
  959. if (i == 0) {
  960. state.current_main_tex = tex;
  961. }
  962. }
  963. return rebind;
  964. }
  965. struct RasterizerGLES3Particle {
  966. float color[4];
  967. float velocity_active[4];
  968. float custom[4];
  969. float xform_1[4];
  970. float xform_2[4];
  971. float xform_3[4];
  972. };
  973. struct RasterizerGLES3ParticleSort {
  974. Vector3 z_dir;
  975. bool operator()(const RasterizerGLES3Particle &p_a, const RasterizerGLES3Particle &p_b) const {
  976. return z_dir.dot(Vector3(p_a.xform_1[3], p_a.xform_2[3], p_a.xform_3[3])) < z_dir.dot(Vector3(p_b.xform_1[3], p_b.xform_2[3], p_b.xform_3[3]));
  977. }
  978. };
  979. void RasterizerSceneGLES3::_setup_geometry(RenderList::Element *e, const Transform &p_view_transform) {
  980. switch (e->instance->base_type) {
  981. case VS::INSTANCE_MESH: {
  982. RasterizerStorageGLES3::Surface *s = static_cast<RasterizerStorageGLES3::Surface *>(e->geometry);
  983. if (s->blend_shapes.size() && e->instance->blend_values.size()) {
  984. //blend shapes, use transform feedback
  985. storage->mesh_render_blend_shapes(s, e->instance->blend_values.ptr());
  986. //rebind shader
  987. state.scene_shader.bind();
  988. #ifdef DEBUG_ENABLED
  989. } else if (state.debug_draw == VS::VIEWPORT_DEBUG_DRAW_WIREFRAME && s->array_wireframe_id) {
  990. glBindVertexArray(s->array_wireframe_id); // everything is so easy nowadays
  991. #endif
  992. } else {
  993. glBindVertexArray(s->array_id); // everything is so easy nowadays
  994. }
  995. } break;
  996. case VS::INSTANCE_MULTIMESH: {
  997. RasterizerStorageGLES3::MultiMesh *multi_mesh = static_cast<RasterizerStorageGLES3::MultiMesh *>(e->owner);
  998. RasterizerStorageGLES3::Surface *s = static_cast<RasterizerStorageGLES3::Surface *>(e->geometry);
  999. #ifdef DEBUG_ENABLED
  1000. if (state.debug_draw == VS::VIEWPORT_DEBUG_DRAW_WIREFRAME && s->instancing_array_wireframe_id) {
  1001. glBindVertexArray(s->instancing_array_wireframe_id); // use the instancing array ID
  1002. } else
  1003. #endif
  1004. {
  1005. glBindVertexArray(s->instancing_array_id); // use the instancing array ID
  1006. }
  1007. glBindBuffer(GL_ARRAY_BUFFER, multi_mesh->buffer); //modify the buffer
  1008. int stride = (multi_mesh->xform_floats + multi_mesh->color_floats + multi_mesh->custom_data_floats) * 4;
  1009. glEnableVertexAttribArray(8);
  1010. glVertexAttribPointer(8, 4, GL_FLOAT, GL_FALSE, stride, NULL);
  1011. glVertexAttribDivisor(8, 1);
  1012. glEnableVertexAttribArray(9);
  1013. glVertexAttribPointer(9, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(4 * 4));
  1014. glVertexAttribDivisor(9, 1);
  1015. int color_ofs;
  1016. if (multi_mesh->transform_format == VS::MULTIMESH_TRANSFORM_3D) {
  1017. glEnableVertexAttribArray(10);
  1018. glVertexAttribPointer(10, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(8 * 4));
  1019. glVertexAttribDivisor(10, 1);
  1020. color_ofs = 12 * 4;
  1021. } else {
  1022. glDisableVertexAttribArray(10);
  1023. glVertexAttrib4f(10, 0, 0, 1, 0);
  1024. color_ofs = 8 * 4;
  1025. }
  1026. int custom_data_ofs = color_ofs;
  1027. switch (multi_mesh->color_format) {
  1028. case VS::MULTIMESH_COLOR_MAX:
  1029. case VS::MULTIMESH_COLOR_NONE: {
  1030. glDisableVertexAttribArray(11);
  1031. glVertexAttrib4f(11, 1, 1, 1, 1);
  1032. } break;
  1033. case VS::MULTIMESH_COLOR_8BIT: {
  1034. glEnableVertexAttribArray(11);
  1035. glVertexAttribPointer(11, 4, GL_UNSIGNED_BYTE, GL_TRUE, stride, CAST_INT_TO_UCHAR_PTR(color_ofs));
  1036. glVertexAttribDivisor(11, 1);
  1037. custom_data_ofs += 4;
  1038. } break;
  1039. case VS::MULTIMESH_COLOR_FLOAT: {
  1040. glEnableVertexAttribArray(11);
  1041. glVertexAttribPointer(11, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(color_ofs));
  1042. glVertexAttribDivisor(11, 1);
  1043. custom_data_ofs += 4 * 4;
  1044. } break;
  1045. }
  1046. switch (multi_mesh->custom_data_format) {
  1047. case VS::MULTIMESH_CUSTOM_DATA_MAX:
  1048. case VS::MULTIMESH_CUSTOM_DATA_NONE: {
  1049. glDisableVertexAttribArray(12);
  1050. glVertexAttrib4f(12, 1, 1, 1, 1);
  1051. } break;
  1052. case VS::MULTIMESH_CUSTOM_DATA_8BIT: {
  1053. glEnableVertexAttribArray(12);
  1054. glVertexAttribPointer(12, 4, GL_UNSIGNED_BYTE, GL_TRUE, stride, CAST_INT_TO_UCHAR_PTR(custom_data_ofs));
  1055. glVertexAttribDivisor(12, 1);
  1056. } break;
  1057. case VS::MULTIMESH_CUSTOM_DATA_FLOAT: {
  1058. glEnableVertexAttribArray(12);
  1059. glVertexAttribPointer(12, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(custom_data_ofs));
  1060. glVertexAttribDivisor(12, 1);
  1061. } break;
  1062. }
  1063. } break;
  1064. case VS::INSTANCE_PARTICLES: {
  1065. RasterizerStorageGLES3::Particles *particles = static_cast<RasterizerStorageGLES3::Particles *>(e->owner);
  1066. RasterizerStorageGLES3::Surface *s = static_cast<RasterizerStorageGLES3::Surface *>(e->geometry);
  1067. if (particles->draw_order == VS::PARTICLES_DRAW_ORDER_VIEW_DEPTH && particles->particle_valid_histories[1]) {
  1068. glBindBuffer(GL_ARRAY_BUFFER, particles->particle_buffer_histories[1]); //modify the buffer, this was used 2 frames ago so it should be good enough for flushing
  1069. RasterizerGLES3Particle *particle_array;
  1070. #ifndef __EMSCRIPTEN__
  1071. particle_array = static_cast<RasterizerGLES3Particle *>(glMapBufferRange(GL_ARRAY_BUFFER, 0, particles->amount * 24 * sizeof(float), GL_MAP_READ_BIT | GL_MAP_WRITE_BIT));
  1072. #else
  1073. PoolVector<RasterizerGLES3Particle> particle_vector;
  1074. particle_vector.resize(particles->amount);
  1075. PoolVector<RasterizerGLES3Particle>::Write particle_writer = particle_vector.write();
  1076. particle_array = particle_writer.ptr();
  1077. glGetBufferSubData(GL_ARRAY_BUFFER, 0, particles->amount * sizeof(RasterizerGLES3Particle), particle_array);
  1078. #endif
  1079. SortArray<RasterizerGLES3Particle, RasterizerGLES3ParticleSort> sorter;
  1080. if (particles->use_local_coords) {
  1081. sorter.compare.z_dir = e->instance->transform.affine_inverse().xform(p_view_transform.basis.get_axis(2)).normalized();
  1082. } else {
  1083. sorter.compare.z_dir = p_view_transform.basis.get_axis(2).normalized();
  1084. }
  1085. sorter.sort(particle_array, particles->amount);
  1086. #ifndef __EMSCRIPTEN__
  1087. glUnmapBuffer(GL_ARRAY_BUFFER);
  1088. #else
  1089. particle_writer.release();
  1090. particle_array = NULL;
  1091. {
  1092. PoolVector<RasterizerGLES3Particle>::Read r = particle_vector.read();
  1093. glBufferSubData(GL_ARRAY_BUFFER, 0, particles->amount * sizeof(RasterizerGLES3Particle), r.ptr());
  1094. }
  1095. particle_vector = PoolVector<RasterizerGLES3Particle>();
  1096. #endif
  1097. #ifdef DEBUG_ENABLED
  1098. if (state.debug_draw == VS::VIEWPORT_DEBUG_DRAW_WIREFRAME && s->instancing_array_wireframe_id) {
  1099. glBindVertexArray(s->instancing_array_wireframe_id); // use the wireframe instancing array ID
  1100. } else
  1101. #endif
  1102. {
  1103. glBindVertexArray(s->instancing_array_id); // use the instancing array ID
  1104. }
  1105. glBindBuffer(GL_ARRAY_BUFFER, particles->particle_buffer_histories[1]); //modify the buffer
  1106. } else {
  1107. #ifdef DEBUG_ENABLED
  1108. if (state.debug_draw == VS::VIEWPORT_DEBUG_DRAW_WIREFRAME && s->instancing_array_wireframe_id) {
  1109. glBindVertexArray(s->instancing_array_wireframe_id); // use the wireframe instancing array ID
  1110. } else
  1111. #endif
  1112. {
  1113. glBindVertexArray(s->instancing_array_id); // use the instancing array ID
  1114. }
  1115. glBindBuffer(GL_ARRAY_BUFFER, particles->particle_buffers[0]); //modify the buffer
  1116. }
  1117. int stride = sizeof(float) * 4 * 6;
  1118. //transform
  1119. if (particles->draw_order != VS::PARTICLES_DRAW_ORDER_LIFETIME) {
  1120. glEnableVertexAttribArray(8); //xform x
  1121. glVertexAttribPointer(8, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(sizeof(float) * 4 * 3));
  1122. glVertexAttribDivisor(8, 1);
  1123. glEnableVertexAttribArray(9); //xform y
  1124. glVertexAttribPointer(9, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(sizeof(float) * 4 * 4));
  1125. glVertexAttribDivisor(9, 1);
  1126. glEnableVertexAttribArray(10); //xform z
  1127. glVertexAttribPointer(10, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(sizeof(float) * 4 * 5));
  1128. glVertexAttribDivisor(10, 1);
  1129. glEnableVertexAttribArray(11); //color
  1130. glVertexAttribPointer(11, 4, GL_FLOAT, GL_FALSE, stride, NULL);
  1131. glVertexAttribDivisor(11, 1);
  1132. glEnableVertexAttribArray(12); //custom
  1133. glVertexAttribPointer(12, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(sizeof(float) * 4 * 2));
  1134. glVertexAttribDivisor(12, 1);
  1135. }
  1136. } break;
  1137. default: {
  1138. }
  1139. }
  1140. }
  1141. static const GLenum gl_primitive[] = {
  1142. GL_POINTS,
  1143. GL_LINES,
  1144. GL_LINE_STRIP,
  1145. GL_LINE_LOOP,
  1146. GL_TRIANGLES,
  1147. GL_TRIANGLE_STRIP,
  1148. GL_TRIANGLE_FAN
  1149. };
  1150. void RasterizerSceneGLES3::_render_geometry(RenderList::Element *e) {
  1151. switch (e->instance->base_type) {
  1152. case VS::INSTANCE_MESH: {
  1153. RasterizerStorageGLES3::Surface *s = static_cast<RasterizerStorageGLES3::Surface *>(e->geometry);
  1154. #ifdef DEBUG_ENABLED
  1155. if (state.debug_draw == VS::VIEWPORT_DEBUG_DRAW_WIREFRAME && s->array_wireframe_id) {
  1156. glDrawElements(GL_LINES, s->index_wireframe_len, GL_UNSIGNED_INT, 0);
  1157. storage->info.render.vertices_count += s->index_array_len;
  1158. } else
  1159. #endif
  1160. if (s->index_array_len > 0) {
  1161. glDrawElements(gl_primitive[s->primitive], s->index_array_len, (s->array_len >= (1 << 16)) ? GL_UNSIGNED_INT : GL_UNSIGNED_SHORT, 0);
  1162. storage->info.render.vertices_count += s->index_array_len;
  1163. } else {
  1164. glDrawArrays(gl_primitive[s->primitive], 0, s->array_len);
  1165. storage->info.render.vertices_count += s->array_len;
  1166. }
  1167. } break;
  1168. case VS::INSTANCE_MULTIMESH: {
  1169. RasterizerStorageGLES3::MultiMesh *multi_mesh = static_cast<RasterizerStorageGLES3::MultiMesh *>(e->owner);
  1170. RasterizerStorageGLES3::Surface *s = static_cast<RasterizerStorageGLES3::Surface *>(e->geometry);
  1171. int amount = MIN(multi_mesh->size, multi_mesh->visible_instances);
  1172. if (amount == -1) {
  1173. amount = multi_mesh->size;
  1174. }
  1175. #ifdef DEBUG_ENABLED
  1176. if (state.debug_draw == VS::VIEWPORT_DEBUG_DRAW_WIREFRAME && s->array_wireframe_id) {
  1177. glDrawElementsInstanced(GL_LINES, s->index_wireframe_len, GL_UNSIGNED_INT, 0, amount);
  1178. storage->info.render.vertices_count += s->index_array_len * amount;
  1179. } else
  1180. #endif
  1181. if (s->index_array_len > 0) {
  1182. glDrawElementsInstanced(gl_primitive[s->primitive], s->index_array_len, (s->array_len >= (1 << 16)) ? GL_UNSIGNED_INT : GL_UNSIGNED_SHORT, 0, amount);
  1183. storage->info.render.vertices_count += s->index_array_len * amount;
  1184. } else {
  1185. glDrawArraysInstanced(gl_primitive[s->primitive], 0, s->array_len, amount);
  1186. storage->info.render.vertices_count += s->array_len * amount;
  1187. }
  1188. } break;
  1189. case VS::INSTANCE_IMMEDIATE: {
  1190. bool restore_tex = false;
  1191. const RasterizerStorageGLES3::Immediate *im = static_cast<const RasterizerStorageGLES3::Immediate *>(e->geometry);
  1192. if (im->building) {
  1193. return;
  1194. }
  1195. glBindBuffer(GL_ARRAY_BUFFER, state.immediate_buffer);
  1196. glBindVertexArray(state.immediate_array);
  1197. for (const List<RasterizerStorageGLES3::Immediate::Chunk>::Element *E = im->chunks.front(); E; E = E->next()) {
  1198. const RasterizerStorageGLES3::Immediate::Chunk &c = E->get();
  1199. if (c.vertices.empty()) {
  1200. continue;
  1201. }
  1202. int vertices = c.vertices.size();
  1203. uint32_t buf_ofs = 0;
  1204. storage->info.render.vertices_count += vertices;
  1205. if (c.texture.is_valid() && storage->texture_owner.owns(c.texture)) {
  1206. RasterizerStorageGLES3::Texture *t = storage->texture_owner.get(c.texture);
  1207. if (t->redraw_if_visible) {
  1208. VisualServerRaster::redraw_request();
  1209. }
  1210. t = t->get_ptr(); //resolve for proxies
  1211. #ifdef TOOLS_ENABLED
  1212. if (t->detect_3d) {
  1213. t->detect_3d(t->detect_3d_ud);
  1214. }
  1215. #endif
  1216. if (t->render_target) {
  1217. t->render_target->used_in_frame = true;
  1218. }
  1219. glActiveTexture(GL_TEXTURE0);
  1220. glBindTexture(t->target, t->tex_id);
  1221. restore_tex = true;
  1222. } else if (restore_tex) {
  1223. glActiveTexture(GL_TEXTURE0);
  1224. glBindTexture(GL_TEXTURE_2D, state.current_main_tex);
  1225. restore_tex = false;
  1226. }
  1227. if (!c.normals.empty()) {
  1228. glEnableVertexAttribArray(VS::ARRAY_NORMAL);
  1229. glBufferSubData(GL_ARRAY_BUFFER, buf_ofs, sizeof(Vector3) * vertices, c.normals.ptr());
  1230. glVertexAttribPointer(VS::ARRAY_NORMAL, 3, GL_FLOAT, false, sizeof(Vector3), CAST_INT_TO_UCHAR_PTR(buf_ofs));
  1231. buf_ofs += sizeof(Vector3) * vertices;
  1232. } else {
  1233. glDisableVertexAttribArray(VS::ARRAY_NORMAL);
  1234. }
  1235. if (!c.tangents.empty()) {
  1236. glEnableVertexAttribArray(VS::ARRAY_TANGENT);
  1237. glBufferSubData(GL_ARRAY_BUFFER, buf_ofs, sizeof(Plane) * vertices, c.tangents.ptr());
  1238. glVertexAttribPointer(VS::ARRAY_TANGENT, 4, GL_FLOAT, false, sizeof(Plane), CAST_INT_TO_UCHAR_PTR(buf_ofs));
  1239. buf_ofs += sizeof(Plane) * vertices;
  1240. } else {
  1241. glDisableVertexAttribArray(VS::ARRAY_TANGENT);
  1242. }
  1243. if (!c.colors.empty()) {
  1244. glEnableVertexAttribArray(VS::ARRAY_COLOR);
  1245. glBufferSubData(GL_ARRAY_BUFFER, buf_ofs, sizeof(Color) * vertices, c.colors.ptr());
  1246. glVertexAttribPointer(VS::ARRAY_COLOR, 4, GL_FLOAT, false, sizeof(Color), CAST_INT_TO_UCHAR_PTR(buf_ofs));
  1247. buf_ofs += sizeof(Color) * vertices;
  1248. } else {
  1249. glDisableVertexAttribArray(VS::ARRAY_COLOR);
  1250. glVertexAttrib4f(VS::ARRAY_COLOR, 1, 1, 1, 1);
  1251. }
  1252. if (!c.uvs.empty()) {
  1253. glEnableVertexAttribArray(VS::ARRAY_TEX_UV);
  1254. glBufferSubData(GL_ARRAY_BUFFER, buf_ofs, sizeof(Vector2) * vertices, c.uvs.ptr());
  1255. glVertexAttribPointer(VS::ARRAY_TEX_UV, 2, GL_FLOAT, false, sizeof(Vector2), CAST_INT_TO_UCHAR_PTR(buf_ofs));
  1256. buf_ofs += sizeof(Vector2) * vertices;
  1257. } else {
  1258. glDisableVertexAttribArray(VS::ARRAY_TEX_UV);
  1259. }
  1260. if (!c.uvs2.empty()) {
  1261. glEnableVertexAttribArray(VS::ARRAY_TEX_UV2);
  1262. glBufferSubData(GL_ARRAY_BUFFER, buf_ofs, sizeof(Vector2) * vertices, c.uvs2.ptr());
  1263. glVertexAttribPointer(VS::ARRAY_TEX_UV2, 2, GL_FLOAT, false, sizeof(Vector2), CAST_INT_TO_UCHAR_PTR(buf_ofs));
  1264. buf_ofs += sizeof(Vector2) * vertices;
  1265. } else {
  1266. glDisableVertexAttribArray(VS::ARRAY_TEX_UV2);
  1267. }
  1268. glEnableVertexAttribArray(VS::ARRAY_VERTEX);
  1269. glBufferSubData(GL_ARRAY_BUFFER, buf_ofs, sizeof(Vector3) * vertices, c.vertices.ptr());
  1270. glVertexAttribPointer(VS::ARRAY_VERTEX, 3, GL_FLOAT, false, sizeof(Vector3), CAST_INT_TO_UCHAR_PTR(buf_ofs));
  1271. glDrawArrays(gl_primitive[c.primitive], 0, c.vertices.size());
  1272. }
  1273. if (restore_tex) {
  1274. glActiveTexture(GL_TEXTURE0);
  1275. glBindTexture(GL_TEXTURE_2D, state.current_main_tex);
  1276. restore_tex = false;
  1277. }
  1278. } break;
  1279. case VS::INSTANCE_PARTICLES: {
  1280. RasterizerStorageGLES3::Particles *particles = static_cast<RasterizerStorageGLES3::Particles *>(e->owner);
  1281. RasterizerStorageGLES3::Surface *s = static_cast<RasterizerStorageGLES3::Surface *>(e->geometry);
  1282. if (!particles->use_local_coords) //not using local coordinates? then clear transform..
  1283. state.scene_shader.set_uniform(SceneShaderGLES3::WORLD_TRANSFORM, Transform());
  1284. int amount = particles->amount;
  1285. if (particles->draw_order == VS::PARTICLES_DRAW_ORDER_LIFETIME) {
  1286. //split
  1287. int stride = sizeof(float) * 4 * 6;
  1288. int split = int(Math::ceil(particles->phase * particles->amount));
  1289. if (amount - split > 0) {
  1290. glEnableVertexAttribArray(8); //xform x
  1291. glVertexAttribPointer(8, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(stride * split + sizeof(float) * 4 * 3));
  1292. glVertexAttribDivisor(8, 1);
  1293. glEnableVertexAttribArray(9); //xform y
  1294. glVertexAttribPointer(9, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(stride * split + sizeof(float) * 4 * 4));
  1295. glVertexAttribDivisor(9, 1);
  1296. glEnableVertexAttribArray(10); //xform z
  1297. glVertexAttribPointer(10, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(stride * split + sizeof(float) * 4 * 5));
  1298. glVertexAttribDivisor(10, 1);
  1299. glEnableVertexAttribArray(11); //color
  1300. glVertexAttribPointer(11, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(stride * split + 0));
  1301. glVertexAttribDivisor(11, 1);
  1302. glEnableVertexAttribArray(12); //custom
  1303. glVertexAttribPointer(12, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(stride * split + sizeof(float) * 4 * 2));
  1304. glVertexAttribDivisor(12, 1);
  1305. #ifdef DEBUG_ENABLED
  1306. if (state.debug_draw == VS::VIEWPORT_DEBUG_DRAW_WIREFRAME && s->array_wireframe_id) {
  1307. glDrawElementsInstanced(GL_LINES, s->index_wireframe_len, GL_UNSIGNED_INT, 0, amount - split);
  1308. storage->info.render.vertices_count += s->index_array_len * (amount - split);
  1309. } else
  1310. #endif
  1311. if (s->index_array_len > 0) {
  1312. glDrawElementsInstanced(gl_primitive[s->primitive], s->index_array_len, (s->array_len >= (1 << 16)) ? GL_UNSIGNED_INT : GL_UNSIGNED_SHORT, 0, amount - split);
  1313. storage->info.render.vertices_count += s->index_array_len * (amount - split);
  1314. } else {
  1315. glDrawArraysInstanced(gl_primitive[s->primitive], 0, s->array_len, amount - split);
  1316. storage->info.render.vertices_count += s->array_len * (amount - split);
  1317. }
  1318. }
  1319. if (split > 0) {
  1320. glEnableVertexAttribArray(8); //xform x
  1321. glVertexAttribPointer(8, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(sizeof(float) * 4 * 3));
  1322. glVertexAttribDivisor(8, 1);
  1323. glEnableVertexAttribArray(9); //xform y
  1324. glVertexAttribPointer(9, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(sizeof(float) * 4 * 4));
  1325. glVertexAttribDivisor(9, 1);
  1326. glEnableVertexAttribArray(10); //xform z
  1327. glVertexAttribPointer(10, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(sizeof(float) * 4 * 5));
  1328. glVertexAttribDivisor(10, 1);
  1329. glEnableVertexAttribArray(11); //color
  1330. glVertexAttribPointer(11, 4, GL_FLOAT, GL_FALSE, stride, NULL);
  1331. glVertexAttribDivisor(11, 1);
  1332. glEnableVertexAttribArray(12); //custom
  1333. glVertexAttribPointer(12, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(sizeof(float) * 4 * 2));
  1334. glVertexAttribDivisor(12, 1);
  1335. #ifdef DEBUG_ENABLED
  1336. if (state.debug_draw == VS::VIEWPORT_DEBUG_DRAW_WIREFRAME && s->array_wireframe_id) {
  1337. glDrawElementsInstanced(GL_LINES, s->index_wireframe_len, GL_UNSIGNED_INT, 0, split);
  1338. storage->info.render.vertices_count += s->index_array_len * split;
  1339. } else
  1340. #endif
  1341. if (s->index_array_len > 0) {
  1342. glDrawElementsInstanced(gl_primitive[s->primitive], s->index_array_len, (s->array_len >= (1 << 16)) ? GL_UNSIGNED_INT : GL_UNSIGNED_SHORT, 0, split);
  1343. storage->info.render.vertices_count += s->index_array_len * split;
  1344. } else {
  1345. glDrawArraysInstanced(gl_primitive[s->primitive], 0, s->array_len, split);
  1346. storage->info.render.vertices_count += s->array_len * split;
  1347. }
  1348. }
  1349. } else {
  1350. #ifdef DEBUG_ENABLED
  1351. if (state.debug_draw == VS::VIEWPORT_DEBUG_DRAW_WIREFRAME && s->array_wireframe_id) {
  1352. glDrawElementsInstanced(GL_LINES, s->index_wireframe_len, GL_UNSIGNED_INT, 0, amount);
  1353. storage->info.render.vertices_count += s->index_array_len * amount;
  1354. } else
  1355. #endif
  1356. if (s->index_array_len > 0) {
  1357. glDrawElementsInstanced(gl_primitive[s->primitive], s->index_array_len, (s->array_len >= (1 << 16)) ? GL_UNSIGNED_INT : GL_UNSIGNED_SHORT, 0, amount);
  1358. storage->info.render.vertices_count += s->index_array_len * amount;
  1359. } else {
  1360. glDrawArraysInstanced(gl_primitive[s->primitive], 0, s->array_len, amount);
  1361. storage->info.render.vertices_count += s->array_len * amount;
  1362. }
  1363. }
  1364. } break;
  1365. default: {
  1366. }
  1367. }
  1368. }
  1369. void RasterizerSceneGLES3::_setup_light(RenderList::Element *e, const Transform &p_view_transform) {
  1370. int maxobj = state.max_forward_lights_per_object;
  1371. int *omni_indices = (int *)alloca(maxobj * sizeof(int));
  1372. int omni_count = 0;
  1373. int *spot_indices = (int *)alloca(maxobj * sizeof(int));
  1374. int spot_count = 0;
  1375. int reflection_indices[16];
  1376. int reflection_count = 0;
  1377. int lc = e->instance->light_instances.size();
  1378. if (lc) {
  1379. const RID *lights = e->instance->light_instances.ptr();
  1380. for (int i = 0; i < lc; i++) {
  1381. LightInstance *li = light_instance_owner.getornull(lights[i]);
  1382. if (!li || li->last_pass != render_pass) {
  1383. continue; // Not visible
  1384. }
  1385. if (e->instance->baked_light && li->light_ptr->bake_mode == VS::LightBakeMode::LIGHT_BAKE_ALL) {
  1386. continue; // This light is already included in the lightmap
  1387. }
  1388. if (li && li->light_ptr->type == VS::LIGHT_OMNI) {
  1389. if (omni_count < maxobj && e->instance->layer_mask & li->light_ptr->cull_mask) {
  1390. omni_indices[omni_count++] = li->light_index;
  1391. }
  1392. }
  1393. if (li && li->light_ptr->type == VS::LIGHT_SPOT) {
  1394. if (spot_count < maxobj && e->instance->layer_mask & li->light_ptr->cull_mask) {
  1395. spot_indices[spot_count++] = li->light_index;
  1396. }
  1397. }
  1398. }
  1399. }
  1400. state.scene_shader.set_uniform(SceneShaderGLES3::OMNI_LIGHT_COUNT, omni_count);
  1401. if (omni_count) {
  1402. glUniform1iv(state.scene_shader.get_uniform(SceneShaderGLES3::OMNI_LIGHT_INDICES), omni_count, omni_indices);
  1403. }
  1404. state.scene_shader.set_uniform(SceneShaderGLES3::SPOT_LIGHT_COUNT, spot_count);
  1405. if (spot_count) {
  1406. glUniform1iv(state.scene_shader.get_uniform(SceneShaderGLES3::SPOT_LIGHT_INDICES), spot_count, spot_indices);
  1407. }
  1408. int rc = e->instance->reflection_probe_instances.size();
  1409. if (rc) {
  1410. const RID *reflections = e->instance->reflection_probe_instances.ptr();
  1411. for (int i = 0; i < rc; i++) {
  1412. ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getptr(reflections[i]);
  1413. if (rpi->last_pass != render_pass) //not visible
  1414. continue;
  1415. if (reflection_count < maxobj) {
  1416. reflection_indices[reflection_count++] = rpi->reflection_index;
  1417. }
  1418. }
  1419. }
  1420. state.scene_shader.set_uniform(SceneShaderGLES3::REFLECTION_COUNT, reflection_count);
  1421. if (reflection_count) {
  1422. glUniform1iv(state.scene_shader.get_uniform(SceneShaderGLES3::REFLECTION_INDICES), reflection_count, reflection_indices);
  1423. }
  1424. int gi_probe_count = e->instance->gi_probe_instances.size();
  1425. if (gi_probe_count) {
  1426. const RID *ridp = e->instance->gi_probe_instances.ptr();
  1427. GIProbeInstance *gipi = gi_probe_instance_owner.getptr(ridp[0]);
  1428. float bias_scale = e->instance->baked_light ? 1 : 0;
  1429. glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 9);
  1430. glBindTexture(GL_TEXTURE_3D, gipi->tex_cache);
  1431. state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_XFORM1, gipi->transform_to_data * p_view_transform);
  1432. state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_BOUNDS1, gipi->bounds);
  1433. state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_MULTIPLIER1, gipi->probe ? gipi->probe->dynamic_range * gipi->probe->energy : 0.0);
  1434. state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_BIAS1, gipi->probe ? gipi->probe->bias * bias_scale : 0.0);
  1435. state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_NORMAL_BIAS1, gipi->probe ? gipi->probe->normal_bias * bias_scale : 0.0);
  1436. state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_BLEND_AMBIENT1, gipi->probe ? !gipi->probe->interior : false);
  1437. state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_CELL_SIZE1, gipi->cell_size_cache);
  1438. if (gi_probe_count > 1) {
  1439. GIProbeInstance *gipi2 = gi_probe_instance_owner.getptr(ridp[1]);
  1440. glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 10);
  1441. glBindTexture(GL_TEXTURE_3D, gipi2->tex_cache);
  1442. state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_XFORM2, gipi2->transform_to_data * p_view_transform);
  1443. state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_BOUNDS2, gipi2->bounds);
  1444. state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_CELL_SIZE2, gipi2->cell_size_cache);
  1445. state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_MULTIPLIER2, gipi2->probe ? gipi2->probe->dynamic_range * gipi2->probe->energy : 0.0);
  1446. state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_BIAS2, gipi2->probe ? gipi2->probe->bias * bias_scale : 0.0);
  1447. state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_NORMAL_BIAS2, gipi2->probe ? gipi2->probe->normal_bias * bias_scale : 0.0);
  1448. state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_BLEND_AMBIENT2, gipi2->probe ? !gipi2->probe->interior : false);
  1449. state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE2_ENABLED, true);
  1450. } else {
  1451. state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE2_ENABLED, false);
  1452. }
  1453. } else if (!e->instance->lightmap_capture_data.empty()) {
  1454. glUniform4fv(state.scene_shader.get_uniform_location(SceneShaderGLES3::LIGHTMAP_CAPTURES), 12, (const GLfloat *)e->instance->lightmap_capture_data.ptr());
  1455. } else if (e->instance->lightmap.is_valid()) {
  1456. RasterizerStorageGLES3::Texture *lightmap = storage->texture_owner.getornull(e->instance->lightmap);
  1457. RasterizerStorageGLES3::LightmapCapture *capture = storage->lightmap_capture_data_owner.getornull(e->instance->lightmap_capture->base);
  1458. if (lightmap && capture) {
  1459. glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 9);
  1460. if (e->instance->lightmap_slice == -1) {
  1461. glBindTexture(GL_TEXTURE_2D, lightmap->tex_id);
  1462. } else {
  1463. glBindTexture(GL_TEXTURE_2D_ARRAY, lightmap->tex_id);
  1464. state.scene_shader.set_uniform(SceneShaderGLES3::LIGHTMAP_LAYER, e->instance->lightmap_slice);
  1465. }
  1466. const Rect2 &uvr = e->instance->lightmap_uv_rect;
  1467. state.scene_shader.set_uniform(SceneShaderGLES3::LIGHTMAP_UV_RECT, Color(uvr.get_position().x, uvr.get_position().y, uvr.get_size().x, uvr.get_size().y));
  1468. if (storage->config.use_lightmap_filter_bicubic) {
  1469. state.scene_shader.set_uniform(SceneShaderGLES3::LIGHTMAP_TEXTURE_SIZE, Vector2(lightmap->width, lightmap->height));
  1470. }
  1471. state.scene_shader.set_uniform(SceneShaderGLES3::LIGHTMAP_ENERGY, capture->energy);
  1472. }
  1473. }
  1474. }
  1475. void RasterizerSceneGLES3::_set_cull(bool p_front, bool p_disabled, bool p_reverse_cull) {
  1476. bool front = p_front;
  1477. if (p_reverse_cull)
  1478. front = !front;
  1479. if (p_disabled != state.cull_disabled) {
  1480. if (p_disabled)
  1481. glDisable(GL_CULL_FACE);
  1482. else
  1483. glEnable(GL_CULL_FACE);
  1484. state.cull_disabled = p_disabled;
  1485. }
  1486. if (front != state.cull_front) {
  1487. glCullFace(front ? GL_FRONT : GL_BACK);
  1488. state.cull_front = front;
  1489. }
  1490. }
  1491. void RasterizerSceneGLES3::_render_list(RenderList::Element **p_elements, int p_element_count, const Transform &p_view_transform, const CameraMatrix &p_projection, RasterizerStorageGLES3::Sky *p_sky, bool p_reverse_cull, bool p_alpha_pass, bool p_shadow, bool p_directional_add, bool p_directional_shadows) {
  1492. glBindBufferBase(GL_UNIFORM_BUFFER, 0, state.scene_ubo); //bind globals ubo
  1493. bool use_radiance_map = false;
  1494. if (!p_shadow && !p_directional_add) {
  1495. glBindBufferBase(GL_UNIFORM_BUFFER, 2, state.env_radiance_ubo); //bind environment radiance info
  1496. if (p_sky != NULL) {
  1497. glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 2);
  1498. if (storage->config.use_texture_array_environment) {
  1499. glBindTexture(GL_TEXTURE_2D_ARRAY, p_sky->radiance);
  1500. } else {
  1501. glBindTexture(GL_TEXTURE_2D, p_sky->radiance);
  1502. }
  1503. glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 6);
  1504. glBindTexture(GL_TEXTURE_2D, p_sky->irradiance);
  1505. state.scene_shader.set_conditional(SceneShaderGLES3::USE_RADIANCE_MAP, true);
  1506. state.scene_shader.set_conditional(SceneShaderGLES3::USE_RADIANCE_MAP_ARRAY, storage->config.use_texture_array_environment);
  1507. use_radiance_map = true;
  1508. } else {
  1509. state.scene_shader.set_conditional(SceneShaderGLES3::USE_RADIANCE_MAP, false);
  1510. state.scene_shader.set_conditional(SceneShaderGLES3::USE_RADIANCE_MAP_ARRAY, false);
  1511. }
  1512. } else {
  1513. state.scene_shader.set_conditional(SceneShaderGLES3::USE_RADIANCE_MAP, false);
  1514. state.scene_shader.set_conditional(SceneShaderGLES3::USE_RADIANCE_MAP_ARRAY, false);
  1515. }
  1516. state.cull_front = false;
  1517. state.cull_disabled = false;
  1518. glCullFace(GL_BACK);
  1519. glEnable(GL_CULL_FACE);
  1520. state.current_depth_test = true;
  1521. glEnable(GL_DEPTH_TEST);
  1522. state.scene_shader.set_conditional(SceneShaderGLES3::USE_SKELETON, false);
  1523. state.current_blend_mode = -1;
  1524. state.current_line_width = -1;
  1525. state.current_depth_draw = -1;
  1526. RasterizerStorageGLES3::Material *prev_material = NULL;
  1527. RasterizerStorageGLES3::Geometry *prev_geometry = NULL;
  1528. RasterizerStorageGLES3::GeometryOwner *prev_owner = NULL;
  1529. VS::InstanceType prev_base_type = VS::INSTANCE_MAX;
  1530. int current_blend_mode = -1;
  1531. uint32_t prev_shading = 0xFFFFFFFF;
  1532. RasterizerStorageGLES3::Skeleton *prev_skeleton = NULL;
  1533. state.scene_shader.set_conditional(SceneShaderGLES3::SHADELESS, true); //by default unshaded (easier to set)
  1534. bool first = true;
  1535. bool prev_use_instancing = false;
  1536. storage->info.render.draw_call_count += p_element_count;
  1537. bool prev_opaque_prepass = false;
  1538. for (int i = 0; i < p_element_count; i++) {
  1539. RenderList::Element *e = p_elements[i];
  1540. RasterizerStorageGLES3::Material *material = e->material;
  1541. RasterizerStorageGLES3::Skeleton *skeleton = NULL;
  1542. if (e->instance->skeleton.is_valid()) {
  1543. skeleton = storage->skeleton_owner.getornull(e->instance->skeleton);
  1544. }
  1545. bool rebind = first;
  1546. uint32_t shading = (e->sort_key >> RenderList::SORT_KEY_SHADING_SHIFT) & RenderList::SORT_KEY_SHADING_MASK;
  1547. if (!p_shadow) {
  1548. bool use_directional = directional_light != NULL;
  1549. if (p_directional_add) {
  1550. use_directional = use_directional && !(e->instance->baked_light && directional_light->light_ptr->bake_mode == VS::LightBakeMode::LIGHT_BAKE_ALL);
  1551. use_directional = use_directional && ((e->instance->layer_mask & directional_light->light_ptr->cull_mask) != 0);
  1552. use_directional = use_directional && ((e->sort_key & SORT_KEY_UNSHADED_FLAG) == 0);
  1553. if (!use_directional) {
  1554. continue; // It's a directional-only pass and the directional light is disabled
  1555. }
  1556. } else {
  1557. use_directional = use_directional && (e->sort_key & SORT_KEY_NO_DIRECTIONAL_FLAG) == 0;
  1558. }
  1559. if (shading != prev_shading) {
  1560. if (e->sort_key & SORT_KEY_UNSHADED_FLAG) {
  1561. state.scene_shader.set_conditional(SceneShaderGLES3::SHADELESS, true);
  1562. state.scene_shader.set_conditional(SceneShaderGLES3::USE_FORWARD_LIGHTING, false);
  1563. state.scene_shader.set_conditional(SceneShaderGLES3::USE_VERTEX_LIGHTING, false);
  1564. state.scene_shader.set_conditional(SceneShaderGLES3::USE_LIGHT_DIRECTIONAL, false);
  1565. state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_DIRECTIONAL_SHADOW, false);
  1566. state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM4, false);
  1567. state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM2, false);
  1568. state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM_BLEND, false);
  1569. state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM_BLEND, false);
  1570. state.scene_shader.set_conditional(SceneShaderGLES3::SHADOW_MODE_PCF_5, false);
  1571. state.scene_shader.set_conditional(SceneShaderGLES3::SHADOW_MODE_PCF_13, false);
  1572. state.scene_shader.set_conditional(SceneShaderGLES3::USE_GI_PROBES, false);
  1573. state.scene_shader.set_conditional(SceneShaderGLES3::USE_LIGHTMAP_CAPTURE, false);
  1574. state.scene_shader.set_conditional(SceneShaderGLES3::USE_LIGHTMAP, false);
  1575. state.scene_shader.set_conditional(SceneShaderGLES3::USE_LIGHTMAP_LAYERED, false);
  1576. state.scene_shader.set_conditional(SceneShaderGLES3::USE_RADIANCE_MAP, false);
  1577. state.scene_shader.set_conditional(SceneShaderGLES3::USE_CONTACT_SHADOWS, false);
  1578. //state.scene_shader.set_conditional(SceneShaderGLES3::SHADELESS,true);
  1579. } else {
  1580. state.scene_shader.set_conditional(SceneShaderGLES3::USE_GI_PROBES, e->instance->gi_probe_instances.size() > 0);
  1581. state.scene_shader.set_conditional(SceneShaderGLES3::USE_LIGHTMAP, e->instance->lightmap.is_valid() && e->instance->gi_probe_instances.size() == 0);
  1582. state.scene_shader.set_conditional(SceneShaderGLES3::USE_LIGHTMAP_LAYERED, e->instance->lightmap_slice != -1);
  1583. state.scene_shader.set_conditional(SceneShaderGLES3::USE_LIGHTMAP_CAPTURE, !e->instance->lightmap_capture_data.empty() && !e->instance->lightmap.is_valid() && e->instance->gi_probe_instances.size() == 0);
  1584. state.scene_shader.set_conditional(SceneShaderGLES3::SHADELESS, false);
  1585. state.scene_shader.set_conditional(SceneShaderGLES3::USE_FORWARD_LIGHTING, !p_directional_add);
  1586. state.scene_shader.set_conditional(SceneShaderGLES3::USE_VERTEX_LIGHTING, (e->sort_key & SORT_KEY_VERTEX_LIT_FLAG));
  1587. state.scene_shader.set_conditional(SceneShaderGLES3::USE_LIGHT_DIRECTIONAL, use_directional);
  1588. state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_DIRECTIONAL_SHADOW, false);
  1589. state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM4, false);
  1590. state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM2, false);
  1591. state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM_BLEND, false);
  1592. state.scene_shader.set_conditional(SceneShaderGLES3::SHADOW_MODE_PCF_5, shadow_filter_mode == SHADOW_FILTER_PCF5);
  1593. state.scene_shader.set_conditional(SceneShaderGLES3::SHADOW_MODE_PCF_13, shadow_filter_mode == SHADOW_FILTER_PCF13);
  1594. state.scene_shader.set_conditional(SceneShaderGLES3::USE_RADIANCE_MAP, use_radiance_map);
  1595. state.scene_shader.set_conditional(SceneShaderGLES3::USE_CONTACT_SHADOWS, state.used_contact_shadows);
  1596. if (use_directional) {
  1597. if (p_directional_shadows && directional_light->light_ptr->shadow) {
  1598. state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_DIRECTIONAL_SHADOW, true);
  1599. switch (directional_light->light_ptr->directional_shadow_mode) {
  1600. case VS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL:
  1601. break; //none
  1602. case VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS:
  1603. state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM2, true);
  1604. state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM_BLEND, directional_light->light_ptr->directional_blend_splits);
  1605. break;
  1606. case VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS:
  1607. state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM4, true);
  1608. state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM_BLEND, directional_light->light_ptr->directional_blend_splits);
  1609. break;
  1610. }
  1611. }
  1612. }
  1613. }
  1614. rebind = true;
  1615. }
  1616. if (p_alpha_pass || p_directional_add) {
  1617. int desired_blend_mode;
  1618. if (p_directional_add) {
  1619. desired_blend_mode = RasterizerStorageGLES3::Shader::Spatial::BLEND_MODE_ADD;
  1620. } else {
  1621. desired_blend_mode = material->shader->spatial.blend_mode;
  1622. }
  1623. if (desired_blend_mode != current_blend_mode) {
  1624. switch (desired_blend_mode) {
  1625. case RasterizerStorageGLES3::Shader::Spatial::BLEND_MODE_MIX: {
  1626. glBlendEquation(GL_FUNC_ADD);
  1627. if (storage->frame.current_rt && storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_TRANSPARENT]) {
  1628. glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
  1629. } else {
  1630. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  1631. }
  1632. } break;
  1633. case RasterizerStorageGLES3::Shader::Spatial::BLEND_MODE_ADD: {
  1634. glBlendEquation(GL_FUNC_ADD);
  1635. glBlendFunc(p_alpha_pass ? GL_SRC_ALPHA : GL_ONE, GL_ONE);
  1636. } break;
  1637. case RasterizerStorageGLES3::Shader::Spatial::BLEND_MODE_SUB: {
  1638. glBlendEquation(GL_FUNC_REVERSE_SUBTRACT);
  1639. glBlendFunc(GL_SRC_ALPHA, GL_ONE);
  1640. } break;
  1641. case RasterizerStorageGLES3::Shader::Spatial::BLEND_MODE_MUL: {
  1642. glBlendEquation(GL_FUNC_ADD);
  1643. if (storage->frame.current_rt && storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_TRANSPARENT]) {
  1644. glBlendFuncSeparate(GL_DST_COLOR, GL_ZERO, GL_DST_ALPHA, GL_ZERO);
  1645. } else {
  1646. glBlendFuncSeparate(GL_DST_COLOR, GL_ZERO, GL_ZERO, GL_ONE);
  1647. }
  1648. } break;
  1649. }
  1650. current_blend_mode = desired_blend_mode;
  1651. }
  1652. }
  1653. }
  1654. bool use_opaque_prepass = e->sort_key & RenderList::SORT_KEY_OPAQUE_PRE_PASS;
  1655. if (use_opaque_prepass != prev_opaque_prepass) {
  1656. state.scene_shader.set_conditional(SceneShaderGLES3::USE_OPAQUE_PREPASS, use_opaque_prepass);
  1657. rebind = true;
  1658. }
  1659. bool use_instancing = e->instance->base_type == VS::INSTANCE_MULTIMESH || e->instance->base_type == VS::INSTANCE_PARTICLES;
  1660. if (use_instancing != prev_use_instancing) {
  1661. state.scene_shader.set_conditional(SceneShaderGLES3::USE_INSTANCING, use_instancing);
  1662. rebind = true;
  1663. }
  1664. if (prev_skeleton != skeleton) {
  1665. if ((prev_skeleton == NULL) != (skeleton == NULL)) {
  1666. state.scene_shader.set_conditional(SceneShaderGLES3::USE_SKELETON, skeleton != NULL);
  1667. rebind = true;
  1668. }
  1669. if (skeleton) {
  1670. glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 1);
  1671. glBindTexture(GL_TEXTURE_2D, skeleton->texture);
  1672. }
  1673. }
  1674. if (material != prev_material || rebind) {
  1675. storage->info.render.material_switch_count++;
  1676. rebind = _setup_material(material, use_opaque_prepass, p_alpha_pass);
  1677. if (rebind) {
  1678. storage->info.render.shader_rebind_count++;
  1679. }
  1680. }
  1681. if (!(e->sort_key & SORT_KEY_UNSHADED_FLAG) && !p_directional_add && !p_shadow) {
  1682. _setup_light(e, p_view_transform);
  1683. }
  1684. if (e->owner != prev_owner || prev_base_type != e->instance->base_type || prev_geometry != e->geometry) {
  1685. _setup_geometry(e, p_view_transform);
  1686. storage->info.render.surface_switch_count++;
  1687. }
  1688. _set_cull(e->sort_key & RenderList::SORT_KEY_MIRROR_FLAG, e->sort_key & RenderList::SORT_KEY_CULL_DISABLED_FLAG, p_reverse_cull);
  1689. state.scene_shader.set_uniform(SceneShaderGLES3::WORLD_TRANSFORM, e->instance->transform);
  1690. _render_geometry(e);
  1691. prev_material = material;
  1692. prev_base_type = e->instance->base_type;
  1693. prev_geometry = e->geometry;
  1694. prev_owner = e->owner;
  1695. prev_shading = shading;
  1696. prev_skeleton = skeleton;
  1697. prev_use_instancing = use_instancing;
  1698. prev_opaque_prepass = use_opaque_prepass;
  1699. first = false;
  1700. }
  1701. glBindVertexArray(0);
  1702. state.scene_shader.set_conditional(SceneShaderGLES3::USE_INSTANCING, false);
  1703. state.scene_shader.set_conditional(SceneShaderGLES3::USE_SKELETON, false);
  1704. state.scene_shader.set_conditional(SceneShaderGLES3::USE_RADIANCE_MAP, false);
  1705. state.scene_shader.set_conditional(SceneShaderGLES3::USE_FORWARD_LIGHTING, false);
  1706. state.scene_shader.set_conditional(SceneShaderGLES3::USE_LIGHT_DIRECTIONAL, false);
  1707. state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_DIRECTIONAL_SHADOW, false);
  1708. state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM4, false);
  1709. state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM2, false);
  1710. state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM_BLEND, false);
  1711. state.scene_shader.set_conditional(SceneShaderGLES3::SHADELESS, false);
  1712. state.scene_shader.set_conditional(SceneShaderGLES3::SHADOW_MODE_PCF_5, false);
  1713. state.scene_shader.set_conditional(SceneShaderGLES3::SHADOW_MODE_PCF_13, false);
  1714. state.scene_shader.set_conditional(SceneShaderGLES3::USE_GI_PROBES, false);
  1715. state.scene_shader.set_conditional(SceneShaderGLES3::USE_LIGHTMAP, false);
  1716. state.scene_shader.set_conditional(SceneShaderGLES3::USE_LIGHTMAP_LAYERED, false);
  1717. state.scene_shader.set_conditional(SceneShaderGLES3::USE_LIGHTMAP_CAPTURE, false);
  1718. state.scene_shader.set_conditional(SceneShaderGLES3::USE_CONTACT_SHADOWS, false);
  1719. state.scene_shader.set_conditional(SceneShaderGLES3::USE_VERTEX_LIGHTING, false);
  1720. state.scene_shader.set_conditional(SceneShaderGLES3::USE_OPAQUE_PREPASS, false);
  1721. }
  1722. void RasterizerSceneGLES3::_add_geometry(RasterizerStorageGLES3::Geometry *p_geometry, InstanceBase *p_instance, RasterizerStorageGLES3::GeometryOwner *p_owner, int p_material, bool p_depth_pass, bool p_shadow_pass) {
  1723. RasterizerStorageGLES3::Material *m = NULL;
  1724. RID m_src = p_instance->material_override.is_valid() ? p_instance->material_override : (p_material >= 0 ? p_instance->materials[p_material] : p_geometry->material);
  1725. if (state.debug_draw == VS::VIEWPORT_DEBUG_DRAW_OVERDRAW) {
  1726. m_src = default_overdraw_material;
  1727. }
  1728. /*
  1729. #ifdef DEBUG_ENABLED
  1730. if (current_debug==VS::SCENARIO_DEBUG_OVERDRAW) {
  1731. m_src=overdraw_material;
  1732. }
  1733. #endif
  1734. */
  1735. if (m_src.is_valid()) {
  1736. m = storage->material_owner.getornull(m_src);
  1737. if (!m->shader || !m->shader->valid) {
  1738. m = NULL;
  1739. }
  1740. }
  1741. if (!m) {
  1742. m = storage->material_owner.getptr(default_material);
  1743. }
  1744. ERR_FAIL_COND(!m);
  1745. _add_geometry_with_material(p_geometry, p_instance, p_owner, m, p_depth_pass, p_shadow_pass);
  1746. while (m->next_pass.is_valid()) {
  1747. m = storage->material_owner.getornull(m->next_pass);
  1748. if (!m || !m->shader || !m->shader->valid)
  1749. break;
  1750. _add_geometry_with_material(p_geometry, p_instance, p_owner, m, p_depth_pass, p_shadow_pass);
  1751. }
  1752. }
  1753. void RasterizerSceneGLES3::_add_geometry_with_material(RasterizerStorageGLES3::Geometry *p_geometry, InstanceBase *p_instance, RasterizerStorageGLES3::GeometryOwner *p_owner, RasterizerStorageGLES3::Material *p_material, bool p_depth_pass, bool p_shadow_pass) {
  1754. bool has_base_alpha = (p_material->shader->spatial.uses_alpha && !p_material->shader->spatial.uses_alpha_scissor) || p_material->shader->spatial.uses_screen_texture || p_material->shader->spatial.uses_depth_texture;
  1755. bool has_blend_alpha = p_material->shader->spatial.blend_mode != RasterizerStorageGLES3::Shader::Spatial::BLEND_MODE_MIX;
  1756. bool has_alpha = has_base_alpha || has_blend_alpha;
  1757. bool mirror = p_instance->mirror;
  1758. bool no_cull = false;
  1759. if (p_material->shader->spatial.cull_mode == RasterizerStorageGLES3::Shader::Spatial::CULL_MODE_DISABLED) {
  1760. no_cull = true;
  1761. mirror = false;
  1762. } else if (p_material->shader->spatial.cull_mode == RasterizerStorageGLES3::Shader::Spatial::CULL_MODE_FRONT) {
  1763. mirror = !mirror;
  1764. }
  1765. if (p_material->shader->spatial.uses_sss) {
  1766. state.used_sss = true;
  1767. }
  1768. if (p_material->shader->spatial.uses_screen_texture) {
  1769. state.used_screen_texture = true;
  1770. }
  1771. if (p_material->shader->spatial.uses_depth_texture) {
  1772. state.used_depth_texture = true;
  1773. }
  1774. if (p_depth_pass) {
  1775. if (has_blend_alpha || p_material->shader->spatial.uses_depth_texture || ((has_base_alpha || p_instance->cast_shadows == VS::SHADOW_CASTING_SETTING_OFF) && p_material->shader->spatial.depth_draw_mode != RasterizerStorageGLES3::Shader::Spatial::DEPTH_DRAW_ALPHA_PREPASS) || p_material->shader->spatial.depth_draw_mode == RasterizerStorageGLES3::Shader::Spatial::DEPTH_DRAW_NEVER || p_material->shader->spatial.no_depth_test)
  1776. return; //bye
  1777. if (!p_material->shader->spatial.uses_alpha_scissor && !p_material->shader->spatial.writes_modelview_or_projection && !p_material->shader->spatial.uses_vertex && !p_material->shader->spatial.uses_discard && p_material->shader->spatial.depth_draw_mode != RasterizerStorageGLES3::Shader::Spatial::DEPTH_DRAW_ALPHA_PREPASS) {
  1778. //shader does not use discard and does not write a vertex position, use generic material
  1779. if (p_instance->cast_shadows == VS::SHADOW_CASTING_SETTING_DOUBLE_SIDED) {
  1780. p_material = storage->material_owner.getptr(!p_shadow_pass && p_material->shader->spatial.uses_world_coordinates ? default_worldcoord_material_twosided : default_material_twosided);
  1781. no_cull = true;
  1782. mirror = false;
  1783. } else {
  1784. p_material = storage->material_owner.getptr(!p_shadow_pass && p_material->shader->spatial.uses_world_coordinates ? default_worldcoord_material : default_material);
  1785. }
  1786. }
  1787. has_alpha = false;
  1788. }
  1789. RenderList::Element *e = (has_alpha || p_material->shader->spatial.no_depth_test) ? render_list.add_alpha_element() : render_list.add_element();
  1790. if (!e)
  1791. return;
  1792. e->geometry = p_geometry;
  1793. e->material = p_material;
  1794. e->instance = p_instance;
  1795. e->owner = p_owner;
  1796. e->sort_key = 0;
  1797. if (e->geometry->last_pass != render_pass) {
  1798. e->geometry->last_pass = render_pass;
  1799. e->geometry->index = current_geometry_index++;
  1800. }
  1801. // We sort only by the first directional light. The rest of directional lights will be drawn in additive passes that are skipped if disabled.
  1802. if (first_directional_light.is_valid() && light_instance_owner.owns(first_directional_light)) {
  1803. RasterizerStorageGLES3::Light *directional = light_instance_owner.getptr(first_directional_light)->light_ptr;
  1804. if ((e->instance->layer_mask & directional->cull_mask) == 0 || (e->instance->baked_light && directional->bake_mode == VS::LightBakeMode::LIGHT_BAKE_ALL)) {
  1805. e->sort_key |= SORT_KEY_NO_DIRECTIONAL_FLAG;
  1806. }
  1807. }
  1808. e->sort_key |= uint64_t(e->geometry->index) << RenderList::SORT_KEY_GEOMETRY_INDEX_SHIFT;
  1809. e->sort_key |= uint64_t(e->instance->base_type) << RenderList::SORT_KEY_GEOMETRY_TYPE_SHIFT;
  1810. if (e->material->last_pass != render_pass) {
  1811. e->material->last_pass = render_pass;
  1812. e->material->index = current_material_index++;
  1813. }
  1814. e->sort_key |= uint64_t(e->material->index) << RenderList::SORT_KEY_MATERIAL_INDEX_SHIFT;
  1815. e->sort_key |= uint64_t(e->instance->depth_layer) << RenderList::SORT_KEY_OPAQUE_DEPTH_LAYER_SHIFT;
  1816. if (!p_depth_pass) {
  1817. if (e->instance->gi_probe_instances.size()) {
  1818. e->sort_key |= SORT_KEY_GI_PROBES_FLAG;
  1819. }
  1820. if (e->instance->lightmap.is_valid()) {
  1821. e->sort_key |= SORT_KEY_LIGHTMAP_FLAG;
  1822. if (e->instance->lightmap_slice != -1) {
  1823. e->sort_key |= SORT_KEY_LIGHTMAP_LAYERED_FLAG;
  1824. }
  1825. }
  1826. if (!e->instance->lightmap_capture_data.empty()) {
  1827. e->sort_key |= SORT_KEY_LIGHTMAP_CAPTURE_FLAG;
  1828. }
  1829. e->sort_key |= (uint64_t(p_material->render_priority) + 128) << RenderList::SORT_KEY_PRIORITY_SHIFT;
  1830. }
  1831. /*
  1832. if (e->geometry->type==RasterizerStorageGLES3::Geometry::GEOMETRY_MULTISURFACE)
  1833. e->sort_flags|=RenderList::SORT_FLAG_INSTANCING;
  1834. */
  1835. if (mirror) {
  1836. e->sort_key |= RenderList::SORT_KEY_MIRROR_FLAG;
  1837. }
  1838. if (no_cull) {
  1839. e->sort_key |= RenderList::SORT_KEY_CULL_DISABLED_FLAG;
  1840. }
  1841. //e->light_type=0xFF; // no lights!
  1842. if (p_depth_pass || p_material->shader->spatial.unshaded || state.debug_draw == VS::VIEWPORT_DEBUG_DRAW_UNSHADED) {
  1843. e->sort_key |= SORT_KEY_UNSHADED_FLAG;
  1844. }
  1845. if (p_depth_pass && p_material->shader->spatial.depth_draw_mode == RasterizerStorageGLES3::Shader::Spatial::DEPTH_DRAW_ALPHA_PREPASS) {
  1846. e->sort_key |= RenderList::SORT_KEY_OPAQUE_PRE_PASS;
  1847. }
  1848. if (!p_depth_pass && (p_material->shader->spatial.uses_vertex_lighting || storage->config.force_vertex_shading)) {
  1849. e->sort_key |= SORT_KEY_VERTEX_LIT_FLAG;
  1850. }
  1851. if (p_material->shader->spatial.uses_time) {
  1852. VisualServerRaster::redraw_request();
  1853. }
  1854. }
  1855. void RasterizerSceneGLES3::_draw_sky(RasterizerStorageGLES3::Sky *p_sky, const CameraMatrix &p_projection, const Transform &p_transform, bool p_vflip, float p_custom_fov, float p_energy, const Basis &p_sky_orientation) {
  1856. ERR_FAIL_COND(!p_sky);
  1857. RasterizerStorageGLES3::Texture *tex = storage->texture_owner.getornull(p_sky->panorama);
  1858. ERR_FAIL_COND(!tex);
  1859. glActiveTexture(GL_TEXTURE0);
  1860. tex = tex->get_ptr(); //resolve for proxies
  1861. glBindTexture(tex->target, tex->tex_id);
  1862. if (storage->config.srgb_decode_supported && tex->srgb && !tex->using_srgb) {
  1863. glTexParameteri(tex->target, _TEXTURE_SRGB_DECODE_EXT, _DECODE_EXT);
  1864. tex->using_srgb = true;
  1865. #ifdef TOOLS_ENABLED
  1866. if (!(tex->flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)) {
  1867. tex->flags |= VS::TEXTURE_FLAG_CONVERT_TO_LINEAR;
  1868. //notify that texture must be set to linear beforehand, so it works in other platforms when exported
  1869. }
  1870. #endif
  1871. }
  1872. glDepthMask(GL_TRUE);
  1873. glEnable(GL_DEPTH_TEST);
  1874. glDisable(GL_CULL_FACE);
  1875. glDisable(GL_BLEND);
  1876. glDepthFunc(GL_LEQUAL);
  1877. glColorMask(1, 1, 1, 1);
  1878. // Camera
  1879. CameraMatrix camera;
  1880. if (p_custom_fov) {
  1881. float near_plane = p_projection.get_z_near();
  1882. float far_plane = p_projection.get_z_far();
  1883. float aspect = p_projection.get_aspect();
  1884. camera.set_perspective(p_custom_fov, aspect, near_plane, far_plane);
  1885. } else {
  1886. camera = p_projection;
  1887. }
  1888. float flip_sign = p_vflip ? -1 : 1;
  1889. /*
  1890. If matrix[2][0] or matrix[2][1] we're dealing with an asymmetrical projection matrix. This is the case for stereoscopic rendering (i.e. VR).
  1891. To ensure the image rendered is perspective correct we need to move some logic into the shader. For this the USE_ASYM_PANO option is introduced.
  1892. It also means the uv coordinates are ignored in this mode and we don't need our loop.
  1893. */
  1894. bool asymmetrical = ((camera.matrix[2][0] != 0.0) || (camera.matrix[2][1] != 0.0));
  1895. Vector3 vertices[8] = {
  1896. Vector3(-1, -1 * flip_sign, 1),
  1897. Vector3(0, 1, 0),
  1898. Vector3(1, -1 * flip_sign, 1),
  1899. Vector3(1, 1, 0),
  1900. Vector3(1, 1 * flip_sign, 1),
  1901. Vector3(1, 0, 0),
  1902. Vector3(-1, 1 * flip_sign, 1),
  1903. Vector3(0, 0, 0)
  1904. };
  1905. if (!asymmetrical) {
  1906. Vector2 vp_he = camera.get_viewport_half_extents();
  1907. float zn;
  1908. zn = p_projection.get_z_near();
  1909. for (int i = 0; i < 4; i++) {
  1910. Vector3 uv = vertices[i * 2 + 1];
  1911. uv.x = (uv.x * 2.0 - 1.0) * vp_he.x;
  1912. uv.y = -(uv.y * 2.0 - 1.0) * vp_he.y;
  1913. uv.z = -zn;
  1914. vertices[i * 2 + 1] = p_transform.basis.xform(uv).normalized();
  1915. vertices[i * 2 + 1].z = -vertices[i * 2 + 1].z;
  1916. }
  1917. }
  1918. glBindBuffer(GL_ARRAY_BUFFER, state.sky_verts);
  1919. glBufferData(GL_ARRAY_BUFFER, sizeof(Vector3) * 8, vertices, GL_DYNAMIC_DRAW);
  1920. glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind
  1921. glBindVertexArray(state.sky_array);
  1922. storage->shaders.copy.set_conditional(CopyShaderGLES3::USE_ASYM_PANO, asymmetrical);
  1923. storage->shaders.copy.set_conditional(CopyShaderGLES3::USE_PANORAMA, !asymmetrical);
  1924. storage->shaders.copy.set_conditional(CopyShaderGLES3::USE_MULTIPLIER, true);
  1925. storage->shaders.copy.bind();
  1926. storage->shaders.copy.set_uniform(CopyShaderGLES3::MULTIPLIER, p_energy);
  1927. // don't know why but I always have problems setting a uniform mat3, so we're using a transform
  1928. storage->shaders.copy.set_uniform(CopyShaderGLES3::SKY_TRANSFORM, Transform(p_sky_orientation, Vector3(0.0, 0.0, 0.0)).affine_inverse());
  1929. if (asymmetrical) {
  1930. // pack the bits we need from our projection matrix
  1931. storage->shaders.copy.set_uniform(CopyShaderGLES3::ASYM_PROJ, camera.matrix[2][0], camera.matrix[0][0], camera.matrix[2][1], camera.matrix[1][1]);
  1932. ///@TODO I couldn't get mat3 + p_transform.basis to work, that would be better here.
  1933. storage->shaders.copy.set_uniform(CopyShaderGLES3::PANO_TRANSFORM, p_transform);
  1934. }
  1935. glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
  1936. glBindVertexArray(0);
  1937. glColorMask(1, 1, 1, 1);
  1938. storage->shaders.copy.set_conditional(CopyShaderGLES3::USE_ASYM_PANO, false);
  1939. storage->shaders.copy.set_conditional(CopyShaderGLES3::USE_MULTIPLIER, false);
  1940. storage->shaders.copy.set_conditional(CopyShaderGLES3::USE_PANORAMA, false);
  1941. }
  1942. void RasterizerSceneGLES3::_setup_environment(Environment *env, const CameraMatrix &p_cam_projection, const Transform &p_cam_transform, bool p_no_fog) {
  1943. Transform sky_orientation;
  1944. //store camera into ubo
  1945. store_camera(p_cam_projection, state.ubo_data.projection_matrix);
  1946. store_camera(p_cam_projection.inverse(), state.ubo_data.inv_projection_matrix);
  1947. store_transform(p_cam_transform, state.ubo_data.camera_matrix);
  1948. store_transform(p_cam_transform.affine_inverse(), state.ubo_data.camera_inverse_matrix);
  1949. //time global variables
  1950. state.ubo_data.time = storage->frame.time[0];
  1951. state.ubo_data.z_far = p_cam_projection.get_z_far();
  1952. //bg and ambient
  1953. if (env) {
  1954. state.ubo_data.bg_energy = env->bg_energy;
  1955. state.ubo_data.ambient_energy = env->ambient_energy;
  1956. Color linear_ambient_color = env->ambient_color.to_linear();
  1957. state.ubo_data.ambient_light_color[0] = linear_ambient_color.r;
  1958. state.ubo_data.ambient_light_color[1] = linear_ambient_color.g;
  1959. state.ubo_data.ambient_light_color[2] = linear_ambient_color.b;
  1960. state.ubo_data.ambient_light_color[3] = linear_ambient_color.a;
  1961. Color bg_color;
  1962. switch (env->bg_mode) {
  1963. case VS::ENV_BG_CLEAR_COLOR: {
  1964. bg_color = storage->frame.clear_request_color.to_linear();
  1965. } break;
  1966. case VS::ENV_BG_COLOR: {
  1967. bg_color = env->bg_color.to_linear();
  1968. } break;
  1969. default: {
  1970. bg_color = Color(0, 0, 0, 1);
  1971. } break;
  1972. }
  1973. state.ubo_data.bg_color[0] = bg_color.r;
  1974. state.ubo_data.bg_color[1] = bg_color.g;
  1975. state.ubo_data.bg_color[2] = bg_color.b;
  1976. state.ubo_data.bg_color[3] = bg_color.a;
  1977. //use the inverse of our sky_orientation, we may need to skip this if we're using a reflection probe?
  1978. sky_orientation = Transform(env->sky_orientation, Vector3(0.0, 0.0, 0.0)).affine_inverse();
  1979. state.env_radiance_data.ambient_contribution = env->ambient_sky_contribution;
  1980. state.ubo_data.ambient_occlusion_affect_light = env->ssao_light_affect;
  1981. state.ubo_data.ambient_occlusion_affect_ssao = env->ssao_ao_channel_affect;
  1982. //fog
  1983. Color linear_fog = env->fog_color.to_linear();
  1984. state.ubo_data.fog_color_enabled[0] = linear_fog.r;
  1985. state.ubo_data.fog_color_enabled[1] = linear_fog.g;
  1986. state.ubo_data.fog_color_enabled[2] = linear_fog.b;
  1987. state.ubo_data.fog_color_enabled[3] = (!p_no_fog && env->fog_enabled) ? 1.0 : 0.0;
  1988. state.ubo_data.fog_density = linear_fog.a;
  1989. Color linear_sun = env->fog_sun_color.to_linear();
  1990. state.ubo_data.fog_sun_color_amount[0] = linear_sun.r;
  1991. state.ubo_data.fog_sun_color_amount[1] = linear_sun.g;
  1992. state.ubo_data.fog_sun_color_amount[2] = linear_sun.b;
  1993. state.ubo_data.fog_sun_color_amount[3] = env->fog_sun_amount;
  1994. state.ubo_data.fog_depth_enabled = env->fog_depth_enabled;
  1995. state.ubo_data.fog_depth_begin = env->fog_depth_begin;
  1996. state.ubo_data.fog_depth_end = env->fog_depth_end;
  1997. state.ubo_data.fog_depth_curve = env->fog_depth_curve;
  1998. state.ubo_data.fog_transmit_enabled = env->fog_transmit_enabled;
  1999. state.ubo_data.fog_transmit_curve = env->fog_transmit_curve;
  2000. state.ubo_data.fog_height_enabled = env->fog_height_enabled;
  2001. state.ubo_data.fog_height_min = env->fog_height_min;
  2002. state.ubo_data.fog_height_max = env->fog_height_max;
  2003. state.ubo_data.fog_height_curve = env->fog_height_curve;
  2004. } else {
  2005. state.ubo_data.bg_energy = 1.0;
  2006. state.ubo_data.ambient_energy = 1.0;
  2007. //use from clear color instead, since there is no ambient
  2008. Color linear_ambient_color = storage->frame.clear_request_color.to_linear();
  2009. state.ubo_data.ambient_light_color[0] = linear_ambient_color.r;
  2010. state.ubo_data.ambient_light_color[1] = linear_ambient_color.g;
  2011. state.ubo_data.ambient_light_color[2] = linear_ambient_color.b;
  2012. state.ubo_data.ambient_light_color[3] = linear_ambient_color.a;
  2013. state.ubo_data.bg_color[0] = linear_ambient_color.r;
  2014. state.ubo_data.bg_color[1] = linear_ambient_color.g;
  2015. state.ubo_data.bg_color[2] = linear_ambient_color.b;
  2016. state.ubo_data.bg_color[3] = linear_ambient_color.a;
  2017. state.env_radiance_data.ambient_contribution = 0;
  2018. state.ubo_data.ambient_occlusion_affect_light = 0;
  2019. state.ubo_data.fog_color_enabled[3] = 0.0;
  2020. }
  2021. {
  2022. //directional shadow
  2023. state.ubo_data.shadow_directional_pixel_size[0] = 1.0 / directional_shadow.size;
  2024. state.ubo_data.shadow_directional_pixel_size[1] = 1.0 / directional_shadow.size;
  2025. glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 4);
  2026. glBindTexture(GL_TEXTURE_2D, directional_shadow.depth);
  2027. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
  2028. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LESS);
  2029. }
  2030. glBindBuffer(GL_UNIFORM_BUFFER, state.scene_ubo);
  2031. glBufferData(GL_UNIFORM_BUFFER, sizeof(State::SceneDataUBO), &state.ubo_data, GL_DYNAMIC_DRAW);
  2032. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  2033. //fill up environment
  2034. store_transform(sky_orientation * p_cam_transform, state.env_radiance_data.transform);
  2035. glBindBuffer(GL_UNIFORM_BUFFER, state.env_radiance_ubo);
  2036. glBufferData(GL_UNIFORM_BUFFER, sizeof(State::EnvironmentRadianceUBO), &state.env_radiance_data, GL_DYNAMIC_DRAW);
  2037. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  2038. }
  2039. void RasterizerSceneGLES3::_setup_directional_light(int p_index, const Transform &p_camera_inverse_transform, bool p_use_shadows) {
  2040. LightInstance *li = directional_lights[p_index];
  2041. LightDataUBO ubo_data; //used for filling
  2042. float sign = li->light_ptr->negative ? -1 : 1;
  2043. Color linear_col = li->light_ptr->color.to_linear();
  2044. //compensate normalized diffuse range by multiplying by PI
  2045. ubo_data.light_color_energy[0] = linear_col.r * sign * li->light_ptr->param[VS::LIGHT_PARAM_ENERGY] * Math_PI;
  2046. ubo_data.light_color_energy[1] = linear_col.g * sign * li->light_ptr->param[VS::LIGHT_PARAM_ENERGY] * Math_PI;
  2047. ubo_data.light_color_energy[2] = linear_col.b * sign * li->light_ptr->param[VS::LIGHT_PARAM_ENERGY] * Math_PI;
  2048. ubo_data.light_color_energy[3] = 0;
  2049. //omni, keep at 0
  2050. ubo_data.light_pos_inv_radius[0] = 0.0;
  2051. ubo_data.light_pos_inv_radius[1] = 0.0;
  2052. ubo_data.light_pos_inv_radius[2] = 0.0;
  2053. ubo_data.light_pos_inv_radius[3] = 0.0;
  2054. Vector3 direction = p_camera_inverse_transform.basis.xform(li->transform.basis.xform(Vector3(0, 0, -1))).normalized();
  2055. ubo_data.light_direction_attenuation[0] = direction.x;
  2056. ubo_data.light_direction_attenuation[1] = direction.y;
  2057. ubo_data.light_direction_attenuation[2] = direction.z;
  2058. ubo_data.light_direction_attenuation[3] = 1.0;
  2059. ubo_data.light_params[0] = 0;
  2060. ubo_data.light_params[1] = 0;
  2061. ubo_data.light_params[2] = li->light_ptr->param[VS::LIGHT_PARAM_SPECULAR];
  2062. ubo_data.light_params[3] = 0;
  2063. Color shadow_color = li->light_ptr->shadow_color.to_linear();
  2064. ubo_data.light_shadow_color_contact[0] = shadow_color.r;
  2065. ubo_data.light_shadow_color_contact[1] = shadow_color.g;
  2066. ubo_data.light_shadow_color_contact[2] = shadow_color.b;
  2067. ubo_data.light_shadow_color_contact[3] = li->light_ptr->param[VS::LIGHT_PARAM_CONTACT_SHADOW_SIZE];
  2068. if (p_use_shadows && li->light_ptr->shadow) {
  2069. int shadow_count = 0;
  2070. switch (li->light_ptr->directional_shadow_mode) {
  2071. case VS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL: {
  2072. shadow_count = 1;
  2073. } break;
  2074. case VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS: {
  2075. shadow_count = 2;
  2076. } break;
  2077. case VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS: {
  2078. shadow_count = 4;
  2079. } break;
  2080. }
  2081. for (int j = 0; j < shadow_count; j++) {
  2082. uint32_t x = li->directional_rect.position.x;
  2083. uint32_t y = li->directional_rect.position.y;
  2084. uint32_t width = li->directional_rect.size.x;
  2085. uint32_t height = li->directional_rect.size.y;
  2086. if (li->light_ptr->directional_shadow_mode == VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS) {
  2087. width /= 2;
  2088. height /= 2;
  2089. if (j == 1) {
  2090. x += width;
  2091. } else if (j == 2) {
  2092. y += height;
  2093. } else if (j == 3) {
  2094. x += width;
  2095. y += height;
  2096. }
  2097. } else if (li->light_ptr->directional_shadow_mode == VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS) {
  2098. height /= 2;
  2099. if (j != 0) {
  2100. y += height;
  2101. }
  2102. }
  2103. ubo_data.shadow_split_offsets[j] = li->shadow_transform[j].split;
  2104. Transform modelview = (p_camera_inverse_transform * li->shadow_transform[j].transform).affine_inverse();
  2105. CameraMatrix bias;
  2106. bias.set_light_bias();
  2107. CameraMatrix rectm;
  2108. Rect2 atlas_rect = Rect2(float(x) / directional_shadow.size, float(y) / directional_shadow.size, float(width) / directional_shadow.size, float(height) / directional_shadow.size);
  2109. rectm.set_light_atlas_rect(atlas_rect);
  2110. CameraMatrix shadow_mtx = rectm * bias * li->shadow_transform[j].camera * modelview;
  2111. store_camera(shadow_mtx, &ubo_data.shadow.matrix[16 * j]);
  2112. ubo_data.light_clamp[0] = atlas_rect.position.x;
  2113. ubo_data.light_clamp[1] = atlas_rect.position.y;
  2114. ubo_data.light_clamp[2] = atlas_rect.size.x;
  2115. ubo_data.light_clamp[3] = atlas_rect.size.y;
  2116. }
  2117. }
  2118. glBindBuffer(GL_UNIFORM_BUFFER, state.directional_ubo);
  2119. glBufferData(GL_UNIFORM_BUFFER, sizeof(LightDataUBO), &ubo_data, GL_DYNAMIC_DRAW);
  2120. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  2121. directional_light = li;
  2122. glBindBufferBase(GL_UNIFORM_BUFFER, 3, state.directional_ubo);
  2123. }
  2124. void RasterizerSceneGLES3::_setup_lights(RID *p_light_cull_result, int p_light_cull_count, const Transform &p_camera_inverse_transform, const CameraMatrix &p_camera_projection, RID p_shadow_atlas) {
  2125. state.omni_light_count = 0;
  2126. state.spot_light_count = 0;
  2127. state.directional_light_count = 0;
  2128. directional_light = NULL;
  2129. first_directional_light = RID();
  2130. ShadowAtlas *shadow_atlas = shadow_atlas_owner.getornull(p_shadow_atlas);
  2131. for (int i = 0; i < p_light_cull_count; i++) {
  2132. ERR_BREAK(i >= render_list.max_lights);
  2133. LightInstance *li = light_instance_owner.getptr(p_light_cull_result[i]);
  2134. LightDataUBO ubo_data; //used for filling
  2135. switch (li->light_ptr->type) {
  2136. case VS::LIGHT_DIRECTIONAL: {
  2137. if (state.directional_light_count == 0) {
  2138. first_directional_light = p_light_cull_result[i];
  2139. }
  2140. if (state.directional_light_count < RenderList::MAX_DIRECTIONAL_LIGHTS) {
  2141. directional_lights[state.directional_light_count++] = li;
  2142. }
  2143. } break;
  2144. case VS::LIGHT_OMNI: {
  2145. float sign = li->light_ptr->negative ? -1 : 1;
  2146. Color linear_col = li->light_ptr->color.to_linear();
  2147. ubo_data.light_color_energy[0] = linear_col.r * sign * li->light_ptr->param[VS::LIGHT_PARAM_ENERGY] * Math_PI;
  2148. ubo_data.light_color_energy[1] = linear_col.g * sign * li->light_ptr->param[VS::LIGHT_PARAM_ENERGY] * Math_PI;
  2149. ubo_data.light_color_energy[2] = linear_col.b * sign * li->light_ptr->param[VS::LIGHT_PARAM_ENERGY] * Math_PI;
  2150. ubo_data.light_color_energy[3] = 0;
  2151. Vector3 pos = p_camera_inverse_transform.xform(li->transform.origin);
  2152. //directional, keep at 0
  2153. ubo_data.light_pos_inv_radius[0] = pos.x;
  2154. ubo_data.light_pos_inv_radius[1] = pos.y;
  2155. ubo_data.light_pos_inv_radius[2] = pos.z;
  2156. ubo_data.light_pos_inv_radius[3] = 1.0 / MAX(0.001, li->light_ptr->param[VS::LIGHT_PARAM_RANGE]);
  2157. ubo_data.light_direction_attenuation[0] = 0;
  2158. ubo_data.light_direction_attenuation[1] = 0;
  2159. ubo_data.light_direction_attenuation[2] = 0;
  2160. ubo_data.light_direction_attenuation[3] = li->light_ptr->param[VS::LIGHT_PARAM_ATTENUATION];
  2161. ubo_data.light_params[0] = 0;
  2162. ubo_data.light_params[1] = 0;
  2163. ubo_data.light_params[2] = li->light_ptr->param[VS::LIGHT_PARAM_SPECULAR];
  2164. ubo_data.light_params[3] = 0;
  2165. Color shadow_color = li->light_ptr->shadow_color.to_linear();
  2166. ubo_data.light_shadow_color_contact[0] = shadow_color.r;
  2167. ubo_data.light_shadow_color_contact[1] = shadow_color.g;
  2168. ubo_data.light_shadow_color_contact[2] = shadow_color.b;
  2169. ubo_data.light_shadow_color_contact[3] = li->light_ptr->param[VS::LIGHT_PARAM_CONTACT_SHADOW_SIZE];
  2170. if (li->light_ptr->shadow && shadow_atlas && shadow_atlas->shadow_owners.has(li->self)) {
  2171. // fill in the shadow information
  2172. uint32_t key = shadow_atlas->shadow_owners[li->self];
  2173. uint32_t quadrant = (key >> ShadowAtlas::QUADRANT_SHIFT) & 0x3;
  2174. uint32_t shadow = key & ShadowAtlas::SHADOW_INDEX_MASK;
  2175. ERR_CONTINUE(shadow >= (uint32_t)shadow_atlas->quadrants[quadrant].shadows.size());
  2176. uint32_t atlas_size = shadow_atlas->size;
  2177. uint32_t quadrant_size = atlas_size >> 1;
  2178. uint32_t x = (quadrant & 1) * quadrant_size;
  2179. uint32_t y = (quadrant >> 1) * quadrant_size;
  2180. uint32_t shadow_size = (quadrant_size / shadow_atlas->quadrants[quadrant].subdivision);
  2181. x += (shadow % shadow_atlas->quadrants[quadrant].subdivision) * shadow_size;
  2182. y += (shadow / shadow_atlas->quadrants[quadrant].subdivision) * shadow_size;
  2183. uint32_t width = shadow_size;
  2184. uint32_t height = shadow_size;
  2185. if (li->light_ptr->omni_shadow_detail == VS::LIGHT_OMNI_SHADOW_DETAIL_HORIZONTAL) {
  2186. height /= 2;
  2187. } else {
  2188. width /= 2;
  2189. }
  2190. Transform proj = (p_camera_inverse_transform * li->transform).inverse();
  2191. store_transform(proj, ubo_data.shadow.matrix1);
  2192. ubo_data.light_params[3] = 1.0; //means it has shadow
  2193. ubo_data.light_clamp[0] = float(x) / atlas_size;
  2194. ubo_data.light_clamp[1] = float(y) / atlas_size;
  2195. ubo_data.light_clamp[2] = float(width) / atlas_size;
  2196. ubo_data.light_clamp[3] = float(height) / atlas_size;
  2197. }
  2198. li->light_index = state.omni_light_count;
  2199. copymem(&state.omni_array_tmp[li->light_index * state.ubo_light_size], &ubo_data, state.ubo_light_size);
  2200. state.omni_light_count++;
  2201. } break;
  2202. case VS::LIGHT_SPOT: {
  2203. float sign = li->light_ptr->negative ? -1 : 1;
  2204. Color linear_col = li->light_ptr->color.to_linear();
  2205. ubo_data.light_color_energy[0] = linear_col.r * sign * li->light_ptr->param[VS::LIGHT_PARAM_ENERGY] * Math_PI;
  2206. ubo_data.light_color_energy[1] = linear_col.g * sign * li->light_ptr->param[VS::LIGHT_PARAM_ENERGY] * Math_PI;
  2207. ubo_data.light_color_energy[2] = linear_col.b * sign * li->light_ptr->param[VS::LIGHT_PARAM_ENERGY] * Math_PI;
  2208. ubo_data.light_color_energy[3] = 0;
  2209. Vector3 pos = p_camera_inverse_transform.xform(li->transform.origin);
  2210. //directional, keep at 0
  2211. ubo_data.light_pos_inv_radius[0] = pos.x;
  2212. ubo_data.light_pos_inv_radius[1] = pos.y;
  2213. ubo_data.light_pos_inv_radius[2] = pos.z;
  2214. ubo_data.light_pos_inv_radius[3] = 1.0 / MAX(0.001, li->light_ptr->param[VS::LIGHT_PARAM_RANGE]);
  2215. Vector3 direction = p_camera_inverse_transform.basis.xform(li->transform.basis.xform(Vector3(0, 0, -1))).normalized();
  2216. ubo_data.light_direction_attenuation[0] = direction.x;
  2217. ubo_data.light_direction_attenuation[1] = direction.y;
  2218. ubo_data.light_direction_attenuation[2] = direction.z;
  2219. ubo_data.light_direction_attenuation[3] = li->light_ptr->param[VS::LIGHT_PARAM_ATTENUATION];
  2220. ubo_data.light_params[0] = li->light_ptr->param[VS::LIGHT_PARAM_SPOT_ATTENUATION];
  2221. ubo_data.light_params[1] = Math::cos(Math::deg2rad(li->light_ptr->param[VS::LIGHT_PARAM_SPOT_ANGLE]));
  2222. ubo_data.light_params[2] = li->light_ptr->param[VS::LIGHT_PARAM_SPECULAR];
  2223. ubo_data.light_params[3] = 0;
  2224. Color shadow_color = li->light_ptr->shadow_color.to_linear();
  2225. ubo_data.light_shadow_color_contact[0] = shadow_color.r;
  2226. ubo_data.light_shadow_color_contact[1] = shadow_color.g;
  2227. ubo_data.light_shadow_color_contact[2] = shadow_color.b;
  2228. ubo_data.light_shadow_color_contact[3] = li->light_ptr->param[VS::LIGHT_PARAM_CONTACT_SHADOW_SIZE];
  2229. if (li->light_ptr->shadow && shadow_atlas && shadow_atlas->shadow_owners.has(li->self)) {
  2230. // fill in the shadow information
  2231. uint32_t key = shadow_atlas->shadow_owners[li->self];
  2232. uint32_t quadrant = (key >> ShadowAtlas::QUADRANT_SHIFT) & 0x3;
  2233. uint32_t shadow = key & ShadowAtlas::SHADOW_INDEX_MASK;
  2234. ERR_CONTINUE(shadow >= (uint32_t)shadow_atlas->quadrants[quadrant].shadows.size());
  2235. uint32_t atlas_size = shadow_atlas->size;
  2236. uint32_t quadrant_size = atlas_size >> 1;
  2237. uint32_t x = (quadrant & 1) * quadrant_size;
  2238. uint32_t y = (quadrant >> 1) * quadrant_size;
  2239. uint32_t shadow_size = (quadrant_size / shadow_atlas->quadrants[quadrant].subdivision);
  2240. x += (shadow % shadow_atlas->quadrants[quadrant].subdivision) * shadow_size;
  2241. y += (shadow / shadow_atlas->quadrants[quadrant].subdivision) * shadow_size;
  2242. uint32_t width = shadow_size;
  2243. uint32_t height = shadow_size;
  2244. Rect2 rect(float(x) / atlas_size, float(y) / atlas_size, float(width) / atlas_size, float(height) / atlas_size);
  2245. ubo_data.light_params[3] = 1.0; //means it has shadow
  2246. ubo_data.light_clamp[0] = rect.position.x;
  2247. ubo_data.light_clamp[1] = rect.position.y;
  2248. ubo_data.light_clamp[2] = rect.size.x;
  2249. ubo_data.light_clamp[3] = rect.size.y;
  2250. Transform modelview = (p_camera_inverse_transform * li->transform).inverse();
  2251. CameraMatrix bias;
  2252. bias.set_light_bias();
  2253. CameraMatrix rectm;
  2254. rectm.set_light_atlas_rect(rect);
  2255. CameraMatrix shadow_mtx = rectm * bias * li->shadow_transform[0].camera * modelview;
  2256. store_camera(shadow_mtx, ubo_data.shadow.matrix1);
  2257. }
  2258. li->light_index = state.spot_light_count;
  2259. copymem(&state.spot_array_tmp[li->light_index * state.ubo_light_size], &ubo_data, state.ubo_light_size);
  2260. state.spot_light_count++;
  2261. } break;
  2262. }
  2263. li->last_pass = render_pass;
  2264. //update UBO for forward rendering, blit to texture for clustered
  2265. }
  2266. if (state.omni_light_count) {
  2267. glBindBuffer(GL_UNIFORM_BUFFER, state.omni_array_ubo);
  2268. glBufferSubData(GL_UNIFORM_BUFFER, 0, state.omni_light_count * state.ubo_light_size, state.omni_array_tmp);
  2269. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  2270. }
  2271. glBindBufferBase(GL_UNIFORM_BUFFER, 4, state.omni_array_ubo);
  2272. if (state.spot_light_count) {
  2273. glBindBuffer(GL_UNIFORM_BUFFER, state.spot_array_ubo);
  2274. glBufferSubData(GL_UNIFORM_BUFFER, 0, state.spot_light_count * state.ubo_light_size, state.spot_array_tmp);
  2275. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  2276. }
  2277. glBindBufferBase(GL_UNIFORM_BUFFER, 5, state.spot_array_ubo);
  2278. }
  2279. void RasterizerSceneGLES3::_setup_reflections(RID *p_reflection_probe_cull_result, int p_reflection_probe_cull_count, const Transform &p_camera_inverse_transform, const CameraMatrix &p_camera_projection, RID p_reflection_atlas, Environment *p_env) {
  2280. state.reflection_probe_count = 0;
  2281. for (int i = 0; i < p_reflection_probe_cull_count; i++) {
  2282. ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_reflection_probe_cull_result[i]);
  2283. ERR_CONTINUE(!rpi);
  2284. ReflectionAtlas *reflection_atlas = reflection_atlas_owner.getornull(p_reflection_atlas);
  2285. ERR_CONTINUE(!reflection_atlas);
  2286. ERR_CONTINUE(rpi->reflection_atlas_index < 0);
  2287. if (state.reflection_probe_count >= state.max_ubo_reflections)
  2288. break;
  2289. rpi->last_pass = render_pass;
  2290. ReflectionProbeDataUBO reflection_ubo;
  2291. reflection_ubo.box_extents[0] = rpi->probe_ptr->extents.x;
  2292. reflection_ubo.box_extents[1] = rpi->probe_ptr->extents.y;
  2293. reflection_ubo.box_extents[2] = rpi->probe_ptr->extents.z;
  2294. reflection_ubo.box_extents[3] = 0;
  2295. reflection_ubo.box_ofs[0] = rpi->probe_ptr->origin_offset.x;
  2296. reflection_ubo.box_ofs[1] = rpi->probe_ptr->origin_offset.y;
  2297. reflection_ubo.box_ofs[2] = rpi->probe_ptr->origin_offset.z;
  2298. reflection_ubo.box_ofs[3] = 0;
  2299. reflection_ubo.params[0] = rpi->probe_ptr->intensity;
  2300. reflection_ubo.params[1] = 0;
  2301. reflection_ubo.params[2] = rpi->probe_ptr->interior ? 1.0 : 0.0;
  2302. reflection_ubo.params[3] = rpi->probe_ptr->box_projection ? 1.0 : 0.0;
  2303. if (rpi->probe_ptr->interior) {
  2304. Color ambient_linear = rpi->probe_ptr->interior_ambient.to_linear();
  2305. reflection_ubo.ambient[0] = ambient_linear.r * rpi->probe_ptr->interior_ambient_energy;
  2306. reflection_ubo.ambient[1] = ambient_linear.g * rpi->probe_ptr->interior_ambient_energy;
  2307. reflection_ubo.ambient[2] = ambient_linear.b * rpi->probe_ptr->interior_ambient_energy;
  2308. reflection_ubo.ambient[3] = rpi->probe_ptr->interior_ambient_probe_contrib;
  2309. } else {
  2310. Color ambient_linear;
  2311. if (p_env) {
  2312. ambient_linear = p_env->ambient_color.to_linear();
  2313. ambient_linear.r *= p_env->ambient_energy;
  2314. ambient_linear.g *= p_env->ambient_energy;
  2315. ambient_linear.b *= p_env->ambient_energy;
  2316. }
  2317. reflection_ubo.ambient[0] = ambient_linear.r;
  2318. reflection_ubo.ambient[1] = ambient_linear.g;
  2319. reflection_ubo.ambient[2] = ambient_linear.b;
  2320. reflection_ubo.ambient[3] = 0; //not used in exterior mode, since it just blends with regular ambient light
  2321. }
  2322. int cell_size = reflection_atlas->size / reflection_atlas->subdiv;
  2323. int x = (rpi->reflection_atlas_index % reflection_atlas->subdiv) * cell_size;
  2324. int y = (rpi->reflection_atlas_index / reflection_atlas->subdiv) * cell_size;
  2325. int width = cell_size;
  2326. int height = cell_size;
  2327. reflection_ubo.atlas_clamp[0] = float(x) / reflection_atlas->size;
  2328. reflection_ubo.atlas_clamp[1] = float(y) / reflection_atlas->size;
  2329. reflection_ubo.atlas_clamp[2] = float(width) / reflection_atlas->size;
  2330. reflection_ubo.atlas_clamp[3] = float(height) / reflection_atlas->size;
  2331. Transform proj = (p_camera_inverse_transform * rpi->transform).inverse();
  2332. store_transform(proj, reflection_ubo.local_matrix);
  2333. rpi->reflection_index = state.reflection_probe_count;
  2334. copymem(&state.reflection_array_tmp[rpi->reflection_index * sizeof(ReflectionProbeDataUBO)], &reflection_ubo, sizeof(ReflectionProbeDataUBO));
  2335. state.reflection_probe_count++;
  2336. }
  2337. if (state.reflection_probe_count) {
  2338. glBindBuffer(GL_UNIFORM_BUFFER, state.reflection_array_ubo);
  2339. glBufferSubData(GL_UNIFORM_BUFFER, 0, state.reflection_probe_count * sizeof(ReflectionProbeDataUBO), state.reflection_array_tmp);
  2340. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  2341. }
  2342. glBindBufferBase(GL_UNIFORM_BUFFER, 6, state.reflection_array_ubo);
  2343. }
  2344. void RasterizerSceneGLES3::_copy_screen(bool p_invalidate_color, bool p_invalidate_depth) {
  2345. #ifndef GLES_OVER_GL
  2346. if (p_invalidate_color) {
  2347. GLenum attachments[2] = {
  2348. GL_COLOR_ATTACHMENT0,
  2349. GL_DEPTH_ATTACHMENT
  2350. };
  2351. glInvalidateFramebuffer(GL_FRAMEBUFFER, p_invalidate_depth ? 2 : 1, attachments);
  2352. }
  2353. #endif
  2354. glBindVertexArray(storage->resources.quadie_array);
  2355. glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
  2356. glBindVertexArray(0);
  2357. }
  2358. void RasterizerSceneGLES3::_copy_texture_to_front_buffer(GLuint p_texture) {
  2359. //copy to front buffer
  2360. glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->fbo);
  2361. glDepthMask(GL_FALSE);
  2362. glDisable(GL_DEPTH_TEST);
  2363. glDisable(GL_CULL_FACE);
  2364. glDisable(GL_BLEND);
  2365. glDepthFunc(GL_LEQUAL);
  2366. glColorMask(1, 1, 1, 1);
  2367. glActiveTexture(GL_TEXTURE0);
  2368. glBindTexture(GL_TEXTURE_2D, p_texture);
  2369. glViewport(0, 0, storage->frame.current_rt->width * 0.5, storage->frame.current_rt->height * 0.5);
  2370. storage->shaders.copy.set_conditional(CopyShaderGLES3::DISABLE_ALPHA, true);
  2371. storage->shaders.copy.bind();
  2372. _copy_screen();
  2373. //turn off everything used
  2374. storage->shaders.copy.set_conditional(CopyShaderGLES3::LINEAR_TO_SRGB, false);
  2375. storage->shaders.copy.set_conditional(CopyShaderGLES3::DISABLE_ALPHA, false);
  2376. }
  2377. void RasterizerSceneGLES3::_fill_render_list(InstanceBase **p_cull_result, int p_cull_count, bool p_depth_pass, bool p_shadow_pass) {
  2378. current_geometry_index = 0;
  2379. current_material_index = 0;
  2380. state.used_sss = false;
  2381. state.used_screen_texture = false;
  2382. state.used_depth_texture = false;
  2383. //fill list
  2384. for (int i = 0; i < p_cull_count; i++) {
  2385. InstanceBase *inst = p_cull_result[i];
  2386. switch (inst->base_type) {
  2387. case VS::INSTANCE_MESH: {
  2388. RasterizerStorageGLES3::Mesh *mesh = storage->mesh_owner.getptr(inst->base);
  2389. ERR_CONTINUE(!mesh);
  2390. int ssize = mesh->surfaces.size();
  2391. for (int j = 0; j < ssize; j++) {
  2392. int mat_idx = inst->materials[j].is_valid() ? j : -1;
  2393. RasterizerStorageGLES3::Surface *s = mesh->surfaces[j];
  2394. _add_geometry(s, inst, NULL, mat_idx, p_depth_pass, p_shadow_pass);
  2395. }
  2396. //mesh->last_pass=frame;
  2397. } break;
  2398. case VS::INSTANCE_MULTIMESH: {
  2399. RasterizerStorageGLES3::MultiMesh *multi_mesh = storage->multimesh_owner.getptr(inst->base);
  2400. ERR_CONTINUE(!multi_mesh);
  2401. if (multi_mesh->size == 0 || multi_mesh->visible_instances == 0)
  2402. continue;
  2403. RasterizerStorageGLES3::Mesh *mesh = storage->mesh_owner.getptr(multi_mesh->mesh);
  2404. if (!mesh)
  2405. continue; //mesh not assigned
  2406. int ssize = mesh->surfaces.size();
  2407. for (int j = 0; j < ssize; j++) {
  2408. RasterizerStorageGLES3::Surface *s = mesh->surfaces[j];
  2409. _add_geometry(s, inst, multi_mesh, -1, p_depth_pass, p_shadow_pass);
  2410. }
  2411. } break;
  2412. case VS::INSTANCE_IMMEDIATE: {
  2413. RasterizerStorageGLES3::Immediate *immediate = storage->immediate_owner.getptr(inst->base);
  2414. ERR_CONTINUE(!immediate);
  2415. _add_geometry(immediate, inst, NULL, -1, p_depth_pass, p_shadow_pass);
  2416. } break;
  2417. case VS::INSTANCE_PARTICLES: {
  2418. RasterizerStorageGLES3::Particles *particles = storage->particles_owner.getptr(inst->base);
  2419. ERR_CONTINUE(!particles);
  2420. for (int j = 0; j < particles->draw_passes.size(); j++) {
  2421. RID pmesh = particles->draw_passes[j];
  2422. if (!pmesh.is_valid())
  2423. continue;
  2424. RasterizerStorageGLES3::Mesh *mesh = storage->mesh_owner.get(pmesh);
  2425. if (!mesh)
  2426. continue; //mesh not assigned
  2427. int ssize = mesh->surfaces.size();
  2428. for (int k = 0; k < ssize; k++) {
  2429. RasterizerStorageGLES3::Surface *s = mesh->surfaces[k];
  2430. _add_geometry(s, inst, particles, -1, p_depth_pass, p_shadow_pass);
  2431. }
  2432. }
  2433. } break;
  2434. default: {
  2435. }
  2436. }
  2437. }
  2438. }
  2439. void RasterizerSceneGLES3::_blur_effect_buffer() {
  2440. //blur diffuse into effect mipmaps using separatable convolution
  2441. //storage->shaders.copy.set_conditional(CopyShaderGLES3::GAUSSIAN_HORIZONTAL,true);
  2442. for (int i = 0; i < storage->frame.current_rt->effects.mip_maps[1].sizes.size(); i++) {
  2443. int vp_w = storage->frame.current_rt->effects.mip_maps[1].sizes[i].width;
  2444. int vp_h = storage->frame.current_rt->effects.mip_maps[1].sizes[i].height;
  2445. glViewport(0, 0, vp_w, vp_h);
  2446. //horizontal pass
  2447. state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GAUSSIAN_HORIZONTAL, true);
  2448. state.effect_blur_shader.bind();
  2449. state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::PIXEL_SIZE, Vector2(1.0 / vp_w, 1.0 / vp_h));
  2450. state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::LOD, float(i));
  2451. glActiveTexture(GL_TEXTURE0);
  2452. glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.mip_maps[0].color); //previous level, since mipmaps[0] starts one level bigger
  2453. glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->effects.mip_maps[1].sizes[i].fbo);
  2454. _copy_screen(true);
  2455. state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GAUSSIAN_HORIZONTAL, false);
  2456. //vertical pass
  2457. state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GAUSSIAN_VERTICAL, true);
  2458. state.effect_blur_shader.bind();
  2459. state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::PIXEL_SIZE, Vector2(1.0 / vp_w, 1.0 / vp_h));
  2460. state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::LOD, float(i));
  2461. glActiveTexture(GL_TEXTURE0);
  2462. glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.mip_maps[1].color);
  2463. glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->effects.mip_maps[0].sizes[i + 1].fbo); //next level, since mipmaps[0] starts one level bigger
  2464. _copy_screen(true);
  2465. state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GAUSSIAN_VERTICAL, false);
  2466. }
  2467. }
  2468. void RasterizerSceneGLES3::_prepare_depth_texture() {
  2469. if (!state.prepared_depth_texture) {
  2470. //resolve depth buffer
  2471. glBindFramebuffer(GL_READ_FRAMEBUFFER, storage->frame.current_rt->buffers.fbo);
  2472. glReadBuffer(GL_COLOR_ATTACHMENT0);
  2473. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, storage->frame.current_rt->fbo);
  2474. glBlitFramebuffer(0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, 0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, GL_DEPTH_BUFFER_BIT, GL_NEAREST);
  2475. glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
  2476. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
  2477. state.prepared_depth_texture = true;
  2478. }
  2479. }
  2480. void RasterizerSceneGLES3::_bind_depth_texture() {
  2481. if (!state.bound_depth_texture) {
  2482. ERR_FAIL_COND(!state.prepared_depth_texture);
  2483. //bind depth for read
  2484. glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 8);
  2485. glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->depth);
  2486. state.bound_depth_texture = true;
  2487. }
  2488. }
  2489. void RasterizerSceneGLES3::_render_mrts(Environment *env, const CameraMatrix &p_cam_projection) {
  2490. glDepthMask(GL_FALSE);
  2491. glDisable(GL_DEPTH_TEST);
  2492. glDisable(GL_CULL_FACE);
  2493. glDisable(GL_BLEND);
  2494. _prepare_depth_texture();
  2495. if (env->ssao_enabled || env->ssr_enabled) {
  2496. //copy normal and roughness to effect buffer
  2497. glBindFramebuffer(GL_READ_FRAMEBUFFER, storage->frame.current_rt->buffers.fbo);
  2498. glReadBuffer(GL_COLOR_ATTACHMENT2);
  2499. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, storage->frame.current_rt->buffers.effect_fbo);
  2500. glBlitFramebuffer(0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, 0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, GL_COLOR_BUFFER_BIT, GL_NEAREST);
  2501. }
  2502. if (env->ssao_enabled) {
  2503. //copy diffuse to front buffer
  2504. glBindFramebuffer(GL_READ_FRAMEBUFFER, storage->frame.current_rt->buffers.fbo);
  2505. glReadBuffer(GL_COLOR_ATTACHMENT0);
  2506. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, storage->frame.current_rt->fbo);
  2507. glBlitFramebuffer(0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, 0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, GL_NEAREST);
  2508. glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
  2509. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
  2510. //copy from depth, convert to linear
  2511. GLint ss[2];
  2512. ss[0] = storage->frame.current_rt->width;
  2513. ss[1] = storage->frame.current_rt->height;
  2514. for (int i = 0; i < storage->frame.current_rt->effects.ssao.depth_mipmap_fbos.size(); i++) {
  2515. state.ssao_minify_shader.set_conditional(SsaoMinifyShaderGLES3::MINIFY_START, i == 0);
  2516. state.ssao_minify_shader.set_conditional(SsaoMinifyShaderGLES3::USE_ORTHOGONAL_PROJECTION, p_cam_projection.is_orthogonal());
  2517. state.ssao_minify_shader.bind();
  2518. state.ssao_minify_shader.set_uniform(SsaoMinifyShaderGLES3::CAMERA_Z_FAR, p_cam_projection.get_z_far());
  2519. state.ssao_minify_shader.set_uniform(SsaoMinifyShaderGLES3::CAMERA_Z_NEAR, p_cam_projection.get_z_near());
  2520. state.ssao_minify_shader.set_uniform(SsaoMinifyShaderGLES3::SOURCE_MIPMAP, MAX(0, i - 1));
  2521. glUniform2iv(state.ssao_minify_shader.get_uniform(SsaoMinifyShaderGLES3::FROM_SIZE), 1, ss);
  2522. ss[0] >>= 1;
  2523. ss[1] >>= 1;
  2524. glActiveTexture(GL_TEXTURE0);
  2525. if (i == 0) {
  2526. glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->depth);
  2527. } else {
  2528. glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.ssao.linear_depth);
  2529. }
  2530. glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->effects.ssao.depth_mipmap_fbos[i]); //copy to front first
  2531. glViewport(0, 0, ss[0], ss[1]);
  2532. _copy_screen(true);
  2533. }
  2534. ss[0] = storage->frame.current_rt->width;
  2535. ss[1] = storage->frame.current_rt->height;
  2536. glViewport(0, 0, ss[0], ss[1]);
  2537. glEnable(GL_DEPTH_TEST);
  2538. glDepthFunc(GL_GREATER);
  2539. // do SSAO!
  2540. state.ssao_shader.set_conditional(SsaoShaderGLES3::ENABLE_RADIUS2, env->ssao_radius2 > 0.001);
  2541. state.ssao_shader.set_conditional(SsaoShaderGLES3::USE_ORTHOGONAL_PROJECTION, p_cam_projection.is_orthogonal());
  2542. state.ssao_shader.set_conditional(SsaoShaderGLES3::SSAO_QUALITY_LOW, env->ssao_quality == VS::ENV_SSAO_QUALITY_LOW);
  2543. state.ssao_shader.set_conditional(SsaoShaderGLES3::SSAO_QUALITY_HIGH, env->ssao_quality == VS::ENV_SSAO_QUALITY_HIGH);
  2544. state.ssao_shader.bind();
  2545. state.ssao_shader.set_uniform(SsaoShaderGLES3::CAMERA_Z_FAR, p_cam_projection.get_z_far());
  2546. state.ssao_shader.set_uniform(SsaoShaderGLES3::CAMERA_Z_NEAR, p_cam_projection.get_z_near());
  2547. glUniform2iv(state.ssao_shader.get_uniform(SsaoShaderGLES3::SCREEN_SIZE), 1, ss);
  2548. float radius = env->ssao_radius;
  2549. state.ssao_shader.set_uniform(SsaoShaderGLES3::RADIUS, radius);
  2550. float intensity = env->ssao_intensity;
  2551. state.ssao_shader.set_uniform(SsaoShaderGLES3::INTENSITY_DIV_R6, intensity / pow(radius, 6.0f));
  2552. if (env->ssao_radius2 > 0.001) {
  2553. float radius2 = env->ssao_radius2;
  2554. state.ssao_shader.set_uniform(SsaoShaderGLES3::RADIUS2, radius2);
  2555. float intensity2 = env->ssao_intensity2;
  2556. state.ssao_shader.set_uniform(SsaoShaderGLES3::INTENSITY_DIV_R62, intensity2 / pow(radius2, 6.0f));
  2557. }
  2558. float proj_info[4] = {
  2559. -2.0f / (ss[0] * p_cam_projection.matrix[0][0]),
  2560. -2.0f / (ss[1] * p_cam_projection.matrix[1][1]),
  2561. (1.0f - p_cam_projection.matrix[0][2]) / p_cam_projection.matrix[0][0],
  2562. (1.0f + p_cam_projection.matrix[1][2]) / p_cam_projection.matrix[1][1]
  2563. };
  2564. glUniform4fv(state.ssao_shader.get_uniform(SsaoShaderGLES3::PROJ_INFO), 1, proj_info);
  2565. float pixels_per_meter = float(p_cam_projection.get_pixels_per_meter(ss[0]));
  2566. state.ssao_shader.set_uniform(SsaoShaderGLES3::PROJ_SCALE, pixels_per_meter);
  2567. state.ssao_shader.set_uniform(SsaoShaderGLES3::BIAS, env->ssao_bias);
  2568. glActiveTexture(GL_TEXTURE0);
  2569. glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->depth);
  2570. glActiveTexture(GL_TEXTURE1);
  2571. glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.ssao.linear_depth);
  2572. glActiveTexture(GL_TEXTURE2);
  2573. glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->buffers.effect);
  2574. glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->effects.ssao.blur_fbo[0]); //copy to front first
  2575. Color white(1, 1, 1, 1);
  2576. glClearBufferfv(GL_COLOR, 0, white.components); // specular
  2577. _copy_screen(true);
  2578. //do the batm, i mean blur
  2579. state.ssao_blur_shader.bind();
  2580. if (env->ssao_filter) {
  2581. for (int i = 0; i < 2; i++) {
  2582. state.ssao_blur_shader.set_uniform(SsaoBlurShaderGLES3::CAMERA_Z_FAR, p_cam_projection.get_z_far());
  2583. state.ssao_blur_shader.set_uniform(SsaoBlurShaderGLES3::CAMERA_Z_NEAR, p_cam_projection.get_z_near());
  2584. state.ssao_blur_shader.set_uniform(SsaoBlurShaderGLES3::EDGE_SHARPNESS, env->ssao_bilateral_sharpness);
  2585. state.ssao_blur_shader.set_uniform(SsaoBlurShaderGLES3::FILTER_SCALE, int(env->ssao_filter));
  2586. GLint axis[2] = { i, 1 - i };
  2587. glUniform2iv(state.ssao_blur_shader.get_uniform(SsaoBlurShaderGLES3::AXIS), 1, axis);
  2588. glUniform2iv(state.ssao_blur_shader.get_uniform(SsaoBlurShaderGLES3::SCREEN_SIZE), 1, ss);
  2589. glActiveTexture(GL_TEXTURE0);
  2590. glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.ssao.blur_red[i]);
  2591. glActiveTexture(GL_TEXTURE1);
  2592. glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->depth);
  2593. glActiveTexture(GL_TEXTURE2);
  2594. glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->buffers.effect);
  2595. glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->effects.ssao.blur_fbo[1 - i]);
  2596. if (i == 0) {
  2597. glClearBufferfv(GL_COLOR, 0, white.components); // specular
  2598. }
  2599. _copy_screen(true);
  2600. }
  2601. }
  2602. glDisable(GL_DEPTH_TEST);
  2603. glDepthFunc(GL_LEQUAL);
  2604. // just copy diffuse while applying SSAO
  2605. state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::SSAO_MERGE, true);
  2606. state.effect_blur_shader.bind();
  2607. state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::SSAO_COLOR, env->ssao_color);
  2608. glActiveTexture(GL_TEXTURE0);
  2609. glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->color); //previous level, since mipmaps[0] starts one level bigger
  2610. glActiveTexture(GL_TEXTURE1);
  2611. glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.ssao.blur_red[0]); //previous level, since mipmaps[0] starts one level bigger
  2612. glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->effects.mip_maps[0].sizes[0].fbo); // copy to base level
  2613. _copy_screen(true);
  2614. state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::SSAO_MERGE, false);
  2615. } else {
  2616. //copy diffuse to effect buffer
  2617. glBindFramebuffer(GL_READ_FRAMEBUFFER, storage->frame.current_rt->buffers.fbo);
  2618. glReadBuffer(GL_COLOR_ATTACHMENT0);
  2619. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, storage->frame.current_rt->effects.mip_maps[0].sizes[0].fbo);
  2620. glBlitFramebuffer(0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, 0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, GL_NEAREST);
  2621. glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
  2622. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
  2623. }
  2624. if (state.used_sss) { //sss enabled
  2625. //copy diffuse while performing sss
  2626. Plane p = p_cam_projection.xform4(Plane(1, 0, -1, 1));
  2627. p.normal /= p.d;
  2628. float unit_size = p.normal.x;
  2629. //copy normal and roughness to effect buffer
  2630. glBindFramebuffer(GL_READ_FRAMEBUFFER, storage->frame.current_rt->buffers.fbo);
  2631. glReadBuffer(GL_COLOR_ATTACHMENT3);
  2632. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, storage->frame.current_rt->effects.ssao.blur_fbo[0]);
  2633. glBlitFramebuffer(0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, 0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, GL_COLOR_BUFFER_BIT, GL_LINEAR);
  2634. state.sss_shader.set_conditional(SubsurfScatteringShaderGLES3::USE_ORTHOGONAL_PROJECTION, p_cam_projection.is_orthogonal());
  2635. state.sss_shader.set_conditional(SubsurfScatteringShaderGLES3::USE_11_SAMPLES, subsurface_scatter_quality == SSS_QUALITY_LOW);
  2636. state.sss_shader.set_conditional(SubsurfScatteringShaderGLES3::USE_17_SAMPLES, subsurface_scatter_quality == SSS_QUALITY_MEDIUM);
  2637. state.sss_shader.set_conditional(SubsurfScatteringShaderGLES3::USE_25_SAMPLES, subsurface_scatter_quality == SSS_QUALITY_HIGH);
  2638. state.sss_shader.set_conditional(SubsurfScatteringShaderGLES3::ENABLE_FOLLOW_SURFACE, subsurface_scatter_follow_surface);
  2639. state.sss_shader.set_conditional(SubsurfScatteringShaderGLES3::ENABLE_STRENGTH_WEIGHTING, subsurface_scatter_weight_samples);
  2640. state.sss_shader.bind();
  2641. state.sss_shader.set_uniform(SubsurfScatteringShaderGLES3::MAX_RADIUS, subsurface_scatter_size);
  2642. state.sss_shader.set_uniform(SubsurfScatteringShaderGLES3::UNIT_SIZE, unit_size);
  2643. state.sss_shader.set_uniform(SubsurfScatteringShaderGLES3::CAMERA_Z_NEAR, p_cam_projection.get_z_near());
  2644. state.sss_shader.set_uniform(SubsurfScatteringShaderGLES3::CAMERA_Z_FAR, p_cam_projection.get_z_far());
  2645. state.sss_shader.set_uniform(SubsurfScatteringShaderGLES3::DIR, Vector2(1, 0));
  2646. glActiveTexture(GL_TEXTURE0);
  2647. glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.mip_maps[0].color);
  2648. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); //disable filter (fixes bugs on AMD)
  2649. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  2650. glActiveTexture(GL_TEXTURE1);
  2651. glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.ssao.blur_red[0]);
  2652. glActiveTexture(GL_TEXTURE2);
  2653. glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->depth);
  2654. //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE);
  2655. glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->fbo); //copy to front first
  2656. _copy_screen(true);
  2657. glActiveTexture(GL_TEXTURE0);
  2658. glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->color);
  2659. state.sss_shader.set_uniform(SubsurfScatteringShaderGLES3::DIR, Vector2(0, 1));
  2660. glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->effects.mip_maps[0].sizes[0].fbo); // copy to base level
  2661. _copy_screen(true);
  2662. glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.mip_maps[0].color); //restore filter
  2663. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  2664. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
  2665. }
  2666. if (env->ssr_enabled) {
  2667. //blur diffuse into effect mipmaps using separatable convolution
  2668. //storage->shaders.copy.set_conditional(CopyShaderGLES3::GAUSSIAN_HORIZONTAL,true);
  2669. _blur_effect_buffer();
  2670. //perform SSR
  2671. state.ssr_shader.set_conditional(ScreenSpaceReflectionShaderGLES3::REFLECT_ROUGHNESS, env->ssr_roughness);
  2672. state.ssr_shader.set_conditional(ScreenSpaceReflectionShaderGLES3::USE_ORTHOGONAL_PROJECTION, p_cam_projection.is_orthogonal());
  2673. state.ssr_shader.bind();
  2674. int ssr_w = storage->frame.current_rt->effects.mip_maps[1].sizes[0].width;
  2675. int ssr_h = storage->frame.current_rt->effects.mip_maps[1].sizes[0].height;
  2676. state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::PIXEL_SIZE, Vector2(1.0 / (ssr_w * 0.5), 1.0 / (ssr_h * 0.5)));
  2677. state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::CAMERA_Z_NEAR, p_cam_projection.get_z_near());
  2678. state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::CAMERA_Z_FAR, p_cam_projection.get_z_far());
  2679. state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::PROJECTION, p_cam_projection);
  2680. state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::INVERSE_PROJECTION, p_cam_projection.inverse());
  2681. state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::VIEWPORT_SIZE, Size2(ssr_w, ssr_h));
  2682. //state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::FRAME_INDEX,int(render_pass));
  2683. state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::FILTER_MIPMAP_LEVELS, float(storage->frame.current_rt->effects.mip_maps[0].sizes.size()));
  2684. state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::NUM_STEPS, env->ssr_max_steps);
  2685. state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::DEPTH_TOLERANCE, env->ssr_depth_tolerance);
  2686. state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::DISTANCE_FADE, env->ssr_fade_out);
  2687. state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::CURVE_FADE_IN, env->ssr_fade_in);
  2688. glActiveTexture(GL_TEXTURE0);
  2689. glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.mip_maps[0].color);
  2690. glActiveTexture(GL_TEXTURE1);
  2691. glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->buffers.effect);
  2692. glActiveTexture(GL_TEXTURE2);
  2693. glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->depth);
  2694. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE);
  2695. glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->effects.mip_maps[1].sizes[0].fbo);
  2696. glViewport(0, 0, ssr_w, ssr_h);
  2697. _copy_screen(true);
  2698. glViewport(0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height);
  2699. }
  2700. glBindFramebuffer(GL_READ_FRAMEBUFFER, storage->frame.current_rt->buffers.fbo);
  2701. glReadBuffer(GL_COLOR_ATTACHMENT1);
  2702. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, storage->frame.current_rt->fbo);
  2703. //glDrawBuffer(GL_COLOR_ATTACHMENT0);
  2704. glBlitFramebuffer(0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, 0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, GL_COLOR_BUFFER_BIT, GL_NEAREST);
  2705. glReadBuffer(GL_COLOR_ATTACHMENT0);
  2706. glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
  2707. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
  2708. //copy reflection over diffuse, resolving SSR if needed
  2709. state.resolve_shader.set_conditional(ResolveShaderGLES3::USE_SSR, env->ssr_enabled);
  2710. state.resolve_shader.bind();
  2711. state.resolve_shader.set_uniform(ResolveShaderGLES3::PIXEL_SIZE, Vector2(1.0 / storage->frame.current_rt->width, 1.0 / storage->frame.current_rt->height));
  2712. glActiveTexture(GL_TEXTURE0);
  2713. glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->color);
  2714. if (env->ssr_enabled) {
  2715. glActiveTexture(GL_TEXTURE1);
  2716. glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.mip_maps[1].color);
  2717. }
  2718. glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->effects.mip_maps[0].sizes[0].fbo);
  2719. glEnable(GL_BLEND);
  2720. glBlendEquation(GL_FUNC_ADD);
  2721. glBlendFunc(GL_ONE, GL_ONE); //use additive to accumulate one over the other
  2722. _copy_screen(true);
  2723. glDisable(GL_BLEND); //end additive
  2724. if (state.used_screen_texture) {
  2725. _blur_effect_buffer();
  2726. //restored framebuffer
  2727. glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->effects.mip_maps[0].sizes[0].fbo);
  2728. glViewport(0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height);
  2729. }
  2730. state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::SIMPLE_COPY, true);
  2731. state.effect_blur_shader.bind();
  2732. state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::LOD, float(0));
  2733. {
  2734. GLuint db = GL_COLOR_ATTACHMENT0;
  2735. glDrawBuffers(1, &db);
  2736. }
  2737. glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->buffers.fbo);
  2738. glActiveTexture(GL_TEXTURE0);
  2739. glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.mip_maps[0].color);
  2740. _copy_screen(true);
  2741. state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::SIMPLE_COPY, false);
  2742. }
  2743. void RasterizerSceneGLES3::_post_process(Environment *env, const CameraMatrix &p_cam_projection) {
  2744. //copy to front buffer
  2745. glDepthMask(GL_FALSE);
  2746. glDisable(GL_DEPTH_TEST);
  2747. glDisable(GL_CULL_FACE);
  2748. glDisable(GL_BLEND);
  2749. glDepthFunc(GL_LEQUAL);
  2750. glColorMask(1, 1, 1, 1);
  2751. //turn off everything used
  2752. //copy specular to front buffer
  2753. //copy diffuse to effect buffer
  2754. if (storage->frame.current_rt->buffers.active) {
  2755. //transfer to effect buffer if using buffers, also resolve MSAA
  2756. glBindFramebuffer(GL_READ_FRAMEBUFFER, storage->frame.current_rt->buffers.fbo);
  2757. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, storage->frame.current_rt->effects.mip_maps[0].sizes[0].fbo);
  2758. glBlitFramebuffer(0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, 0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, GL_COLOR_BUFFER_BIT, GL_NEAREST);
  2759. glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
  2760. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
  2761. }
  2762. if ((!env || storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_TRANSPARENT] || storage->frame.current_rt->width < 4 || storage->frame.current_rt->height < 4) && !storage->frame.current_rt->use_fxaa && !storage->frame.current_rt->use_debanding) { //no post process on small render targets
  2763. //no environment or transparent render, simply return and convert to SRGB
  2764. if (storage->frame.current_rt->external.fbo != 0) {
  2765. glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->external.fbo);
  2766. } else {
  2767. glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->fbo);
  2768. }
  2769. glActiveTexture(GL_TEXTURE0);
  2770. glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.mip_maps[0].color);
  2771. storage->shaders.copy.set_conditional(CopyShaderGLES3::LINEAR_TO_SRGB, !storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_KEEP_3D_LINEAR]);
  2772. storage->shaders.copy.set_conditional(CopyShaderGLES3::V_FLIP, storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_VFLIP]);
  2773. storage->shaders.copy.set_conditional(CopyShaderGLES3::DISABLE_ALPHA, !storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_TRANSPARENT]);
  2774. storage->shaders.copy.bind();
  2775. _copy_screen(true);
  2776. storage->shaders.copy.set_conditional(CopyShaderGLES3::LINEAR_TO_SRGB, false);
  2777. storage->shaders.copy.set_conditional(CopyShaderGLES3::DISABLE_ALPHA, false); //compute luminance
  2778. storage->shaders.copy.set_conditional(CopyShaderGLES3::V_FLIP, false);
  2779. return;
  2780. }
  2781. //order of operation
  2782. //1) DOF Blur (first blur, then copy to buffer applying the blur)
  2783. //2) FXAA
  2784. //3) Bloom (Glow)
  2785. //4) Tonemap
  2786. //5) Adjustments
  2787. GLuint composite_from = storage->frame.current_rt->effects.mip_maps[0].color;
  2788. if (env && env->dof_blur_far_enabled) {
  2789. //blur diffuse into effect mipmaps using separatable convolution
  2790. //storage->shaders.copy.set_conditional(CopyShaderGLES3::GAUSSIAN_HORIZONTAL,true);
  2791. int vp_h = storage->frame.current_rt->height;
  2792. int vp_w = storage->frame.current_rt->width;
  2793. state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::USE_ORTHOGONAL_PROJECTION, p_cam_projection.is_orthogonal());
  2794. state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_FAR_BLUR, true);
  2795. state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_LOW, env->dof_blur_far_quality == VS::ENV_DOF_BLUR_QUALITY_LOW);
  2796. state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_MEDIUM, env->dof_blur_far_quality == VS::ENV_DOF_BLUR_QUALITY_MEDIUM);
  2797. state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_HIGH, env->dof_blur_far_quality == VS::ENV_DOF_BLUR_QUALITY_HIGH);
  2798. state.effect_blur_shader.bind();
  2799. int qsteps[3] = { 4, 10, 20 };
  2800. float radius = (env->dof_blur_far_amount * env->dof_blur_far_amount) / qsteps[env->dof_blur_far_quality];
  2801. state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_BEGIN, env->dof_blur_far_distance);
  2802. state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_END, env->dof_blur_far_distance + env->dof_blur_far_transition);
  2803. state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_DIR, Vector2(1, 0));
  2804. state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_RADIUS, radius);
  2805. state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::PIXEL_SIZE, Vector2(1.0 / vp_w, 1.0 / vp_h));
  2806. state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::CAMERA_Z_NEAR, p_cam_projection.get_z_near());
  2807. state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::CAMERA_Z_FAR, p_cam_projection.get_z_far());
  2808. glActiveTexture(GL_TEXTURE1);
  2809. glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->depth);
  2810. glActiveTexture(GL_TEXTURE0);
  2811. glBindTexture(GL_TEXTURE_2D, composite_from);
  2812. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  2813. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  2814. glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  2815. glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  2816. glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->fbo); //copy to front first
  2817. _copy_screen(true);
  2818. glActiveTexture(GL_TEXTURE0);
  2819. glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->color);
  2820. state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_DIR, Vector2(0, 1));
  2821. glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->effects.mip_maps[0].sizes[0].fbo); // copy to base level
  2822. _copy_screen();
  2823. state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_FAR_BLUR, false);
  2824. state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_LOW, false);
  2825. state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_MEDIUM, false);
  2826. state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_HIGH, false);
  2827. state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::USE_ORTHOGONAL_PROJECTION, false);
  2828. composite_from = storage->frame.current_rt->effects.mip_maps[0].color;
  2829. }
  2830. if (env && env->dof_blur_near_enabled) {
  2831. //blur diffuse into effect mipmaps using separatable convolution
  2832. //storage->shaders.copy.set_conditional(CopyShaderGLES3::GAUSSIAN_HORIZONTAL,true);
  2833. int vp_h = storage->frame.current_rt->height;
  2834. int vp_w = storage->frame.current_rt->width;
  2835. state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::USE_ORTHOGONAL_PROJECTION, p_cam_projection.is_orthogonal());
  2836. state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_NEAR_BLUR, true);
  2837. state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_NEAR_FIRST_TAP, true);
  2838. state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_LOW, env->dof_blur_near_quality == VS::ENV_DOF_BLUR_QUALITY_LOW);
  2839. state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_MEDIUM, env->dof_blur_near_quality == VS::ENV_DOF_BLUR_QUALITY_MEDIUM);
  2840. state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_HIGH, env->dof_blur_near_quality == VS::ENV_DOF_BLUR_QUALITY_HIGH);
  2841. state.effect_blur_shader.bind();
  2842. int qsteps[3] = { 4, 10, 20 };
  2843. float radius = (env->dof_blur_near_amount * env->dof_blur_near_amount) / qsteps[env->dof_blur_near_quality];
  2844. state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_BEGIN, env->dof_blur_near_distance);
  2845. state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_END, env->dof_blur_near_distance - env->dof_blur_near_transition);
  2846. state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_DIR, Vector2(1, 0));
  2847. state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_RADIUS, radius);
  2848. state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::PIXEL_SIZE, Vector2(1.0 / vp_w, 1.0 / vp_h));
  2849. state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::CAMERA_Z_NEAR, p_cam_projection.get_z_near());
  2850. state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::CAMERA_Z_FAR, p_cam_projection.get_z_far());
  2851. glActiveTexture(GL_TEXTURE1);
  2852. glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->depth);
  2853. glActiveTexture(GL_TEXTURE0);
  2854. glBindTexture(GL_TEXTURE_2D, composite_from);
  2855. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  2856. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  2857. glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  2858. glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  2859. glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->fbo); //copy to front first
  2860. _copy_screen();
  2861. //manually do the blend if this is the first operation resolving from the diffuse buffer
  2862. state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_NEAR_BLUR_MERGE, composite_from == storage->frame.current_rt->buffers.diffuse);
  2863. state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_NEAR_FIRST_TAP, false);
  2864. state.effect_blur_shader.bind();
  2865. state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_BEGIN, env->dof_blur_near_distance);
  2866. state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_END, env->dof_blur_near_distance - env->dof_blur_near_transition);
  2867. state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_DIR, Vector2(0, 1));
  2868. state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_RADIUS, radius);
  2869. state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::PIXEL_SIZE, Vector2(1.0 / vp_w, 1.0 / vp_h));
  2870. state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::CAMERA_Z_NEAR, p_cam_projection.get_z_near());
  2871. state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::CAMERA_Z_FAR, p_cam_projection.get_z_far());
  2872. glActiveTexture(GL_TEXTURE0);
  2873. glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->color);
  2874. glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->effects.mip_maps[0].sizes[0].fbo); // copy to base level
  2875. if (composite_from != storage->frame.current_rt->buffers.diffuse) {
  2876. glEnable(GL_BLEND);
  2877. glBlendEquation(GL_FUNC_ADD);
  2878. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  2879. } else {
  2880. glActiveTexture(GL_TEXTURE2);
  2881. glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->buffers.diffuse);
  2882. }
  2883. _copy_screen(true);
  2884. if (composite_from != storage->frame.current_rt->buffers.diffuse) {
  2885. glDisable(GL_BLEND);
  2886. }
  2887. state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_NEAR_BLUR, false);
  2888. state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_NEAR_FIRST_TAP, false);
  2889. state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_NEAR_BLUR_MERGE, false);
  2890. state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_LOW, false);
  2891. state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_MEDIUM, false);
  2892. state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_HIGH, false);
  2893. state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::USE_ORTHOGONAL_PROJECTION, false);
  2894. composite_from = storage->frame.current_rt->effects.mip_maps[0].color;
  2895. }
  2896. if (env && (env->dof_blur_near_enabled || env->dof_blur_far_enabled)) {
  2897. //these needed to disable filtering, reenamble
  2898. glActiveTexture(GL_TEXTURE0);
  2899. glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.mip_maps[0].color);
  2900. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  2901. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
  2902. glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  2903. glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  2904. }
  2905. if (env && env->auto_exposure) {
  2906. //compute auto exposure
  2907. //first step, copy from image to luminance buffer
  2908. state.exposure_shader.set_conditional(ExposureShaderGLES3::EXPOSURE_BEGIN, true);
  2909. state.exposure_shader.bind();
  2910. int ss[2] = {
  2911. storage->frame.current_rt->width,
  2912. storage->frame.current_rt->height,
  2913. };
  2914. int ds[2] = {
  2915. exposure_shrink_size,
  2916. exposure_shrink_size,
  2917. };
  2918. glUniform2iv(state.exposure_shader.get_uniform(ExposureShaderGLES3::SOURCE_RENDER_SIZE), 1, ss);
  2919. glUniform2iv(state.exposure_shader.get_uniform(ExposureShaderGLES3::TARGET_SIZE), 1, ds);
  2920. glActiveTexture(GL_TEXTURE0);
  2921. glBindTexture(GL_TEXTURE_2D, composite_from);
  2922. glBindFramebuffer(GL_FRAMEBUFFER, exposure_shrink[0].fbo);
  2923. glViewport(0, 0, exposure_shrink_size, exposure_shrink_size);
  2924. _copy_screen(true);
  2925. //second step, shrink to 2x2 pixels
  2926. state.exposure_shader.set_conditional(ExposureShaderGLES3::EXPOSURE_BEGIN, false);
  2927. state.exposure_shader.bind();
  2928. //shrink from second to previous to last level
  2929. int s_size = exposure_shrink_size / 3;
  2930. for (int i = 1; i < exposure_shrink.size() - 1; i++) {
  2931. glBindFramebuffer(GL_FRAMEBUFFER, exposure_shrink[i].fbo);
  2932. glActiveTexture(GL_TEXTURE0);
  2933. glBindTexture(GL_TEXTURE_2D, exposure_shrink[i - 1].color);
  2934. _copy_screen();
  2935. glViewport(0, 0, s_size, s_size);
  2936. s_size /= 3;
  2937. }
  2938. //third step, shrink to 1x1 pixel taking in consideration the previous exposure
  2939. state.exposure_shader.set_conditional(ExposureShaderGLES3::EXPOSURE_END, true);
  2940. uint64_t tick = OS::get_singleton()->get_ticks_usec();
  2941. uint64_t tick_diff = storage->frame.current_rt->last_exposure_tick == 0 ? 0 : tick - storage->frame.current_rt->last_exposure_tick;
  2942. storage->frame.current_rt->last_exposure_tick = tick;
  2943. if (tick_diff == 0 || tick_diff > 1000000) {
  2944. state.exposure_shader.set_conditional(ExposureShaderGLES3::EXPOSURE_FORCE_SET, true);
  2945. }
  2946. state.exposure_shader.bind();
  2947. glBindFramebuffer(GL_FRAMEBUFFER, exposure_shrink[exposure_shrink.size() - 1].fbo);
  2948. glViewport(0, 0, 1, 1);
  2949. glActiveTexture(GL_TEXTURE0);
  2950. glBindTexture(GL_TEXTURE_2D, exposure_shrink[exposure_shrink.size() - 2].color);
  2951. glActiveTexture(GL_TEXTURE1);
  2952. glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->exposure.color); //read from previous
  2953. state.exposure_shader.set_uniform(ExposureShaderGLES3::EXPOSURE_ADJUST, env->auto_exposure_speed * (tick_diff / 1000000.0));
  2954. state.exposure_shader.set_uniform(ExposureShaderGLES3::MAX_LUMINANCE, env->auto_exposure_max);
  2955. state.exposure_shader.set_uniform(ExposureShaderGLES3::MIN_LUMINANCE, env->auto_exposure_min);
  2956. _copy_screen(true);
  2957. state.exposure_shader.set_conditional(ExposureShaderGLES3::EXPOSURE_FORCE_SET, false);
  2958. state.exposure_shader.set_conditional(ExposureShaderGLES3::EXPOSURE_END, false);
  2959. //last step, swap with the framebuffer exposure, so the right exposure is kept int he framebuffer
  2960. SWAP(exposure_shrink.write[exposure_shrink.size() - 1].fbo, storage->frame.current_rt->exposure.fbo);
  2961. SWAP(exposure_shrink.write[exposure_shrink.size() - 1].color, storage->frame.current_rt->exposure.color);
  2962. glViewport(0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height);
  2963. VisualServerRaster::redraw_request(); //if using auto exposure, redraw must happen
  2964. }
  2965. int max_glow_level = -1;
  2966. int glow_mask = 0;
  2967. if (env && env->glow_enabled) {
  2968. for (int i = 0; i < VS::MAX_GLOW_LEVELS; i++) {
  2969. if (env->glow_levels & (1 << i)) {
  2970. if (i >= storage->frame.current_rt->effects.mip_maps[1].sizes.size()) {
  2971. max_glow_level = storage->frame.current_rt->effects.mip_maps[1].sizes.size() - 1;
  2972. glow_mask |= 1 << max_glow_level;
  2973. } else {
  2974. max_glow_level = i;
  2975. glow_mask |= (1 << i);
  2976. }
  2977. }
  2978. }
  2979. //blur diffuse into effect mipmaps using separatable convolution
  2980. //storage->shaders.copy.set_conditional(CopyShaderGLES3::GAUSSIAN_HORIZONTAL,true);
  2981. for (int i = 0; i < (max_glow_level + 1); i++) {
  2982. int vp_w = storage->frame.current_rt->effects.mip_maps[1].sizes[i].width;
  2983. int vp_h = storage->frame.current_rt->effects.mip_maps[1].sizes[i].height;
  2984. glViewport(0, 0, vp_w, vp_h);
  2985. //horizontal pass
  2986. if (i == 0) {
  2987. state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GLOW_FIRST_PASS, true);
  2988. state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GLOW_USE_AUTO_EXPOSURE, env->auto_exposure);
  2989. }
  2990. state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GLOW_GAUSSIAN_HORIZONTAL, true);
  2991. state.effect_blur_shader.bind();
  2992. state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::PIXEL_SIZE, Vector2(1.0 / vp_w, 1.0 / vp_h));
  2993. state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::LOD, float(i));
  2994. state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::GLOW_STRENGTH, env->glow_strength);
  2995. state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::LUMINANCE_CAP, env->glow_hdr_luminance_cap);
  2996. glActiveTexture(GL_TEXTURE0);
  2997. if (i == 0) {
  2998. glBindTexture(GL_TEXTURE_2D, composite_from);
  2999. state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::EXPOSURE, env->tone_mapper_exposure);
  3000. if (env->auto_exposure) {
  3001. state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::AUTO_EXPOSURE_GREY, env->auto_exposure_grey);
  3002. }
  3003. glActiveTexture(GL_TEXTURE1);
  3004. glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->exposure.color);
  3005. state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::GLOW_BLOOM, env->glow_bloom);
  3006. state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::GLOW_HDR_THRESHOLD, env->glow_hdr_bleed_threshold);
  3007. state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::GLOW_HDR_SCALE, env->glow_hdr_bleed_scale);
  3008. } else {
  3009. glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.mip_maps[0].color); //previous level, since mipmaps[0] starts one level bigger
  3010. }
  3011. glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->effects.mip_maps[1].sizes[i].fbo);
  3012. _copy_screen(true);
  3013. state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GLOW_GAUSSIAN_HORIZONTAL, false);
  3014. state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GLOW_FIRST_PASS, false);
  3015. state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GLOW_USE_AUTO_EXPOSURE, false);
  3016. //vertical pass
  3017. state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GLOW_GAUSSIAN_VERTICAL, true);
  3018. state.effect_blur_shader.bind();
  3019. state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::PIXEL_SIZE, Vector2(1.0 / vp_w, 1.0 / vp_h));
  3020. state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::LOD, float(i));
  3021. state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::GLOW_STRENGTH, env->glow_strength);
  3022. glActiveTexture(GL_TEXTURE0);
  3023. glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.mip_maps[1].color);
  3024. glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->effects.mip_maps[0].sizes[i + 1].fbo); //next level, since mipmaps[0] starts one level bigger
  3025. _copy_screen();
  3026. state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GLOW_GAUSSIAN_VERTICAL, false);
  3027. }
  3028. glViewport(0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height);
  3029. }
  3030. if (storage->frame.current_rt->external.fbo != 0) {
  3031. glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->external.fbo);
  3032. } else {
  3033. glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->fbo);
  3034. }
  3035. glActiveTexture(GL_TEXTURE0);
  3036. glBindTexture(GL_TEXTURE_2D, composite_from);
  3037. if (env) {
  3038. state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_FILMIC_TONEMAPPER, env->tone_mapper == VS::ENV_TONE_MAPPER_FILMIC);
  3039. state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_ACES_TONEMAPPER, env->tone_mapper == VS::ENV_TONE_MAPPER_ACES);
  3040. state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_REINHARD_TONEMAPPER, env->tone_mapper == VS::ENV_TONE_MAPPER_REINHARD);
  3041. state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_AUTO_EXPOSURE, env->auto_exposure);
  3042. state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_FILTER_BICUBIC, env->glow_bicubic_upscale);
  3043. }
  3044. state.tonemap_shader.set_conditional(TonemapShaderGLES3::KEEP_3D_LINEAR, storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_KEEP_3D_LINEAR]);
  3045. state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_FXAA, storage->frame.current_rt->use_fxaa);
  3046. state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_DEBANDING, storage->frame.current_rt->use_debanding);
  3047. if (env && max_glow_level >= 0) {
  3048. for (int i = 0; i < (max_glow_level + 1); i++) {
  3049. if (glow_mask & (1 << i)) {
  3050. if (i == 0) {
  3051. state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL1, true);
  3052. }
  3053. if (i == 1) {
  3054. state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL2, true);
  3055. }
  3056. if (i == 2) {
  3057. state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL3, true);
  3058. }
  3059. if (i == 3) {
  3060. state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL4, true);
  3061. }
  3062. if (i == 4) {
  3063. state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL5, true);
  3064. }
  3065. if (i == 5) {
  3066. state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL6, true);
  3067. }
  3068. if (i == 6) {
  3069. state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL7, true);
  3070. }
  3071. }
  3072. }
  3073. state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_SCREEN, env->glow_blend_mode == VS::GLOW_BLEND_MODE_SCREEN);
  3074. state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_SOFTLIGHT, env->glow_blend_mode == VS::GLOW_BLEND_MODE_SOFTLIGHT);
  3075. state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_REPLACE, env->glow_blend_mode == VS::GLOW_BLEND_MODE_REPLACE);
  3076. glActiveTexture(GL_TEXTURE2);
  3077. glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.mip_maps[0].color);
  3078. }
  3079. if (env && env->adjustments_enabled) {
  3080. state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_BCS, true);
  3081. RasterizerStorageGLES3::Texture *tex = storage->texture_owner.getornull(env->color_correction);
  3082. if (tex) {
  3083. state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_COLOR_CORRECTION, true);
  3084. glActiveTexture(GL_TEXTURE3);
  3085. glBindTexture(tex->target, tex->tex_id);
  3086. }
  3087. }
  3088. state.tonemap_shader.set_conditional(TonemapShaderGLES3::V_FLIP, storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_VFLIP]);
  3089. state.tonemap_shader.bind();
  3090. if (env) {
  3091. state.tonemap_shader.set_uniform(TonemapShaderGLES3::EXPOSURE, env->tone_mapper_exposure);
  3092. state.tonemap_shader.set_uniform(TonemapShaderGLES3::WHITE, env->tone_mapper_exposure_white);
  3093. if (max_glow_level >= 0) {
  3094. state.tonemap_shader.set_uniform(TonemapShaderGLES3::GLOW_INTENSITY, env->glow_intensity);
  3095. int ss[2] = {
  3096. storage->frame.current_rt->width,
  3097. storage->frame.current_rt->height,
  3098. };
  3099. glUniform2iv(state.tonemap_shader.get_uniform(TonemapShaderGLES3::GLOW_TEXTURE_SIZE), 1, ss);
  3100. }
  3101. if (env->auto_exposure) {
  3102. glActiveTexture(GL_TEXTURE1);
  3103. glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->exposure.color);
  3104. state.tonemap_shader.set_uniform(TonemapShaderGLES3::AUTO_EXPOSURE_GREY, env->auto_exposure_grey);
  3105. }
  3106. if (env->adjustments_enabled) {
  3107. state.tonemap_shader.set_uniform(TonemapShaderGLES3::BCS, Vector3(env->adjustments_brightness, env->adjustments_contrast, env->adjustments_saturation));
  3108. }
  3109. } else {
  3110. // No environment, so no exposure.
  3111. state.tonemap_shader.set_uniform(TonemapShaderGLES3::EXPOSURE, 1.0);
  3112. }
  3113. if (storage->frame.current_rt->use_fxaa) {
  3114. state.tonemap_shader.set_uniform(TonemapShaderGLES3::PIXEL_SIZE, Vector2(1.0 / storage->frame.current_rt->width, 1.0 / storage->frame.current_rt->height));
  3115. }
  3116. _copy_screen(true, true);
  3117. //turn off everything used
  3118. state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_FXAA, false);
  3119. state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_DEBANDING, false);
  3120. state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_AUTO_EXPOSURE, false);
  3121. state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_FILMIC_TONEMAPPER, false);
  3122. state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_ACES_TONEMAPPER, false);
  3123. state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_REINHARD_TONEMAPPER, false);
  3124. state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL1, false);
  3125. state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL2, false);
  3126. state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL3, false);
  3127. state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL4, false);
  3128. state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL5, false);
  3129. state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL6, false);
  3130. state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL7, false);
  3131. state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_REPLACE, false);
  3132. state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_SCREEN, false);
  3133. state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_SOFTLIGHT, false);
  3134. state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_FILTER_BICUBIC, false);
  3135. state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_BCS, false);
  3136. state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_COLOR_CORRECTION, false);
  3137. state.tonemap_shader.set_conditional(TonemapShaderGLES3::V_FLIP, false);
  3138. }
  3139. void RasterizerSceneGLES3::render_scene(const Transform &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_ortogonal, InstanceBase **p_cull_result, int p_cull_count, RID *p_light_cull_result, int p_light_cull_count, RID *p_reflection_probe_cull_result, int p_reflection_probe_cull_count, RID p_environment, RID p_shadow_atlas, RID p_reflection_atlas, RID p_reflection_probe, int p_reflection_probe_pass) {
  3140. //first of all, make a new render pass
  3141. render_pass++;
  3142. //fill up ubo
  3143. storage->info.render.object_count += p_cull_count;
  3144. Environment *env = environment_owner.getornull(p_environment);
  3145. ShadowAtlas *shadow_atlas = shadow_atlas_owner.getornull(p_shadow_atlas);
  3146. ReflectionAtlas *reflection_atlas = reflection_atlas_owner.getornull(p_reflection_atlas);
  3147. bool use_shadows = shadow_atlas && shadow_atlas->size;
  3148. state.scene_shader.set_conditional(SceneShaderGLES3::USE_SHADOW, use_shadows);
  3149. if (use_shadows) {
  3150. glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 5);
  3151. glBindTexture(GL_TEXTURE_2D, shadow_atlas->depth);
  3152. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
  3153. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LESS);
  3154. state.ubo_data.shadow_atlas_pixel_size[0] = 1.0 / shadow_atlas->size;
  3155. state.ubo_data.shadow_atlas_pixel_size[1] = 1.0 / shadow_atlas->size;
  3156. }
  3157. if (reflection_atlas && reflection_atlas->size) {
  3158. glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 3);
  3159. glBindTexture(GL_TEXTURE_2D, reflection_atlas->color);
  3160. }
  3161. if (p_reflection_probe.is_valid()) {
  3162. state.ubo_data.reflection_multiplier = 0.0;
  3163. } else {
  3164. state.ubo_data.reflection_multiplier = 1.0;
  3165. }
  3166. state.ubo_data.subsurface_scatter_width = subsurface_scatter_size;
  3167. state.ubo_data.z_offset = 0;
  3168. state.ubo_data.z_slope_scale = 0;
  3169. state.ubo_data.shadow_dual_paraboloid_render_side = 0;
  3170. state.ubo_data.shadow_dual_paraboloid_render_zfar = 0;
  3171. state.ubo_data.opaque_prepass_threshold = 0.99;
  3172. if (storage->frame.current_rt) {
  3173. int viewport_width_pixels = storage->frame.current_rt->width;
  3174. int viewport_height_pixels = storage->frame.current_rt->height;
  3175. state.ubo_data.viewport_size[0] = viewport_width_pixels;
  3176. state.ubo_data.viewport_size[1] = viewport_height_pixels;
  3177. state.ubo_data.screen_pixel_size[0] = 1.0 / viewport_width_pixels;
  3178. state.ubo_data.screen_pixel_size[1] = 1.0 / viewport_height_pixels;
  3179. }
  3180. _setup_environment(env, p_cam_projection, p_cam_transform, p_reflection_probe.is_valid());
  3181. bool fb_cleared = false;
  3182. glDepthFunc(GL_LEQUAL);
  3183. state.used_contact_shadows = false;
  3184. state.prepared_depth_texture = false;
  3185. state.bound_depth_texture = false;
  3186. for (int i = 0; i < p_light_cull_count; i++) {
  3187. ERR_BREAK(i >= render_list.max_lights);
  3188. LightInstance *li = light_instance_owner.getptr(p_light_cull_result[i]);
  3189. if (li->light_ptr->param[VS::LIGHT_PARAM_CONTACT_SHADOW_SIZE] > CMP_EPSILON) {
  3190. state.used_contact_shadows = true;
  3191. }
  3192. }
  3193. // Do depth prepass if it's explicitly enabled
  3194. bool use_depth_prepass = storage->config.use_depth_prepass;
  3195. // If contact shadows are used then we need to do depth prepass even if it's otherwise disabled
  3196. use_depth_prepass = use_depth_prepass || state.used_contact_shadows;
  3197. // Never do depth prepass if effects are disabled or if we render overdraws
  3198. use_depth_prepass = use_depth_prepass && storage->frame.current_rt && !storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_NO_3D_EFFECTS];
  3199. use_depth_prepass = use_depth_prepass && state.debug_draw != VS::VIEWPORT_DEBUG_DRAW_OVERDRAW;
  3200. if (use_depth_prepass) {
  3201. //pre z pass
  3202. glDisable(GL_BLEND);
  3203. glDepthMask(GL_TRUE);
  3204. glEnable(GL_DEPTH_TEST);
  3205. glDisable(GL_SCISSOR_TEST);
  3206. glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->buffers.fbo);
  3207. glDrawBuffers(0, NULL);
  3208. glViewport(0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height);
  3209. glColorMask(0, 0, 0, 0);
  3210. glClearDepth(1.0f);
  3211. glClear(GL_DEPTH_BUFFER_BIT);
  3212. render_list.clear();
  3213. _fill_render_list(p_cull_result, p_cull_count, true, false);
  3214. render_list.sort_by_key(false);
  3215. state.scene_shader.set_conditional(SceneShaderGLES3::RENDER_DEPTH, true);
  3216. _render_list(render_list.elements, render_list.element_count, p_cam_transform, p_cam_projection, NULL, false, false, true, false, false);
  3217. state.scene_shader.set_conditional(SceneShaderGLES3::RENDER_DEPTH, false);
  3218. glColorMask(1, 1, 1, 1);
  3219. if (state.used_contact_shadows) {
  3220. _prepare_depth_texture();
  3221. _bind_depth_texture();
  3222. }
  3223. fb_cleared = true;
  3224. render_pass++;
  3225. state.used_depth_prepass = true;
  3226. } else {
  3227. state.used_depth_prepass = false;
  3228. }
  3229. _setup_lights(p_light_cull_result, p_light_cull_count, p_cam_transform.affine_inverse(), p_cam_projection, p_shadow_atlas);
  3230. _setup_reflections(p_reflection_probe_cull_result, p_reflection_probe_cull_count, p_cam_transform.affine_inverse(), p_cam_projection, p_reflection_atlas, env);
  3231. bool use_mrt = false;
  3232. render_list.clear();
  3233. _fill_render_list(p_cull_result, p_cull_count, false, false);
  3234. //
  3235. glEnable(GL_BLEND);
  3236. glDepthMask(GL_TRUE);
  3237. glEnable(GL_DEPTH_TEST);
  3238. glDisable(GL_SCISSOR_TEST);
  3239. //rendering to a probe cubemap side
  3240. ReflectionProbeInstance *probe = reflection_probe_instance_owner.getornull(p_reflection_probe);
  3241. GLuint current_fbo;
  3242. if (probe) {
  3243. ReflectionAtlas *ref_atlas = reflection_atlas_owner.getptr(probe->atlas);
  3244. ERR_FAIL_COND(!ref_atlas);
  3245. int target_size = ref_atlas->size / ref_atlas->subdiv;
  3246. int cubemap_index = reflection_cubemaps.size() - 1;
  3247. for (int i = reflection_cubemaps.size() - 1; i >= 0; i--) {
  3248. //find appropriate cubemap to render to
  3249. if (reflection_cubemaps[i].size > target_size * 2)
  3250. break;
  3251. cubemap_index = i;
  3252. }
  3253. current_fbo = reflection_cubemaps[cubemap_index].fbo_id[p_reflection_probe_pass];
  3254. use_mrt = false;
  3255. state.scene_shader.set_conditional(SceneShaderGLES3::USE_MULTIPLE_RENDER_TARGETS, false);
  3256. glViewport(0, 0, reflection_cubemaps[cubemap_index].size, reflection_cubemaps[cubemap_index].size);
  3257. glBindFramebuffer(GL_FRAMEBUFFER, current_fbo);
  3258. } else {
  3259. use_mrt = env && (state.used_sss || env->ssao_enabled || env->ssr_enabled || env->dof_blur_far_enabled || env->dof_blur_near_enabled); //only enable MRT rendering if any of these is enabled
  3260. //effects disabled and transparency also prevent using MRTs
  3261. use_mrt = use_mrt && !storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_TRANSPARENT];
  3262. use_mrt = use_mrt && !storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_NO_3D_EFFECTS];
  3263. use_mrt = use_mrt && state.debug_draw != VS::VIEWPORT_DEBUG_DRAW_OVERDRAW;
  3264. use_mrt = use_mrt && (env->bg_mode != VS::ENV_BG_KEEP && env->bg_mode != VS::ENV_BG_CANVAS);
  3265. glViewport(0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height);
  3266. if (use_mrt) {
  3267. current_fbo = storage->frame.current_rt->buffers.fbo;
  3268. glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->buffers.fbo);
  3269. state.scene_shader.set_conditional(SceneShaderGLES3::USE_MULTIPLE_RENDER_TARGETS, true);
  3270. Vector<GLenum> draw_buffers;
  3271. draw_buffers.push_back(GL_COLOR_ATTACHMENT0);
  3272. draw_buffers.push_back(GL_COLOR_ATTACHMENT1);
  3273. draw_buffers.push_back(GL_COLOR_ATTACHMENT2);
  3274. if (state.used_sss) {
  3275. draw_buffers.push_back(GL_COLOR_ATTACHMENT3);
  3276. }
  3277. glDrawBuffers(draw_buffers.size(), draw_buffers.ptr());
  3278. Color black(0, 0, 0, 0);
  3279. glClearBufferfv(GL_COLOR, 1, black.components); // specular
  3280. glClearBufferfv(GL_COLOR, 2, black.components); // normal metal rough
  3281. if (state.used_sss) {
  3282. glClearBufferfv(GL_COLOR, 3, black.components); // normal metal rough
  3283. }
  3284. } else {
  3285. if (storage->frame.current_rt->buffers.active) {
  3286. current_fbo = storage->frame.current_rt->buffers.fbo;
  3287. } else {
  3288. if (storage->frame.current_rt->effects.mip_maps[0].sizes.size() == 0) {
  3289. ERR_PRINT_ONCE("Can't use canvas background mode in a render target configured without sampling");
  3290. return;
  3291. }
  3292. current_fbo = storage->frame.current_rt->effects.mip_maps[0].sizes[0].fbo;
  3293. }
  3294. glBindFramebuffer(GL_FRAMEBUFFER, current_fbo);
  3295. state.scene_shader.set_conditional(SceneShaderGLES3::USE_MULTIPLE_RENDER_TARGETS, false);
  3296. Vector<GLenum> draw_buffers;
  3297. draw_buffers.push_back(GL_COLOR_ATTACHMENT0);
  3298. glDrawBuffers(draw_buffers.size(), draw_buffers.ptr());
  3299. }
  3300. }
  3301. if (!fb_cleared) {
  3302. glClearDepth(1.0f);
  3303. glClear(GL_DEPTH_BUFFER_BIT);
  3304. }
  3305. Color clear_color(0, 0, 0, 0);
  3306. RasterizerStorageGLES3::Sky *sky = NULL;
  3307. Ref<CameraFeed> feed;
  3308. if (state.debug_draw == VS::VIEWPORT_DEBUG_DRAW_OVERDRAW) {
  3309. clear_color = Color(0, 0, 0, 0);
  3310. storage->frame.clear_request = false;
  3311. } else if (!probe && storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_TRANSPARENT]) {
  3312. clear_color = Color(0, 0, 0, 0);
  3313. storage->frame.clear_request = false;
  3314. } else if (!env || env->bg_mode == VS::ENV_BG_CLEAR_COLOR) {
  3315. if (storage->frame.clear_request) {
  3316. clear_color = storage->frame.clear_request_color.to_linear();
  3317. storage->frame.clear_request = false;
  3318. }
  3319. } else if (env->bg_mode == VS::ENV_BG_CANVAS) {
  3320. clear_color = env->bg_color.to_linear();
  3321. storage->frame.clear_request = false;
  3322. } else if (env->bg_mode == VS::ENV_BG_COLOR) {
  3323. clear_color = env->bg_color.to_linear();
  3324. storage->frame.clear_request = false;
  3325. } else if (env->bg_mode == VS::ENV_BG_SKY) {
  3326. storage->frame.clear_request = false;
  3327. } else if (env->bg_mode == VS::ENV_BG_COLOR_SKY) {
  3328. clear_color = env->bg_color.to_linear();
  3329. storage->frame.clear_request = false;
  3330. } else if (env->bg_mode == VS::ENV_BG_CAMERA_FEED) {
  3331. feed = CameraServer::get_singleton()->get_feed_by_id(env->camera_feed_id);
  3332. storage->frame.clear_request = false;
  3333. } else {
  3334. storage->frame.clear_request = false;
  3335. }
  3336. if (!env || env->bg_mode != VS::ENV_BG_KEEP) {
  3337. glClearBufferfv(GL_COLOR, 0, clear_color.components); // specular
  3338. }
  3339. VS::EnvironmentBG bg_mode = (!env || (probe && env->bg_mode == VS::ENV_BG_CANVAS)) ? VS::ENV_BG_CLEAR_COLOR : env->bg_mode; //if no environment, or canvas while rendering a probe (invalid use case), use color.
  3340. if (env) {
  3341. switch (bg_mode) {
  3342. case VS::ENV_BG_COLOR_SKY:
  3343. case VS::ENV_BG_SKY:
  3344. sky = storage->sky_owner.getornull(env->sky);
  3345. break;
  3346. case VS::ENV_BG_CANVAS:
  3347. //copy canvas to 3d buffer and convert it to linear
  3348. glDisable(GL_BLEND);
  3349. glDepthMask(GL_FALSE);
  3350. glDisable(GL_DEPTH_TEST);
  3351. glDisable(GL_CULL_FACE);
  3352. glActiveTexture(GL_TEXTURE0);
  3353. glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->color);
  3354. storage->shaders.copy.set_conditional(CopyShaderGLES3::DISABLE_ALPHA, true);
  3355. storage->shaders.copy.set_conditional(CopyShaderGLES3::SRGB_TO_LINEAR, true);
  3356. storage->shaders.copy.bind();
  3357. _copy_screen(true, true);
  3358. //turn off everything used
  3359. storage->shaders.copy.set_conditional(CopyShaderGLES3::SRGB_TO_LINEAR, false);
  3360. storage->shaders.copy.set_conditional(CopyShaderGLES3::DISABLE_ALPHA, false);
  3361. //restore
  3362. glEnable(GL_BLEND);
  3363. glDepthMask(GL_TRUE);
  3364. glEnable(GL_DEPTH_TEST);
  3365. glEnable(GL_CULL_FACE);
  3366. break;
  3367. case VS::ENV_BG_CAMERA_FEED:
  3368. if (feed.is_valid() && (feed->get_base_width() > 0) && (feed->get_base_height() > 0)) {
  3369. // copy our camera feed to our background
  3370. glDisable(GL_BLEND);
  3371. glDepthMask(GL_FALSE);
  3372. glDisable(GL_DEPTH_TEST);
  3373. glDisable(GL_CULL_FACE);
  3374. storage->shaders.copy.set_conditional(CopyShaderGLES3::USE_DISPLAY_TRANSFORM, true);
  3375. storage->shaders.copy.set_conditional(CopyShaderGLES3::DISABLE_ALPHA, true);
  3376. storage->shaders.copy.set_conditional(CopyShaderGLES3::SRGB_TO_LINEAR, true);
  3377. if (feed->get_datatype() == CameraFeed::FEED_RGB) {
  3378. RID camera_RGBA = feed->get_texture(CameraServer::FEED_RGBA_IMAGE);
  3379. VS::get_singleton()->texture_bind(camera_RGBA, 0);
  3380. } else if (feed->get_datatype() == CameraFeed::FEED_YCBCR) {
  3381. RID camera_YCbCr = feed->get_texture(CameraServer::FEED_YCBCR_IMAGE);
  3382. VS::get_singleton()->texture_bind(camera_YCbCr, 0);
  3383. storage->shaders.copy.set_conditional(CopyShaderGLES3::YCBCR_TO_SRGB, true);
  3384. } else if (feed->get_datatype() == CameraFeed::FEED_YCBCR_SEP) {
  3385. RID camera_Y = feed->get_texture(CameraServer::FEED_Y_IMAGE);
  3386. RID camera_CbCr = feed->get_texture(CameraServer::FEED_CBCR_IMAGE);
  3387. VS::get_singleton()->texture_bind(camera_Y, 0);
  3388. VS::get_singleton()->texture_bind(camera_CbCr, 1);
  3389. storage->shaders.copy.set_conditional(CopyShaderGLES3::SEP_CBCR_TEXTURE, true);
  3390. storage->shaders.copy.set_conditional(CopyShaderGLES3::YCBCR_TO_SRGB, true);
  3391. };
  3392. storage->shaders.copy.bind();
  3393. storage->shaders.copy.set_uniform(CopyShaderGLES3::DISPLAY_TRANSFORM, feed->get_transform());
  3394. _copy_screen(true, true);
  3395. //turn off everything used
  3396. storage->shaders.copy.set_conditional(CopyShaderGLES3::USE_DISPLAY_TRANSFORM, false);
  3397. storage->shaders.copy.set_conditional(CopyShaderGLES3::DISABLE_ALPHA, false);
  3398. storage->shaders.copy.set_conditional(CopyShaderGLES3::SRGB_TO_LINEAR, false);
  3399. storage->shaders.copy.set_conditional(CopyShaderGLES3::SEP_CBCR_TEXTURE, false);
  3400. storage->shaders.copy.set_conditional(CopyShaderGLES3::YCBCR_TO_SRGB, false);
  3401. //restore
  3402. glEnable(GL_BLEND);
  3403. glDepthMask(GL_TRUE);
  3404. glEnable(GL_DEPTH_TEST);
  3405. glEnable(GL_CULL_FACE);
  3406. } else {
  3407. // don't have a feed, just show greenscreen :)
  3408. clear_color = Color(0.0, 1.0, 0.0, 1.0);
  3409. }
  3410. break;
  3411. default: {
  3412. }
  3413. }
  3414. }
  3415. if (probe && probe->probe_ptr->interior) {
  3416. sky = NULL; //for rendering probe interiors, radiance must not be used.
  3417. }
  3418. state.texscreen_copied = false;
  3419. glBlendEquation(GL_FUNC_ADD);
  3420. if (storage->frame.current_rt && storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_TRANSPARENT]) {
  3421. glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
  3422. glEnable(GL_BLEND);
  3423. } else {
  3424. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  3425. glDisable(GL_BLEND);
  3426. }
  3427. render_list.sort_by_key(false);
  3428. if (state.directional_light_count == 0) {
  3429. directional_light = NULL;
  3430. _render_list(render_list.elements, render_list.element_count, p_cam_transform, p_cam_projection, sky, false, false, false, false, use_shadows);
  3431. } else {
  3432. for (int i = 0; i < state.directional_light_count; i++) {
  3433. directional_light = directional_lights[i];
  3434. if (i > 0) {
  3435. glEnable(GL_BLEND);
  3436. }
  3437. _setup_directional_light(i, p_cam_transform.affine_inverse(), use_shadows);
  3438. _render_list(render_list.elements, render_list.element_count, p_cam_transform, p_cam_projection, sky, false, false, false, i > 0, use_shadows);
  3439. }
  3440. }
  3441. state.scene_shader.set_conditional(SceneShaderGLES3::USE_MULTIPLE_RENDER_TARGETS, false);
  3442. if (use_mrt) {
  3443. GLenum gldb = GL_COLOR_ATTACHMENT0;
  3444. glDrawBuffers(1, &gldb);
  3445. }
  3446. if (env && env->bg_mode == VS::ENV_BG_SKY && (!storage->frame.current_rt || (!storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_TRANSPARENT] && state.debug_draw != VS::VIEWPORT_DEBUG_DRAW_OVERDRAW))) {
  3447. /*
  3448. if (use_mrt) {
  3449. glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->buffers.fbo); //switch to alpha fbo for sky, only diffuse/ambient matters
  3450. */
  3451. if (sky && sky->panorama.is_valid())
  3452. _draw_sky(sky, p_cam_projection, p_cam_transform, false, env->sky_custom_fov, env->bg_energy, env->sky_orientation);
  3453. }
  3454. //_render_list_forward(&alpha_render_list,camera_transform,camera_transform_inverse,camera_projection,false,fragment_lighting,true);
  3455. //glColorMask(1,1,1,1);
  3456. //state.scene_shader.set_conditional( SceneShaderGLES3::USE_FOG,false);
  3457. if (use_mrt) {
  3458. _render_mrts(env, p_cam_projection);
  3459. } else {
  3460. // Here we have to do the blits/resolves that otherwise are done in the MRT rendering, in particular
  3461. // - prepare screen texture for any geometry that uses a shader with screen texture
  3462. // - prepare depth texture for any geometry that uses a shader with depth texture
  3463. bool framebuffer_dirty = false;
  3464. if (storage->frame.current_rt && storage->frame.current_rt->buffers.active && state.used_screen_texture) {
  3465. glBindFramebuffer(GL_READ_FRAMEBUFFER, storage->frame.current_rt->buffers.fbo);
  3466. glReadBuffer(GL_COLOR_ATTACHMENT0);
  3467. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, storage->frame.current_rt->effects.mip_maps[0].sizes[0].fbo);
  3468. glBlitFramebuffer(0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, 0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, GL_NEAREST);
  3469. glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
  3470. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
  3471. _blur_effect_buffer();
  3472. framebuffer_dirty = true;
  3473. }
  3474. if (storage->frame.current_rt && storage->frame.current_rt->buffers.active && state.used_depth_texture) {
  3475. _prepare_depth_texture();
  3476. framebuffer_dirty = true;
  3477. }
  3478. if (framebuffer_dirty) {
  3479. // Restore framebuffer
  3480. glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->buffers.fbo);
  3481. glViewport(0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height);
  3482. }
  3483. }
  3484. if (storage->frame.current_rt && state.used_depth_texture && storage->frame.current_rt->buffers.active) {
  3485. _bind_depth_texture();
  3486. }
  3487. if (storage->frame.current_rt && state.used_screen_texture && storage->frame.current_rt->buffers.active) {
  3488. glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 7);
  3489. glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.mip_maps[0].color);
  3490. }
  3491. glEnable(GL_BLEND);
  3492. glDepthMask(GL_TRUE);
  3493. glEnable(GL_DEPTH_TEST);
  3494. glDisable(GL_SCISSOR_TEST);
  3495. render_list.sort_by_reverse_depth_and_priority(true);
  3496. if (state.directional_light_count == 0) {
  3497. directional_light = NULL;
  3498. _render_list(&render_list.elements[render_list.max_elements - render_list.alpha_element_count], render_list.alpha_element_count, p_cam_transform, p_cam_projection, sky, false, true, false, false, use_shadows);
  3499. } else {
  3500. for (int i = 0; i < state.directional_light_count; i++) {
  3501. directional_light = directional_lights[i];
  3502. _setup_directional_light(i, p_cam_transform.affine_inverse(), use_shadows);
  3503. _render_list(&render_list.elements[render_list.max_elements - render_list.alpha_element_count], render_list.alpha_element_count, p_cam_transform, p_cam_projection, sky, false, true, false, i > 0, use_shadows);
  3504. }
  3505. }
  3506. if (probe) {
  3507. //rendering a probe, do no more!
  3508. return;
  3509. }
  3510. if (env && (env->dof_blur_far_enabled || env->dof_blur_near_enabled) && storage->frame.current_rt && storage->frame.current_rt->buffers.active)
  3511. _prepare_depth_texture();
  3512. _post_process(env, p_cam_projection);
  3513. // Needed only for debugging
  3514. /* if (shadow_atlas && storage->frame.current_rt) {
  3515. //_copy_texture_to_front_buffer(shadow_atlas->depth);
  3516. storage->canvas->canvas_begin();
  3517. glActiveTexture(GL_TEXTURE0);
  3518. glBindTexture(GL_TEXTURE_2D, shadow_atlas->depth);
  3519. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE);
  3520. storage->canvas->draw_generic_textured_rect(Rect2(0, 0, storage->frame.current_rt->width / 2, storage->frame.current_rt->height / 2), Rect2(0, 0, 1, 1));
  3521. }
  3522. if (storage->frame.current_rt) {
  3523. //_copy_texture_to_front_buffer(shadow_atlas->depth);
  3524. storage->canvas->canvas_begin();
  3525. glActiveTexture(GL_TEXTURE0);
  3526. glBindTexture(GL_TEXTURE_2D, exposure_shrink[4].color);
  3527. //glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->exposure.color);
  3528. storage->canvas->draw_generic_textured_rect(Rect2(0, 0, storage->frame.current_rt->width / 16, storage->frame.current_rt->height / 16), Rect2(0, 0, 1, 1));
  3529. }
  3530. if (reflection_atlas && storage->frame.current_rt) {
  3531. //_copy_texture_to_front_buffer(shadow_atlas->depth);
  3532. storage->canvas->canvas_begin();
  3533. glActiveTexture(GL_TEXTURE0);
  3534. glBindTexture(GL_TEXTURE_2D, reflection_atlas->color);
  3535. storage->canvas->draw_generic_textured_rect(Rect2(0, 0, storage->frame.current_rt->width / 2, storage->frame.current_rt->height / 2), Rect2(0, 0, 1, 1));
  3536. }
  3537. if (directional_shadow.fbo) {
  3538. //_copy_texture_to_front_buffer(shadow_atlas->depth);
  3539. storage->canvas->canvas_begin();
  3540. glActiveTexture(GL_TEXTURE0);
  3541. glBindTexture(GL_TEXTURE_2D, directional_shadow.depth);
  3542. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE);
  3543. storage->canvas->draw_generic_textured_rect(Rect2(0, 0, storage->frame.current_rt->width / 2, storage->frame.current_rt->height / 2), Rect2(0, 0, 1, 1));
  3544. }
  3545. if ( env_radiance_tex) {
  3546. //_copy_texture_to_front_buffer(shadow_atlas->depth);
  3547. storage->canvas->canvas_begin();
  3548. glActiveTexture(GL_TEXTURE0);
  3549. glBindTexture(GL_TEXTURE_2D, env_radiance_tex);
  3550. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  3551. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  3552. storage->canvas->draw_generic_textured_rect(Rect2(0, 0, storage->frame.current_rt->width / 2, storage->frame.current_rt->height / 2), Rect2(0, 0, 1, 1));
  3553. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
  3554. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  3555. }*/
  3556. //disable all stuff
  3557. }
  3558. void RasterizerSceneGLES3::render_shadow(RID p_light, RID p_shadow_atlas, int p_pass, InstanceBase **p_cull_result, int p_cull_count) {
  3559. render_pass++;
  3560. directional_light = NULL;
  3561. LightInstance *light_instance = light_instance_owner.getornull(p_light);
  3562. ERR_FAIL_COND(!light_instance);
  3563. RasterizerStorageGLES3::Light *light = storage->light_owner.getornull(light_instance->light);
  3564. ERR_FAIL_COND(!light);
  3565. uint32_t x, y, width, height;
  3566. float dp_direction = 0.0;
  3567. float zfar = 0;
  3568. bool flip_facing = false;
  3569. int custom_vp_size = 0;
  3570. GLuint fbo;
  3571. int current_cubemap = -1;
  3572. float bias = 0;
  3573. float normal_bias = 0;
  3574. state.used_depth_prepass = false;
  3575. CameraMatrix light_projection;
  3576. Transform light_transform;
  3577. if (light->type == VS::LIGHT_DIRECTIONAL) {
  3578. //set pssm stuff
  3579. if (light_instance->last_scene_shadow_pass != scene_pass) {
  3580. //assign rect if unassigned
  3581. light_instance->light_directional_index = directional_shadow.current_light;
  3582. light_instance->last_scene_shadow_pass = scene_pass;
  3583. directional_shadow.current_light++;
  3584. if (directional_shadow.light_count == 1) {
  3585. light_instance->directional_rect = Rect2(0, 0, directional_shadow.size, directional_shadow.size);
  3586. } else if (directional_shadow.light_count == 2) {
  3587. light_instance->directional_rect = Rect2(0, 0, directional_shadow.size, directional_shadow.size / 2);
  3588. if (light_instance->light_directional_index == 1) {
  3589. light_instance->directional_rect.position.x += light_instance->directional_rect.size.x;
  3590. }
  3591. } else { //3 and 4
  3592. light_instance->directional_rect = Rect2(0, 0, directional_shadow.size / 2, directional_shadow.size / 2);
  3593. if (light_instance->light_directional_index & 1) {
  3594. light_instance->directional_rect.position.x += light_instance->directional_rect.size.x;
  3595. }
  3596. if (light_instance->light_directional_index / 2) {
  3597. light_instance->directional_rect.position.y += light_instance->directional_rect.size.y;
  3598. }
  3599. }
  3600. }
  3601. light_projection = light_instance->shadow_transform[p_pass].camera;
  3602. light_transform = light_instance->shadow_transform[p_pass].transform;
  3603. x = light_instance->directional_rect.position.x;
  3604. y = light_instance->directional_rect.position.y;
  3605. width = light_instance->directional_rect.size.x;
  3606. height = light_instance->directional_rect.size.y;
  3607. if (light->directional_shadow_mode == VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS) {
  3608. width /= 2;
  3609. height /= 2;
  3610. if (p_pass == 1) {
  3611. x += width;
  3612. } else if (p_pass == 2) {
  3613. y += height;
  3614. } else if (p_pass == 3) {
  3615. x += width;
  3616. y += height;
  3617. }
  3618. } else if (light->directional_shadow_mode == VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS) {
  3619. height /= 2;
  3620. if (p_pass == 0) {
  3621. } else {
  3622. y += height;
  3623. }
  3624. }
  3625. float bias_mult = Math::lerp(1.0f, light_instance->shadow_transform[p_pass].bias_scale, light->param[VS::LIGHT_PARAM_SHADOW_BIAS_SPLIT_SCALE]);
  3626. zfar = light->param[VS::LIGHT_PARAM_RANGE];
  3627. bias = light->param[VS::LIGHT_PARAM_SHADOW_BIAS] * bias_mult;
  3628. normal_bias = light->param[VS::LIGHT_PARAM_SHADOW_NORMAL_BIAS] * bias_mult;
  3629. fbo = directional_shadow.fbo;
  3630. } else {
  3631. //set from shadow atlas
  3632. ShadowAtlas *shadow_atlas = shadow_atlas_owner.getornull(p_shadow_atlas);
  3633. ERR_FAIL_COND(!shadow_atlas);
  3634. ERR_FAIL_COND(!shadow_atlas->shadow_owners.has(p_light));
  3635. fbo = shadow_atlas->fbo;
  3636. uint32_t key = shadow_atlas->shadow_owners[p_light];
  3637. uint32_t quadrant = (key >> ShadowAtlas::QUADRANT_SHIFT) & 0x3;
  3638. uint32_t shadow = key & ShadowAtlas::SHADOW_INDEX_MASK;
  3639. ERR_FAIL_INDEX((int)shadow, shadow_atlas->quadrants[quadrant].shadows.size());
  3640. uint32_t quadrant_size = shadow_atlas->size >> 1;
  3641. x = (quadrant & 1) * quadrant_size;
  3642. y = (quadrant >> 1) * quadrant_size;
  3643. uint32_t shadow_size = (quadrant_size / shadow_atlas->quadrants[quadrant].subdivision);
  3644. x += (shadow % shadow_atlas->quadrants[quadrant].subdivision) * shadow_size;
  3645. y += (shadow / shadow_atlas->quadrants[quadrant].subdivision) * shadow_size;
  3646. width = shadow_size;
  3647. height = shadow_size;
  3648. if (light->type == VS::LIGHT_OMNI) {
  3649. if (light->omni_shadow_mode == VS::LIGHT_OMNI_SHADOW_CUBE) {
  3650. int cubemap_index = shadow_cubemaps.size() - 1;
  3651. for (int i = shadow_cubemaps.size() - 1; i >= 0; i--) {
  3652. //find appropriate cubemap to render to
  3653. if (shadow_cubemaps[i].size > shadow_size)
  3654. break;
  3655. cubemap_index = i;
  3656. }
  3657. fbo = shadow_cubemaps[cubemap_index].fbo_id[p_pass];
  3658. light_projection = light_instance->shadow_transform[0].camera;
  3659. light_transform = light_instance->shadow_transform[0].transform;
  3660. custom_vp_size = shadow_cubemaps[cubemap_index].size;
  3661. zfar = light->param[VS::LIGHT_PARAM_RANGE];
  3662. current_cubemap = cubemap_index;
  3663. } else {
  3664. light_projection = light_instance->shadow_transform[0].camera;
  3665. light_transform = light_instance->shadow_transform[0].transform;
  3666. if (light->omni_shadow_detail == VS::LIGHT_OMNI_SHADOW_DETAIL_HORIZONTAL) {
  3667. height /= 2;
  3668. y += p_pass * height;
  3669. } else {
  3670. width /= 2;
  3671. x += p_pass * width;
  3672. }
  3673. dp_direction = p_pass == 0 ? 1.0 : -1.0;
  3674. flip_facing = (p_pass == 1);
  3675. zfar = light->param[VS::LIGHT_PARAM_RANGE];
  3676. bias = light->param[VS::LIGHT_PARAM_SHADOW_BIAS];
  3677. state.scene_shader.set_conditional(SceneShaderGLES3::RENDER_DEPTH_DUAL_PARABOLOID, true);
  3678. }
  3679. } else if (light->type == VS::LIGHT_SPOT) {
  3680. light_projection = light_instance->shadow_transform[0].camera;
  3681. light_transform = light_instance->shadow_transform[0].transform;
  3682. dp_direction = 1.0;
  3683. flip_facing = false;
  3684. zfar = light->param[VS::LIGHT_PARAM_RANGE];
  3685. bias = light->param[VS::LIGHT_PARAM_SHADOW_BIAS];
  3686. normal_bias = light->param[VS::LIGHT_PARAM_SHADOW_NORMAL_BIAS];
  3687. }
  3688. }
  3689. render_list.clear();
  3690. _fill_render_list(p_cull_result, p_cull_count, true, true);
  3691. render_list.sort_by_depth(false); //shadow is front to back for performance
  3692. glDisable(GL_BLEND);
  3693. glDisable(GL_DITHER);
  3694. glEnable(GL_DEPTH_TEST);
  3695. glBindFramebuffer(GL_FRAMEBUFFER, fbo);
  3696. glDepthMask(true);
  3697. glColorMask(0, 0, 0, 0);
  3698. if (custom_vp_size) {
  3699. glViewport(0, 0, custom_vp_size, custom_vp_size);
  3700. glScissor(0, 0, custom_vp_size, custom_vp_size);
  3701. } else {
  3702. glViewport(x, y, width, height);
  3703. glScissor(x, y, width, height);
  3704. }
  3705. glEnable(GL_SCISSOR_TEST);
  3706. glClearDepth(1.0f);
  3707. glClear(GL_DEPTH_BUFFER_BIT);
  3708. glDisable(GL_SCISSOR_TEST);
  3709. state.ubo_data.z_offset = bias;
  3710. state.ubo_data.z_slope_scale = normal_bias;
  3711. state.ubo_data.shadow_dual_paraboloid_render_side = dp_direction;
  3712. state.ubo_data.shadow_dual_paraboloid_render_zfar = zfar;
  3713. state.ubo_data.opaque_prepass_threshold = 0.1;
  3714. _setup_environment(NULL, light_projection, light_transform);
  3715. state.scene_shader.set_conditional(SceneShaderGLES3::RENDER_DEPTH, true);
  3716. if (light->reverse_cull) {
  3717. flip_facing = !flip_facing;
  3718. }
  3719. _render_list(render_list.elements, render_list.element_count, light_transform, light_projection, NULL, flip_facing, false, true, false, false);
  3720. state.scene_shader.set_conditional(SceneShaderGLES3::RENDER_DEPTH, false);
  3721. state.scene_shader.set_conditional(SceneShaderGLES3::RENDER_DEPTH_DUAL_PARABOLOID, false);
  3722. if (light->type == VS::LIGHT_OMNI && light->omni_shadow_mode == VS::LIGHT_OMNI_SHADOW_CUBE && p_pass == 5) {
  3723. //convert the chosen cubemap to dual paraboloid!
  3724. ShadowAtlas *shadow_atlas = shadow_atlas_owner.getornull(p_shadow_atlas);
  3725. glBindFramebuffer(GL_FRAMEBUFFER, shadow_atlas->fbo);
  3726. state.cube_to_dp_shader.bind();
  3727. glActiveTexture(GL_TEXTURE0);
  3728. glBindTexture(GL_TEXTURE_CUBE_MAP, shadow_cubemaps[current_cubemap].cubemap);
  3729. glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_COMPARE_MODE, GL_NONE);
  3730. glDisable(GL_CULL_FACE);
  3731. for (int i = 0; i < 2; i++) {
  3732. state.cube_to_dp_shader.set_uniform(CubeToDpShaderGLES3::Z_FLIP, i == 1);
  3733. state.cube_to_dp_shader.set_uniform(CubeToDpShaderGLES3::Z_NEAR, light_projection.get_z_near());
  3734. state.cube_to_dp_shader.set_uniform(CubeToDpShaderGLES3::Z_FAR, light_projection.get_z_far());
  3735. state.cube_to_dp_shader.set_uniform(CubeToDpShaderGLES3::BIAS, light->param[VS::LIGHT_PARAM_SHADOW_BIAS]);
  3736. uint32_t local_width = width, local_height = height;
  3737. uint32_t local_x = x, local_y = y;
  3738. if (light->omni_shadow_detail == VS::LIGHT_OMNI_SHADOW_DETAIL_HORIZONTAL) {
  3739. local_height /= 2;
  3740. local_y += i * local_height;
  3741. } else {
  3742. local_width /= 2;
  3743. local_x += i * local_width;
  3744. }
  3745. glViewport(local_x, local_y, local_width, local_height);
  3746. glScissor(local_x, local_y, local_width, local_height);
  3747. glEnable(GL_SCISSOR_TEST);
  3748. glClearDepth(1.0f);
  3749. glClear(GL_DEPTH_BUFFER_BIT);
  3750. glDisable(GL_SCISSOR_TEST);
  3751. //glDisable(GL_DEPTH_TEST);
  3752. glDisable(GL_BLEND);
  3753. _copy_screen();
  3754. }
  3755. }
  3756. glColorMask(1, 1, 1, 1);
  3757. }
  3758. void RasterizerSceneGLES3::set_scene_pass(uint64_t p_pass) {
  3759. scene_pass = p_pass;
  3760. }
  3761. bool RasterizerSceneGLES3::free(RID p_rid) {
  3762. if (light_instance_owner.owns(p_rid)) {
  3763. LightInstance *light_instance = light_instance_owner.getptr(p_rid);
  3764. // Make sure first_directional_light is invalidated
  3765. if (p_rid == first_directional_light) {
  3766. first_directional_light = RID();
  3767. }
  3768. //remove from shadow atlases..
  3769. for (Set<RID>::Element *E = light_instance->shadow_atlases.front(); E; E = E->next()) {
  3770. ShadowAtlas *shadow_atlas = shadow_atlas_owner.get(E->get());
  3771. ERR_CONTINUE(!shadow_atlas->shadow_owners.has(p_rid));
  3772. uint32_t key = shadow_atlas->shadow_owners[p_rid];
  3773. uint32_t q = (key >> ShadowAtlas::QUADRANT_SHIFT) & 0x3;
  3774. uint32_t s = key & ShadowAtlas::SHADOW_INDEX_MASK;
  3775. shadow_atlas->quadrants[q].shadows.write[s].owner = RID();
  3776. shadow_atlas->shadow_owners.erase(p_rid);
  3777. }
  3778. light_instance_owner.free(p_rid);
  3779. memdelete(light_instance);
  3780. } else if (shadow_atlas_owner.owns(p_rid)) {
  3781. ShadowAtlas *shadow_atlas = shadow_atlas_owner.get(p_rid);
  3782. shadow_atlas_set_size(p_rid, 0);
  3783. shadow_atlas_owner.free(p_rid);
  3784. memdelete(shadow_atlas);
  3785. } else if (reflection_atlas_owner.owns(p_rid)) {
  3786. ReflectionAtlas *reflection_atlas = reflection_atlas_owner.get(p_rid);
  3787. reflection_atlas_set_size(p_rid, 0);
  3788. reflection_atlas_owner.free(p_rid);
  3789. memdelete(reflection_atlas);
  3790. } else if (reflection_probe_instance_owner.owns(p_rid)) {
  3791. ReflectionProbeInstance *reflection_instance = reflection_probe_instance_owner.get(p_rid);
  3792. reflection_probe_release_atlas_index(p_rid);
  3793. reflection_probe_instance_owner.free(p_rid);
  3794. memdelete(reflection_instance);
  3795. } else if (environment_owner.owns(p_rid)) {
  3796. Environment *environment = environment_owner.get(p_rid);
  3797. environment_owner.free(p_rid);
  3798. memdelete(environment);
  3799. } else if (gi_probe_instance_owner.owns(p_rid)) {
  3800. GIProbeInstance *gi_probe_instance = gi_probe_instance_owner.get(p_rid);
  3801. gi_probe_instance_owner.free(p_rid);
  3802. memdelete(gi_probe_instance);
  3803. } else {
  3804. return false;
  3805. }
  3806. return true;
  3807. }
  3808. void RasterizerSceneGLES3::set_debug_draw_mode(VS::ViewportDebugDraw p_debug_draw) {
  3809. state.debug_draw = p_debug_draw;
  3810. }
  3811. void RasterizerSceneGLES3::initialize() {
  3812. render_pass = 0;
  3813. state.scene_shader.init();
  3814. {
  3815. //default material and shader
  3816. default_shader = storage->shader_create();
  3817. storage->shader_set_code(default_shader, "shader_type spatial;\n");
  3818. default_material = storage->material_create();
  3819. storage->material_set_shader(default_material, default_shader);
  3820. default_shader_twosided = storage->shader_create();
  3821. default_material_twosided = storage->material_create();
  3822. storage->shader_set_code(default_shader_twosided, "shader_type spatial; render_mode cull_disabled;\n");
  3823. storage->material_set_shader(default_material_twosided, default_shader_twosided);
  3824. //default for shaders using world coordinates (typical for triplanar)
  3825. default_worldcoord_shader = storage->shader_create();
  3826. storage->shader_set_code(default_worldcoord_shader, "shader_type spatial; render_mode world_vertex_coords;\n");
  3827. default_worldcoord_material = storage->material_create();
  3828. storage->material_set_shader(default_worldcoord_material, default_worldcoord_shader);
  3829. default_worldcoord_shader_twosided = storage->shader_create();
  3830. default_worldcoord_material_twosided = storage->material_create();
  3831. storage->shader_set_code(default_worldcoord_shader_twosided, "shader_type spatial; render_mode cull_disabled,world_vertex_coords;\n");
  3832. storage->material_set_shader(default_worldcoord_material_twosided, default_worldcoord_shader_twosided);
  3833. }
  3834. {
  3835. //default material and shader
  3836. default_overdraw_shader = storage->shader_create();
  3837. storage->shader_set_code(default_overdraw_shader, "shader_type spatial;\nrender_mode blend_add,unshaded;\n void fragment() { ALBEDO=vec3(0.4,0.8,0.8); ALPHA=0.2; }");
  3838. default_overdraw_material = storage->material_create();
  3839. storage->material_set_shader(default_overdraw_material, default_overdraw_shader);
  3840. }
  3841. glGenBuffers(1, &state.scene_ubo);
  3842. glBindBuffer(GL_UNIFORM_BUFFER, state.scene_ubo);
  3843. glBufferData(GL_UNIFORM_BUFFER, sizeof(State::SceneDataUBO), &state.scene_ubo, GL_DYNAMIC_DRAW);
  3844. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  3845. glGenBuffers(1, &state.env_radiance_ubo);
  3846. glBindBuffer(GL_UNIFORM_BUFFER, state.env_radiance_ubo);
  3847. glBufferData(GL_UNIFORM_BUFFER, sizeof(State::EnvironmentRadianceUBO), &state.env_radiance_ubo, GL_DYNAMIC_DRAW);
  3848. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  3849. render_list.max_elements = GLOBAL_DEF_RST("rendering/limits/rendering/max_renderable_elements", (int)RenderList::DEFAULT_MAX_ELEMENTS);
  3850. ProjectSettings::get_singleton()->set_custom_property_info("rendering/limits/rendering/max_renderable_elements", PropertyInfo(Variant::INT, "rendering/limits/rendering/max_renderable_elements", PROPERTY_HINT_RANGE, "1024,65536,1"));
  3851. render_list.max_lights = GLOBAL_DEF("rendering/limits/rendering/max_renderable_lights", (int)RenderList::DEFAULT_MAX_LIGHTS);
  3852. ProjectSettings::get_singleton()->set_custom_property_info("rendering/limits/rendering/max_renderable_lights", PropertyInfo(Variant::INT, "rendering/limits/rendering/max_renderable_lights", PROPERTY_HINT_RANGE, "16,4096,1"));
  3853. render_list.max_reflections = GLOBAL_DEF("rendering/limits/rendering/max_renderable_reflections", (int)RenderList::DEFAULT_MAX_REFLECTIONS);
  3854. ProjectSettings::get_singleton()->set_custom_property_info("rendering/limits/rendering/max_renderable_reflections", PropertyInfo(Variant::INT, "rendering/limits/rendering/max_renderable_reflections", PROPERTY_HINT_RANGE, "8,1024,1"));
  3855. render_list.max_lights_per_object = GLOBAL_DEF_RST("rendering/limits/rendering/max_lights_per_object", (int)RenderList::DEFAULT_MAX_LIGHTS_PER_OBJECT);
  3856. ProjectSettings::get_singleton()->set_custom_property_info("rendering/limits/rendering/max_lights_per_object", PropertyInfo(Variant::INT, "rendering/limits/rendering/max_lights_per_object", PROPERTY_HINT_RANGE, "8,1024,1"));
  3857. {
  3858. //quad buffers
  3859. glGenBuffers(1, &state.sky_verts);
  3860. glBindBuffer(GL_ARRAY_BUFFER, state.sky_verts);
  3861. glBufferData(GL_ARRAY_BUFFER, sizeof(Vector3) * 8, NULL, GL_DYNAMIC_DRAW);
  3862. glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind
  3863. glGenVertexArrays(1, &state.sky_array);
  3864. glBindVertexArray(state.sky_array);
  3865. glBindBuffer(GL_ARRAY_BUFFER, state.sky_verts);
  3866. glVertexAttribPointer(VS::ARRAY_VERTEX, 3, GL_FLOAT, GL_FALSE, sizeof(Vector3) * 2, 0);
  3867. glEnableVertexAttribArray(VS::ARRAY_VERTEX);
  3868. glVertexAttribPointer(VS::ARRAY_TEX_UV, 3, GL_FLOAT, GL_FALSE, sizeof(Vector3) * 2, CAST_INT_TO_UCHAR_PTR(sizeof(Vector3)));
  3869. glEnableVertexAttribArray(VS::ARRAY_TEX_UV);
  3870. glBindVertexArray(0);
  3871. glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind
  3872. }
  3873. render_list.init();
  3874. state.cube_to_dp_shader.init();
  3875. shadow_atlas_realloc_tolerance_msec = 500;
  3876. int max_shadow_cubemap_sampler_size = MIN(int(GLOBAL_GET("rendering/quality/shadow_atlas/cubemap_size")), storage->config.max_cubemap_texture_size);
  3877. int cube_size = max_shadow_cubemap_sampler_size;
  3878. glActiveTexture(GL_TEXTURE0);
  3879. while (cube_size >= 32) {
  3880. ShadowCubeMap cube;
  3881. cube.size = cube_size;
  3882. glGenTextures(1, &cube.cubemap);
  3883. glBindTexture(GL_TEXTURE_CUBE_MAP, cube.cubemap);
  3884. //gen cubemap first
  3885. for (int i = 0; i < 6; i++) {
  3886. glTexImage2D(_cube_side_enum[i], 0, GL_DEPTH_COMPONENT24, cube.size, cube.size, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL);
  3887. }
  3888. glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  3889. glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  3890. // Remove artifact on the edges of the shadowmap
  3891. glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  3892. glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  3893. glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
  3894. //gen renderbuffers second, because it needs a complete cubemap
  3895. for (int i = 0; i < 6; i++) {
  3896. glGenFramebuffers(1, &cube.fbo_id[i]);
  3897. glBindFramebuffer(GL_FRAMEBUFFER, cube.fbo_id[i]);
  3898. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, _cube_side_enum[i], cube.cubemap, 0);
  3899. GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
  3900. ERR_CONTINUE(status != GL_FRAMEBUFFER_COMPLETE);
  3901. }
  3902. shadow_cubemaps.push_back(cube);
  3903. cube_size >>= 1;
  3904. }
  3905. {
  3906. //directional light shadow
  3907. directional_shadow.light_count = 0;
  3908. directional_shadow.size = next_power_of_2(GLOBAL_GET("rendering/quality/directional_shadow/size"));
  3909. glGenFramebuffers(1, &directional_shadow.fbo);
  3910. glBindFramebuffer(GL_FRAMEBUFFER, directional_shadow.fbo);
  3911. glGenTextures(1, &directional_shadow.depth);
  3912. glBindTexture(GL_TEXTURE_2D, directional_shadow.depth);
  3913. glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, directional_shadow.size, directional_shadow.size, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL);
  3914. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  3915. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  3916. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  3917. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  3918. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
  3919. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, directional_shadow.depth, 0);
  3920. GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
  3921. if (status != GL_FRAMEBUFFER_COMPLETE) {
  3922. ERR_PRINT("Directional shadow framebuffer status invalid");
  3923. }
  3924. }
  3925. {
  3926. //spot and omni ubos
  3927. int max_ubo_size;
  3928. glGetIntegerv(GL_MAX_UNIFORM_BLOCK_SIZE, &max_ubo_size);
  3929. const int ubo_light_size = 160;
  3930. state.ubo_light_size = ubo_light_size;
  3931. state.max_ubo_lights = MIN(render_list.max_lights, max_ubo_size / ubo_light_size);
  3932. state.spot_array_tmp = (uint8_t *)memalloc(ubo_light_size * state.max_ubo_lights);
  3933. state.omni_array_tmp = (uint8_t *)memalloc(ubo_light_size * state.max_ubo_lights);
  3934. glGenBuffers(1, &state.spot_array_ubo);
  3935. glBindBuffer(GL_UNIFORM_BUFFER, state.spot_array_ubo);
  3936. glBufferData(GL_UNIFORM_BUFFER, ubo_light_size * state.max_ubo_lights, NULL, GL_DYNAMIC_DRAW);
  3937. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  3938. glGenBuffers(1, &state.omni_array_ubo);
  3939. glBindBuffer(GL_UNIFORM_BUFFER, state.omni_array_ubo);
  3940. glBufferData(GL_UNIFORM_BUFFER, ubo_light_size * state.max_ubo_lights, NULL, GL_DYNAMIC_DRAW);
  3941. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  3942. glGenBuffers(1, &state.directional_ubo);
  3943. glBindBuffer(GL_UNIFORM_BUFFER, state.directional_ubo);
  3944. glBufferData(GL_UNIFORM_BUFFER, sizeof(LightDataUBO), NULL, GL_DYNAMIC_DRAW);
  3945. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  3946. state.max_forward_lights_per_object = MIN(state.max_ubo_lights, render_list.max_lights_per_object);
  3947. state.scene_shader.add_custom_define("#define MAX_LIGHT_DATA_STRUCTS " + itos(state.max_ubo_lights) + "\n");
  3948. state.scene_shader.add_custom_define("#define MAX_FORWARD_LIGHTS " + itos(state.max_forward_lights_per_object) + "\n");
  3949. state.max_ubo_reflections = MIN(render_list.max_reflections, max_ubo_size / (int)sizeof(ReflectionProbeDataUBO));
  3950. state.reflection_array_tmp = (uint8_t *)memalloc(sizeof(ReflectionProbeDataUBO) * state.max_ubo_reflections);
  3951. glGenBuffers(1, &state.reflection_array_ubo);
  3952. glBindBuffer(GL_UNIFORM_BUFFER, state.reflection_array_ubo);
  3953. glBufferData(GL_UNIFORM_BUFFER, sizeof(ReflectionProbeDataUBO) * state.max_ubo_reflections, NULL, GL_DYNAMIC_DRAW);
  3954. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  3955. state.scene_shader.add_custom_define("#define MAX_REFLECTION_DATA_STRUCTS " + itos(state.max_ubo_reflections) + "\n");
  3956. state.max_skeleton_bones = MIN(2048, max_ubo_size / (12 * sizeof(float)));
  3957. state.scene_shader.add_custom_define("#define MAX_SKELETON_BONES " + itos(state.max_skeleton_bones) + "\n");
  3958. }
  3959. shadow_filter_mode = SHADOW_FILTER_NEAREST;
  3960. { //reflection cubemaps
  3961. int max_reflection_cubemap_sampler_size = 512;
  3962. int rcube_size = max_reflection_cubemap_sampler_size;
  3963. glActiveTexture(GL_TEXTURE0);
  3964. bool use_float = true;
  3965. GLenum internal_format = use_float ? GL_RGBA16F : GL_RGB10_A2;
  3966. GLenum format = GL_RGBA;
  3967. GLenum type = use_float ? GL_HALF_FLOAT : GL_UNSIGNED_INT_2_10_10_10_REV;
  3968. while (rcube_size >= 32) {
  3969. ReflectionCubeMap cube;
  3970. cube.size = rcube_size;
  3971. glGenTextures(1, &cube.depth);
  3972. glBindTexture(GL_TEXTURE_2D, cube.depth);
  3973. glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, cube.size, cube.size, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL);
  3974. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  3975. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  3976. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  3977. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  3978. glGenTextures(1, &cube.cubemap);
  3979. glBindTexture(GL_TEXTURE_CUBE_MAP, cube.cubemap);
  3980. //gen cubemap first
  3981. for (int i = 0; i < 6; i++) {
  3982. glTexImage2D(_cube_side_enum[i], 0, internal_format, cube.size, cube.size, 0, format, type, NULL);
  3983. }
  3984. glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  3985. glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  3986. // Remove artifact on the edges of the reflectionmap
  3987. glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  3988. glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  3989. glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
  3990. //gen renderbuffers second, because it needs a complete cubemap
  3991. for (int i = 0; i < 6; i++) {
  3992. glGenFramebuffers(1, &cube.fbo_id[i]);
  3993. glBindFramebuffer(GL_FRAMEBUFFER, cube.fbo_id[i]);
  3994. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, _cube_side_enum[i], cube.cubemap, 0);
  3995. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, cube.depth, 0);
  3996. GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
  3997. ERR_CONTINUE(status != GL_FRAMEBUFFER_COMPLETE);
  3998. }
  3999. reflection_cubemaps.push_back(cube);
  4000. rcube_size >>= 1;
  4001. }
  4002. }
  4003. {
  4004. uint32_t immediate_buffer_size = GLOBAL_DEF("rendering/limits/buffers/immediate_buffer_size_kb", 2048);
  4005. ProjectSettings::get_singleton()->set_custom_property_info("rendering/limits/buffers/immediate_buffer_size_kb", PropertyInfo(Variant::INT, "rendering/limits/buffers/immediate_buffer_size_kb", PROPERTY_HINT_RANGE, "0,8192,1,or_greater"));
  4006. glGenBuffers(1, &state.immediate_buffer);
  4007. glBindBuffer(GL_ARRAY_BUFFER, state.immediate_buffer);
  4008. glBufferData(GL_ARRAY_BUFFER, immediate_buffer_size * 1024, NULL, GL_DYNAMIC_DRAW);
  4009. glBindBuffer(GL_ARRAY_BUFFER, 0);
  4010. glGenVertexArrays(1, &state.immediate_array);
  4011. }
  4012. #ifdef GLES_OVER_GL
  4013. //"desktop" opengl needs this.
  4014. glEnable(GL_PROGRAM_POINT_SIZE);
  4015. #endif
  4016. state.resolve_shader.init();
  4017. state.ssr_shader.init();
  4018. state.effect_blur_shader.init();
  4019. state.sss_shader.init();
  4020. state.ssao_minify_shader.init();
  4021. state.ssao_shader.init();
  4022. state.ssao_blur_shader.init();
  4023. state.exposure_shader.init();
  4024. state.tonemap_shader.init();
  4025. {
  4026. GLOBAL_DEF("rendering/quality/subsurface_scattering/quality", 1);
  4027. ProjectSettings::get_singleton()->set_custom_property_info("rendering/quality/subsurface_scattering/quality", PropertyInfo(Variant::INT, "rendering/quality/subsurface_scattering/quality", PROPERTY_HINT_ENUM, "Low,Medium,High"));
  4028. GLOBAL_DEF("rendering/quality/subsurface_scattering/scale", 1.0);
  4029. ProjectSettings::get_singleton()->set_custom_property_info("rendering/quality/subsurface_scattering/scale", PropertyInfo(Variant::INT, "rendering/quality/subsurface_scattering/scale", PROPERTY_HINT_RANGE, "0.01,8,0.01"));
  4030. GLOBAL_DEF("rendering/quality/subsurface_scattering/follow_surface", false);
  4031. GLOBAL_DEF("rendering/quality/subsurface_scattering/weight_samples", true);
  4032. GLOBAL_DEF("rendering/quality/voxel_cone_tracing/high_quality", false);
  4033. }
  4034. exposure_shrink_size = 243;
  4035. int max_exposure_shrink_size = exposure_shrink_size;
  4036. while (max_exposure_shrink_size > 0) {
  4037. RasterizerStorageGLES3::RenderTarget::Exposure e;
  4038. glGenFramebuffers(1, &e.fbo);
  4039. glBindFramebuffer(GL_FRAMEBUFFER, e.fbo);
  4040. glGenTextures(1, &e.color);
  4041. glBindTexture(GL_TEXTURE_2D, e.color);
  4042. if (storage->config.framebuffer_float_supported) {
  4043. glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F, max_exposure_shrink_size, max_exposure_shrink_size, 0, GL_RED, GL_FLOAT, NULL);
  4044. } else if (storage->config.framebuffer_half_float_supported) {
  4045. glTexImage2D(GL_TEXTURE_2D, 0, GL_R16F, max_exposure_shrink_size, max_exposure_shrink_size, 0, GL_RED, GL_HALF_FLOAT, NULL);
  4046. } else {
  4047. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB10_A2, max_exposure_shrink_size, max_exposure_shrink_size, 0, GL_RED, GL_UNSIGNED_INT_2_10_10_10_REV, NULL);
  4048. }
  4049. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, e.color, 0);
  4050. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  4051. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  4052. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  4053. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  4054. exposure_shrink.push_back(e);
  4055. max_exposure_shrink_size /= 3;
  4056. GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
  4057. ERR_CONTINUE(status != GL_FRAMEBUFFER_COMPLETE);
  4058. }
  4059. state.debug_draw = VS::VIEWPORT_DEBUG_DRAW_DISABLED;
  4060. glFrontFace(GL_CW);
  4061. }
  4062. void RasterizerSceneGLES3::iteration() {
  4063. shadow_filter_mode = ShadowFilterMode(int(GLOBAL_GET("rendering/quality/shadows/filter_mode")));
  4064. subsurface_scatter_follow_surface = GLOBAL_GET("rendering/quality/subsurface_scattering/follow_surface");
  4065. subsurface_scatter_weight_samples = GLOBAL_GET("rendering/quality/subsurface_scattering/weight_samples");
  4066. subsurface_scatter_quality = SubSurfaceScatterQuality(int(GLOBAL_GET("rendering/quality/subsurface_scattering/quality")));
  4067. subsurface_scatter_size = GLOBAL_GET("rendering/quality/subsurface_scattering/scale");
  4068. storage->config.use_lightmap_filter_bicubic = GLOBAL_GET("rendering/quality/lightmapping/use_bicubic_sampling");
  4069. state.scene_shader.set_conditional(SceneShaderGLES3::USE_LIGHTMAP_FILTER_BICUBIC, storage->config.use_lightmap_filter_bicubic);
  4070. state.scene_shader.set_conditional(SceneShaderGLES3::VCT_QUALITY_HIGH, GLOBAL_GET("rendering/quality/voxel_cone_tracing/high_quality"));
  4071. }
  4072. void RasterizerSceneGLES3::finalize() {
  4073. }
  4074. RasterizerSceneGLES3::RasterizerSceneGLES3() {
  4075. }
  4076. RasterizerSceneGLES3::~RasterizerSceneGLES3() {
  4077. memdelete(default_material.get_data());
  4078. memdelete(default_material_twosided.get_data());
  4079. memdelete(default_shader.get_data());
  4080. memdelete(default_shader_twosided.get_data());
  4081. memdelete(default_worldcoord_material.get_data());
  4082. memdelete(default_worldcoord_material_twosided.get_data());
  4083. memdelete(default_worldcoord_shader.get_data());
  4084. memdelete(default_worldcoord_shader_twosided.get_data());
  4085. memdelete(default_overdraw_material.get_data());
  4086. memdelete(default_overdraw_shader.get_data());
  4087. memfree(state.spot_array_tmp);
  4088. memfree(state.omni_array_tmp);
  4089. memfree(state.reflection_array_tmp);
  4090. }