rasterizer_scene_gles3.cpp 189 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421
  1. /**************************************************************************/
  2. /* rasterizer_scene_gles3.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  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 "drivers/gles3/effects/copy_effects.h"
  32. #include "drivers/gles3/effects/feed_effects.h"
  33. #include "rasterizer_gles3.h"
  34. #include "storage/config.h"
  35. #include "storage/mesh_storage.h"
  36. #include "storage/particles_storage.h"
  37. #include "storage/texture_storage.h"
  38. #include "core/config/project_settings.h"
  39. #include "core/templates/sort_array.h"
  40. #include "servers/camera/camera_feed.h"
  41. #include "servers/camera_server.h"
  42. #include "servers/rendering/rendering_server_default.h"
  43. #include "servers/rendering/rendering_server_globals.h"
  44. #ifdef GLES3_ENABLED
  45. RasterizerSceneGLES3 *RasterizerSceneGLES3::singleton = nullptr;
  46. RenderGeometryInstance *RasterizerSceneGLES3::geometry_instance_create(RID p_base) {
  47. RS::InstanceType type = RSG::utilities->get_base_type(p_base);
  48. ERR_FAIL_COND_V(!((1 << type) & RS::INSTANCE_GEOMETRY_MASK), nullptr);
  49. GeometryInstanceGLES3 *ginstance = geometry_instance_alloc.alloc();
  50. ginstance->data = memnew(GeometryInstanceGLES3::Data);
  51. ginstance->data->base = p_base;
  52. ginstance->data->base_type = type;
  53. ginstance->data->dependency_tracker.userdata = ginstance;
  54. ginstance->data->dependency_tracker.changed_callback = _geometry_instance_dependency_changed;
  55. ginstance->data->dependency_tracker.deleted_callback = _geometry_instance_dependency_deleted;
  56. ginstance->_mark_dirty();
  57. return ginstance;
  58. }
  59. uint32_t RasterizerSceneGLES3::geometry_instance_get_pair_mask() {
  60. return ((1 << RS::INSTANCE_LIGHT) | (1 << RS::INSTANCE_REFLECTION_PROBE));
  61. }
  62. void RasterizerSceneGLES3::GeometryInstanceGLES3::pair_light_instances(const RID *p_light_instances, uint32_t p_light_instance_count) {
  63. GLES3::Config *config = GLES3::Config::get_singleton();
  64. paired_omni_light_count = 0;
  65. paired_spot_light_count = 0;
  66. paired_omni_lights.clear();
  67. paired_spot_lights.clear();
  68. for (uint32_t i = 0; i < p_light_instance_count; i++) {
  69. RS::LightType type = GLES3::LightStorage::get_singleton()->light_instance_get_type(p_light_instances[i]);
  70. switch (type) {
  71. case RS::LIGHT_OMNI: {
  72. if (paired_omni_light_count < (uint32_t)config->max_lights_per_object) {
  73. paired_omni_lights.push_back(p_light_instances[i]);
  74. paired_omni_light_count++;
  75. }
  76. } break;
  77. case RS::LIGHT_SPOT: {
  78. if (paired_spot_light_count < (uint32_t)config->max_lights_per_object) {
  79. paired_spot_lights.push_back(p_light_instances[i]);
  80. paired_spot_light_count++;
  81. }
  82. } break;
  83. default:
  84. break;
  85. }
  86. }
  87. }
  88. void RasterizerSceneGLES3::GeometryInstanceGLES3::pair_reflection_probe_instances(const RID *p_reflection_probe_instances, uint32_t p_reflection_probe_instance_count) {
  89. paired_reflection_probes.clear();
  90. for (uint32_t i = 0; i < p_reflection_probe_instance_count; i++) {
  91. paired_reflection_probes.push_back(p_reflection_probe_instances[i]);
  92. }
  93. }
  94. void RasterizerSceneGLES3::geometry_instance_free(RenderGeometryInstance *p_geometry_instance) {
  95. GeometryInstanceGLES3 *ginstance = static_cast<GeometryInstanceGLES3 *>(p_geometry_instance);
  96. ERR_FAIL_NULL(ginstance);
  97. GeometryInstanceSurface *surf = ginstance->surface_caches;
  98. while (surf) {
  99. GeometryInstanceSurface *next = surf->next;
  100. geometry_instance_surface_alloc.free(surf);
  101. surf = next;
  102. }
  103. memdelete(ginstance->data);
  104. geometry_instance_alloc.free(ginstance);
  105. }
  106. void RasterizerSceneGLES3::GeometryInstanceGLES3::_mark_dirty() {
  107. if (dirty_list_element.in_list()) {
  108. return;
  109. }
  110. //clear surface caches
  111. GeometryInstanceSurface *surf = surface_caches;
  112. while (surf) {
  113. GeometryInstanceSurface *next = surf->next;
  114. RasterizerSceneGLES3::get_singleton()->geometry_instance_surface_alloc.free(surf);
  115. surf = next;
  116. }
  117. surface_caches = nullptr;
  118. RasterizerSceneGLES3::get_singleton()->geometry_instance_dirty_list.add(&dirty_list_element);
  119. }
  120. void RasterizerSceneGLES3::GeometryInstanceGLES3::set_use_lightmap(RID p_lightmap_instance, const Rect2 &p_lightmap_uv_scale, int p_lightmap_slice_index) {
  121. lightmap_instance = p_lightmap_instance;
  122. lightmap_uv_scale = p_lightmap_uv_scale;
  123. lightmap_slice_index = p_lightmap_slice_index;
  124. _mark_dirty();
  125. }
  126. void RasterizerSceneGLES3::GeometryInstanceGLES3::set_lightmap_capture(const Color *p_sh9) {
  127. if (p_sh9) {
  128. if (lightmap_sh == nullptr) {
  129. lightmap_sh = memnew(GeometryInstanceLightmapSH);
  130. }
  131. memcpy(lightmap_sh->sh, p_sh9, sizeof(Color) * 9);
  132. } else {
  133. if (lightmap_sh != nullptr) {
  134. memdelete(lightmap_sh);
  135. lightmap_sh = nullptr;
  136. }
  137. }
  138. _mark_dirty();
  139. }
  140. void RasterizerSceneGLES3::_update_dirty_geometry_instances() {
  141. while (geometry_instance_dirty_list.first()) {
  142. _geometry_instance_update(geometry_instance_dirty_list.first()->self());
  143. }
  144. }
  145. void RasterizerSceneGLES3::_geometry_instance_dependency_changed(Dependency::DependencyChangedNotification p_notification, DependencyTracker *p_tracker) {
  146. switch (p_notification) {
  147. case Dependency::DEPENDENCY_CHANGED_MATERIAL:
  148. case Dependency::DEPENDENCY_CHANGED_MESH:
  149. case Dependency::DEPENDENCY_CHANGED_PARTICLES:
  150. case Dependency::DEPENDENCY_CHANGED_MULTIMESH:
  151. case Dependency::DEPENDENCY_CHANGED_SKELETON_DATA: {
  152. static_cast<RenderGeometryInstance *>(p_tracker->userdata)->_mark_dirty();
  153. static_cast<GeometryInstanceGLES3 *>(p_tracker->userdata)->data->dirty_dependencies = true;
  154. } break;
  155. case Dependency::DEPENDENCY_CHANGED_MULTIMESH_VISIBLE_INSTANCES: {
  156. GeometryInstanceGLES3 *ginstance = static_cast<GeometryInstanceGLES3 *>(p_tracker->userdata);
  157. if (ginstance->data->base_type == RS::INSTANCE_MULTIMESH) {
  158. ginstance->instance_count = GLES3::MeshStorage::get_singleton()->multimesh_get_instances_to_draw(ginstance->data->base);
  159. }
  160. } break;
  161. default: {
  162. //rest of notifications of no interest
  163. } break;
  164. }
  165. }
  166. void RasterizerSceneGLES3::_geometry_instance_dependency_deleted(const RID &p_dependency, DependencyTracker *p_tracker) {
  167. static_cast<RenderGeometryInstance *>(p_tracker->userdata)->_mark_dirty();
  168. static_cast<GeometryInstanceGLES3 *>(p_tracker->userdata)->data->dirty_dependencies = true;
  169. }
  170. void RasterizerSceneGLES3::_geometry_instance_add_surface_with_material(GeometryInstanceGLES3 *ginstance, uint32_t p_surface, GLES3::SceneMaterialData *p_material, uint32_t p_material_id, uint32_t p_shader_id, RID p_mesh) {
  171. GLES3::MeshStorage *mesh_storage = GLES3::MeshStorage::get_singleton();
  172. bool has_read_screen_alpha = p_material->shader_data->uses_screen_texture || p_material->shader_data->uses_depth_texture || p_material->shader_data->uses_normal_texture;
  173. bool has_base_alpha = ((p_material->shader_data->uses_alpha && !p_material->shader_data->uses_alpha_clip) || has_read_screen_alpha);
  174. bool has_blend_alpha = p_material->shader_data->uses_blend_alpha;
  175. bool has_alpha = has_base_alpha || has_blend_alpha;
  176. uint32_t flags = 0;
  177. if (p_material->shader_data->uses_screen_texture) {
  178. flags |= GeometryInstanceSurface::FLAG_USES_SCREEN_TEXTURE;
  179. }
  180. if (p_material->shader_data->uses_depth_texture) {
  181. flags |= GeometryInstanceSurface::FLAG_USES_DEPTH_TEXTURE;
  182. }
  183. if (p_material->shader_data->uses_normal_texture) {
  184. flags |= GeometryInstanceSurface::FLAG_USES_NORMAL_TEXTURE;
  185. }
  186. if (ginstance->data->cast_double_sided_shadows) {
  187. flags |= GeometryInstanceSurface::FLAG_USES_DOUBLE_SIDED_SHADOWS;
  188. }
  189. if (has_alpha || has_read_screen_alpha || p_material->shader_data->depth_draw == GLES3::SceneShaderData::DEPTH_DRAW_DISABLED || p_material->shader_data->depth_test == GLES3::SceneShaderData::DEPTH_TEST_DISABLED) {
  190. //material is only meant for alpha pass
  191. flags |= GeometryInstanceSurface::FLAG_PASS_ALPHA;
  192. if (p_material->shader_data->uses_depth_prepass_alpha && !(p_material->shader_data->depth_draw == GLES3::SceneShaderData::DEPTH_DRAW_DISABLED || p_material->shader_data->depth_test == GLES3::SceneShaderData::DEPTH_TEST_DISABLED)) {
  193. flags |= GeometryInstanceSurface::FLAG_PASS_DEPTH;
  194. flags |= GeometryInstanceSurface::FLAG_PASS_SHADOW;
  195. }
  196. } else {
  197. flags |= GeometryInstanceSurface::FLAG_PASS_OPAQUE;
  198. flags |= GeometryInstanceSurface::FLAG_PASS_DEPTH;
  199. flags |= GeometryInstanceSurface::FLAG_PASS_SHADOW;
  200. }
  201. GLES3::SceneMaterialData *material_shadow = nullptr;
  202. void *surface_shadow = nullptr;
  203. if (!p_material->shader_data->uses_particle_trails && !p_material->shader_data->writes_modelview_or_projection && !p_material->shader_data->uses_vertex && !p_material->shader_data->uses_discard && !p_material->shader_data->uses_depth_prepass_alpha && !p_material->shader_data->uses_alpha_clip && !p_material->shader_data->uses_world_coordinates && !p_material->shader_data->wireframe) {
  204. flags |= GeometryInstanceSurface::FLAG_USES_SHARED_SHADOW_MATERIAL;
  205. material_shadow = static_cast<GLES3::SceneMaterialData *>(GLES3::MaterialStorage::get_singleton()->material_get_data(scene_globals.default_material, RS::SHADER_SPATIAL));
  206. RID shadow_mesh = mesh_storage->mesh_get_shadow_mesh(p_mesh);
  207. if (shadow_mesh.is_valid()) {
  208. surface_shadow = mesh_storage->mesh_get_surface(shadow_mesh, p_surface);
  209. }
  210. } else {
  211. material_shadow = p_material;
  212. }
  213. GeometryInstanceSurface *sdcache = geometry_instance_surface_alloc.alloc();
  214. sdcache->flags = flags;
  215. sdcache->shader = p_material->shader_data;
  216. sdcache->material = p_material;
  217. sdcache->surface = mesh_storage->mesh_get_surface(p_mesh, p_surface);
  218. sdcache->primitive = mesh_storage->mesh_surface_get_primitive(sdcache->surface);
  219. sdcache->surface_index = p_surface;
  220. if (ginstance->data->dirty_dependencies) {
  221. RSG::utilities->base_update_dependency(p_mesh, &ginstance->data->dependency_tracker);
  222. }
  223. //shadow
  224. sdcache->shader_shadow = material_shadow->shader_data;
  225. sdcache->material_shadow = material_shadow;
  226. sdcache->surface_shadow = surface_shadow ? surface_shadow : sdcache->surface;
  227. sdcache->owner = ginstance;
  228. sdcache->next = ginstance->surface_caches;
  229. ginstance->surface_caches = sdcache;
  230. //sortkey
  231. sdcache->sort.sort_key1 = 0;
  232. sdcache->sort.sort_key2 = 0;
  233. sdcache->sort.surface_index = p_surface;
  234. sdcache->sort.material_id_low = p_material_id & 0x0000FFFF;
  235. sdcache->sort.material_id_hi = p_material_id >> 16;
  236. sdcache->sort.shader_id = p_shader_id;
  237. sdcache->sort.geometry_id = p_mesh.get_local_index();
  238. sdcache->sort.priority = p_material->priority;
  239. GLES3::Mesh::Surface *s = reinterpret_cast<GLES3::Mesh::Surface *>(sdcache->surface);
  240. if (p_material->shader_data->uses_tangent && !(s->format & RS::ARRAY_FORMAT_TANGENT)) {
  241. String shader_path = p_material->shader_data->path.is_empty() ? "" : "(" + p_material->shader_data->path + ")";
  242. String mesh_path = mesh_storage->mesh_get_path(p_mesh).is_empty() ? "" : "(" + mesh_storage->mesh_get_path(p_mesh) + ")";
  243. WARN_PRINT_ED(vformat("Attempting to use a shader %s that requires tangents with a mesh %s that doesn't contain tangents. Ensure that meshes are imported with the 'ensure_tangents' option. If creating your own meshes, add an `ARRAY_TANGENT` array (when using ArrayMesh) or call `generate_tangents()` (when using SurfaceTool).", shader_path, mesh_path));
  244. }
  245. }
  246. void RasterizerSceneGLES3::_geometry_instance_add_surface_with_material_chain(GeometryInstanceGLES3 *ginstance, uint32_t p_surface, GLES3::SceneMaterialData *p_material_data, RID p_mat_src, RID p_mesh) {
  247. GLES3::SceneMaterialData *material_data = p_material_data;
  248. GLES3::MaterialStorage *material_storage = GLES3::MaterialStorage::get_singleton();
  249. _geometry_instance_add_surface_with_material(ginstance, p_surface, material_data, p_mat_src.get_local_index(), material_storage->material_get_shader_id(p_mat_src), p_mesh);
  250. while (material_data->next_pass.is_valid()) {
  251. RID next_pass = material_data->next_pass;
  252. material_data = static_cast<GLES3::SceneMaterialData *>(material_storage->material_get_data(next_pass, RS::SHADER_SPATIAL));
  253. if (!material_data || !material_data->shader_data->valid) {
  254. break;
  255. }
  256. if (ginstance->data->dirty_dependencies) {
  257. material_storage->material_update_dependency(next_pass, &ginstance->data->dependency_tracker);
  258. }
  259. _geometry_instance_add_surface_with_material(ginstance, p_surface, material_data, next_pass.get_local_index(), material_storage->material_get_shader_id(next_pass), p_mesh);
  260. }
  261. }
  262. void RasterizerSceneGLES3::_geometry_instance_add_surface(GeometryInstanceGLES3 *ginstance, uint32_t p_surface, RID p_material, RID p_mesh) {
  263. GLES3::MaterialStorage *material_storage = GLES3::MaterialStorage::get_singleton();
  264. RID m_src;
  265. m_src = ginstance->data->material_override.is_valid() ? ginstance->data->material_override : p_material;
  266. GLES3::SceneMaterialData *material_data = nullptr;
  267. if (m_src.is_valid()) {
  268. material_data = static_cast<GLES3::SceneMaterialData *>(material_storage->material_get_data(m_src, RS::SHADER_SPATIAL));
  269. if (!material_data || !material_data->shader_data->valid) {
  270. material_data = nullptr;
  271. }
  272. }
  273. if (material_data) {
  274. if (ginstance->data->dirty_dependencies) {
  275. material_storage->material_update_dependency(m_src, &ginstance->data->dependency_tracker);
  276. }
  277. } else {
  278. material_data = static_cast<GLES3::SceneMaterialData *>(material_storage->material_get_data(scene_globals.default_material, RS::SHADER_SPATIAL));
  279. m_src = scene_globals.default_material;
  280. }
  281. ERR_FAIL_NULL(material_data);
  282. _geometry_instance_add_surface_with_material_chain(ginstance, p_surface, material_data, m_src, p_mesh);
  283. if (ginstance->data->material_overlay.is_valid()) {
  284. m_src = ginstance->data->material_overlay;
  285. material_data = static_cast<GLES3::SceneMaterialData *>(material_storage->material_get_data(m_src, RS::SHADER_SPATIAL));
  286. if (material_data && material_data->shader_data->valid) {
  287. if (ginstance->data->dirty_dependencies) {
  288. material_storage->material_update_dependency(m_src, &ginstance->data->dependency_tracker);
  289. }
  290. _geometry_instance_add_surface_with_material_chain(ginstance, p_surface, material_data, m_src, p_mesh);
  291. }
  292. }
  293. }
  294. void RasterizerSceneGLES3::_geometry_instance_update(RenderGeometryInstance *p_geometry_instance) {
  295. GLES3::MeshStorage *mesh_storage = GLES3::MeshStorage::get_singleton();
  296. GLES3::ParticlesStorage *particles_storage = GLES3::ParticlesStorage::get_singleton();
  297. GeometryInstanceGLES3 *ginstance = static_cast<GeometryInstanceGLES3 *>(p_geometry_instance);
  298. if (ginstance->data->dirty_dependencies) {
  299. ginstance->data->dependency_tracker.update_begin();
  300. }
  301. //add geometry for drawing
  302. switch (ginstance->data->base_type) {
  303. case RS::INSTANCE_MESH: {
  304. const RID *materials = nullptr;
  305. uint32_t surface_count;
  306. RID mesh = ginstance->data->base;
  307. materials = mesh_storage->mesh_get_surface_count_and_materials(mesh, surface_count);
  308. if (materials) {
  309. //if no materials, no surfaces.
  310. const RID *inst_materials = ginstance->data->surface_materials.ptr();
  311. uint32_t surf_mat_count = ginstance->data->surface_materials.size();
  312. for (uint32_t j = 0; j < surface_count; j++) {
  313. RID material = (j < surf_mat_count && inst_materials[j].is_valid()) ? inst_materials[j] : materials[j];
  314. _geometry_instance_add_surface(ginstance, j, material, mesh);
  315. }
  316. }
  317. ginstance->instance_count = -1;
  318. } break;
  319. case RS::INSTANCE_MULTIMESH: {
  320. RID mesh = mesh_storage->multimesh_get_mesh(ginstance->data->base);
  321. if (mesh.is_valid()) {
  322. const RID *materials = nullptr;
  323. uint32_t surface_count;
  324. materials = mesh_storage->mesh_get_surface_count_and_materials(mesh, surface_count);
  325. if (materials) {
  326. for (uint32_t j = 0; j < surface_count; j++) {
  327. _geometry_instance_add_surface(ginstance, j, materials[j], mesh);
  328. }
  329. }
  330. ginstance->instance_count = mesh_storage->multimesh_get_instances_to_draw(ginstance->data->base);
  331. }
  332. } break;
  333. case RS::INSTANCE_PARTICLES: {
  334. int draw_passes = particles_storage->particles_get_draw_passes(ginstance->data->base);
  335. for (int j = 0; j < draw_passes; j++) {
  336. RID mesh = particles_storage->particles_get_draw_pass_mesh(ginstance->data->base, j);
  337. if (!mesh.is_valid()) {
  338. continue;
  339. }
  340. const RID *materials = nullptr;
  341. uint32_t surface_count;
  342. materials = mesh_storage->mesh_get_surface_count_and_materials(mesh, surface_count);
  343. if (materials) {
  344. for (uint32_t k = 0; k < surface_count; k++) {
  345. _geometry_instance_add_surface(ginstance, k, materials[k], mesh);
  346. }
  347. }
  348. }
  349. ginstance->instance_count = particles_storage->particles_get_amount(ginstance->data->base);
  350. } break;
  351. default: {
  352. }
  353. }
  354. bool store_transform = true;
  355. ginstance->base_flags = 0;
  356. if (ginstance->data->base_type == RS::INSTANCE_MULTIMESH) {
  357. ginstance->base_flags |= INSTANCE_DATA_FLAG_MULTIMESH;
  358. if (mesh_storage->multimesh_get_transform_format(ginstance->data->base) == RS::MULTIMESH_TRANSFORM_2D) {
  359. ginstance->base_flags |= INSTANCE_DATA_FLAG_MULTIMESH_FORMAT_2D;
  360. }
  361. if (mesh_storage->multimesh_uses_colors(ginstance->data->base)) {
  362. ginstance->base_flags |= INSTANCE_DATA_FLAG_MULTIMESH_HAS_COLOR;
  363. }
  364. if (mesh_storage->multimesh_uses_custom_data(ginstance->data->base)) {
  365. ginstance->base_flags |= INSTANCE_DATA_FLAG_MULTIMESH_HAS_CUSTOM_DATA;
  366. }
  367. } else if (ginstance->data->base_type == RS::INSTANCE_PARTICLES) {
  368. ginstance->base_flags |= INSTANCE_DATA_FLAG_PARTICLES;
  369. ginstance->base_flags |= INSTANCE_DATA_FLAG_MULTIMESH;
  370. ginstance->base_flags |= INSTANCE_DATA_FLAG_MULTIMESH_HAS_COLOR;
  371. ginstance->base_flags |= INSTANCE_DATA_FLAG_MULTIMESH_HAS_CUSTOM_DATA;
  372. if (!particles_storage->particles_is_using_local_coords(ginstance->data->base)) {
  373. store_transform = false;
  374. }
  375. } else if (ginstance->data->base_type == RS::INSTANCE_MESH) {
  376. if (mesh_storage->skeleton_is_valid(ginstance->data->skeleton)) {
  377. if (ginstance->data->dirty_dependencies) {
  378. mesh_storage->skeleton_update_dependency(ginstance->data->skeleton, &ginstance->data->dependency_tracker);
  379. }
  380. }
  381. }
  382. ginstance->store_transform_cache = store_transform;
  383. if (ginstance->data->dirty_dependencies) {
  384. ginstance->data->dependency_tracker.update_end();
  385. ginstance->data->dirty_dependencies = false;
  386. }
  387. ginstance->dirty_list_element.remove_from_list();
  388. }
  389. /* SKY API */
  390. void RasterizerSceneGLES3::_free_sky_data(Sky *p_sky) {
  391. if (p_sky->radiance != 0) {
  392. GLES3::Utilities::get_singleton()->texture_free_data(p_sky->radiance);
  393. p_sky->radiance = 0;
  394. GLES3::Utilities::get_singleton()->texture_free_data(p_sky->raw_radiance);
  395. p_sky->raw_radiance = 0;
  396. glDeleteFramebuffers(1, &p_sky->radiance_framebuffer);
  397. p_sky->radiance_framebuffer = 0;
  398. }
  399. }
  400. RID RasterizerSceneGLES3::sky_allocate() {
  401. return sky_owner.allocate_rid();
  402. }
  403. void RasterizerSceneGLES3::sky_initialize(RID p_rid) {
  404. sky_owner.initialize_rid(p_rid);
  405. }
  406. void RasterizerSceneGLES3::sky_set_radiance_size(RID p_sky, int p_radiance_size) {
  407. Sky *sky = sky_owner.get_or_null(p_sky);
  408. ERR_FAIL_NULL(sky);
  409. ERR_FAIL_COND_MSG(p_radiance_size < 32 || p_radiance_size > 2048, "Sky radiance size must be between 32 and 2048");
  410. if (sky->radiance_size == p_radiance_size) {
  411. return; // No need to update
  412. }
  413. sky->radiance_size = p_radiance_size;
  414. _free_sky_data(sky);
  415. _invalidate_sky(sky);
  416. }
  417. void RasterizerSceneGLES3::sky_set_mode(RID p_sky, RS::SkyMode p_mode) {
  418. Sky *sky = sky_owner.get_or_null(p_sky);
  419. ERR_FAIL_NULL(sky);
  420. if (sky->mode == p_mode) {
  421. return;
  422. }
  423. sky->mode = p_mode;
  424. _invalidate_sky(sky);
  425. }
  426. void RasterizerSceneGLES3::sky_set_material(RID p_sky, RID p_material) {
  427. Sky *sky = sky_owner.get_or_null(p_sky);
  428. ERR_FAIL_NULL(sky);
  429. if (sky->material == p_material) {
  430. return;
  431. }
  432. sky->material = p_material;
  433. _invalidate_sky(sky);
  434. }
  435. float RasterizerSceneGLES3::sky_get_baked_exposure(RID p_sky) const {
  436. Sky *sky = sky_owner.get_or_null(p_sky);
  437. ERR_FAIL_NULL_V(sky, 1.0);
  438. return sky->baked_exposure;
  439. }
  440. void RasterizerSceneGLES3::_invalidate_sky(Sky *p_sky) {
  441. if (!p_sky->dirty) {
  442. p_sky->dirty = true;
  443. p_sky->dirty_list = dirty_sky_list;
  444. dirty_sky_list = p_sky;
  445. }
  446. }
  447. GLuint _init_radiance_texture(int p_size, int p_mipmaps, String p_name) {
  448. GLuint radiance_id = 0;
  449. glGenTextures(1, &radiance_id);
  450. glBindTexture(GL_TEXTURE_CUBE_MAP, radiance_id);
  451. #ifdef GL_API_ENABLED
  452. if (RasterizerGLES3::is_gles_over_gl()) {
  453. //TODO, on low-end compare this to allocating each face of each mip individually
  454. // see: https://www.khronos.org/registry/OpenGL-Refpages/es3.0/html/glTexStorage2D.xhtml
  455. for (int i = 0; i < 6; i++) {
  456. glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB10_A2, p_size, p_size, 0, GL_RGBA, GL_UNSIGNED_INT_2_10_10_10_REV, nullptr);
  457. }
  458. glGenerateMipmap(GL_TEXTURE_CUBE_MAP);
  459. }
  460. #endif // GL_API_ENABLED
  461. #ifdef GLES_API_ENABLED
  462. if (!RasterizerGLES3::is_gles_over_gl()) {
  463. glTexStorage2D(GL_TEXTURE_CUBE_MAP, p_mipmaps, GL_RGB10_A2, p_size, p_size);
  464. }
  465. #endif // GLES_API_ENABLED
  466. glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
  467. glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  468. glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  469. glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  470. glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_BASE_LEVEL, 0);
  471. glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAX_LEVEL, p_mipmaps - 1);
  472. GLES3::Utilities::get_singleton()->texture_allocated_data(radiance_id, Image::get_image_data_size(p_size, p_size, Image::FORMAT_RGBA8, true), p_name);
  473. return radiance_id;
  474. }
  475. void RasterizerSceneGLES3::_update_dirty_skys() {
  476. Sky *sky = dirty_sky_list;
  477. while (sky) {
  478. if (sky->radiance == 0) {
  479. sky->mipmap_count = Image::get_image_required_mipmaps(sky->radiance_size, sky->radiance_size, Image::FORMAT_RGBA8) - 1;
  480. // Left uninitialized, will attach a texture at render time
  481. glGenFramebuffers(1, &sky->radiance_framebuffer);
  482. sky->radiance = _init_radiance_texture(sky->radiance_size, sky->mipmap_count, "Sky radiance texture");
  483. sky->raw_radiance = _init_radiance_texture(sky->radiance_size, sky->mipmap_count, "Sky raw radiance texture");
  484. }
  485. sky->reflection_dirty = true;
  486. sky->processing_layer = 0;
  487. Sky *next = sky->dirty_list;
  488. sky->dirty_list = nullptr;
  489. sky->dirty = false;
  490. sky = next;
  491. }
  492. dirty_sky_list = nullptr;
  493. }
  494. void RasterizerSceneGLES3::_setup_sky(const RenderDataGLES3 *p_render_data, const PagedArray<RID> &p_lights, const Projection &p_projection, const Transform3D &p_transform, const Size2i p_screen_size) {
  495. GLES3::LightStorage *light_storage = GLES3::LightStorage::get_singleton();
  496. GLES3::MaterialStorage *material_storage = GLES3::MaterialStorage::get_singleton();
  497. ERR_FAIL_COND(p_render_data->environment.is_null());
  498. GLES3::SkyMaterialData *material = nullptr;
  499. Sky *sky = sky_owner.get_or_null(environment_get_sky(p_render_data->environment));
  500. RID sky_material;
  501. GLES3::SkyShaderData *shader_data = nullptr;
  502. if (sky) {
  503. sky_material = sky->material;
  504. if (sky_material.is_valid()) {
  505. material = static_cast<GLES3::SkyMaterialData *>(material_storage->material_get_data(sky_material, RS::SHADER_SKY));
  506. if (!material || !material->shader_data->valid) {
  507. material = nullptr;
  508. }
  509. }
  510. }
  511. if (!material) {
  512. sky_material = sky_globals.default_material;
  513. material = static_cast<GLES3::SkyMaterialData *>(material_storage->material_get_data(sky_material, RS::SHADER_SKY));
  514. }
  515. ERR_FAIL_NULL(material);
  516. shader_data = material->shader_data;
  517. ERR_FAIL_NULL(shader_data);
  518. if (sky) {
  519. if (shader_data->uses_time && time - sky->prev_time > 0.00001) {
  520. sky->prev_time = time;
  521. sky->reflection_dirty = true;
  522. RenderingServerDefault::redraw_request();
  523. }
  524. if (material != sky->prev_material) {
  525. sky->prev_material = material;
  526. sky->reflection_dirty = true;
  527. }
  528. if (material->uniform_set_updated) {
  529. material->uniform_set_updated = false;
  530. sky->reflection_dirty = true;
  531. }
  532. if (!p_transform.origin.is_equal_approx(sky->prev_position) && shader_data->uses_position) {
  533. sky->prev_position = p_transform.origin;
  534. sky->reflection_dirty = true;
  535. }
  536. }
  537. glBindBufferBase(GL_UNIFORM_BUFFER, SKY_DIRECTIONAL_LIGHT_UNIFORM_LOCATION, sky_globals.directional_light_buffer);
  538. if (shader_data->uses_light) {
  539. sky_globals.directional_light_count = 0;
  540. for (int i = 0; i < (int)p_lights.size(); i++) {
  541. GLES3::LightInstance *li = GLES3::LightStorage::get_singleton()->get_light_instance(p_lights[i]);
  542. if (!li) {
  543. continue;
  544. }
  545. RID base = li->light;
  546. ERR_CONTINUE(base.is_null());
  547. RS::LightType type = light_storage->light_get_type(base);
  548. if (type == RS::LIGHT_DIRECTIONAL && light_storage->light_directional_get_sky_mode(base) != RS::LIGHT_DIRECTIONAL_SKY_MODE_LIGHT_ONLY) {
  549. DirectionalLightData &sky_light_data = sky_globals.directional_lights[sky_globals.directional_light_count];
  550. Transform3D light_transform = li->transform;
  551. Vector3 world_direction = light_transform.basis.xform(Vector3(0, 0, 1)).normalized();
  552. sky_light_data.direction[0] = world_direction.x;
  553. sky_light_data.direction[1] = world_direction.y;
  554. sky_light_data.direction[2] = world_direction.z;
  555. float sign = light_storage->light_is_negative(base) ? -1 : 1;
  556. sky_light_data.energy = sign * light_storage->light_get_param(base, RS::LIGHT_PARAM_ENERGY);
  557. if (is_using_physical_light_units()) {
  558. sky_light_data.energy *= light_storage->light_get_param(base, RS::LIGHT_PARAM_INTENSITY);
  559. }
  560. if (p_render_data->camera_attributes.is_valid()) {
  561. sky_light_data.energy *= RSG::camera_attributes->camera_attributes_get_exposure_normalization_factor(p_render_data->camera_attributes);
  562. }
  563. Color linear_col = light_storage->light_get_color(base);
  564. sky_light_data.color[0] = linear_col.r;
  565. sky_light_data.color[1] = linear_col.g;
  566. sky_light_data.color[2] = linear_col.b;
  567. sky_light_data.enabled = true;
  568. float angular_diameter = light_storage->light_get_param(base, RS::LIGHT_PARAM_SIZE);
  569. if (angular_diameter > 0.0) {
  570. angular_diameter = Math::tan(Math::deg_to_rad(angular_diameter));
  571. } else {
  572. angular_diameter = 0.0;
  573. }
  574. sky_light_data.size = angular_diameter;
  575. sky_globals.directional_light_count++;
  576. if (sky_globals.directional_light_count >= sky_globals.max_directional_lights) {
  577. break;
  578. }
  579. }
  580. }
  581. // Check whether the directional_light_buffer changes
  582. bool light_data_dirty = false;
  583. // Light buffer is dirty if we have fewer or more lights
  584. // If we have fewer lights, make sure that old lights are disabled
  585. if (sky_globals.directional_light_count != sky_globals.last_frame_directional_light_count) {
  586. light_data_dirty = true;
  587. for (uint32_t i = sky_globals.directional_light_count; i < sky_globals.max_directional_lights; i++) {
  588. sky_globals.directional_lights[i].enabled = false;
  589. sky_globals.last_frame_directional_lights[i].enabled = false;
  590. }
  591. }
  592. if (!light_data_dirty) {
  593. for (uint32_t i = 0; i < sky_globals.directional_light_count; i++) {
  594. if (sky_globals.directional_lights[i].direction[0] != sky_globals.last_frame_directional_lights[i].direction[0] ||
  595. sky_globals.directional_lights[i].direction[1] != sky_globals.last_frame_directional_lights[i].direction[1] ||
  596. sky_globals.directional_lights[i].direction[2] != sky_globals.last_frame_directional_lights[i].direction[2] ||
  597. sky_globals.directional_lights[i].energy != sky_globals.last_frame_directional_lights[i].energy ||
  598. sky_globals.directional_lights[i].color[0] != sky_globals.last_frame_directional_lights[i].color[0] ||
  599. sky_globals.directional_lights[i].color[1] != sky_globals.last_frame_directional_lights[i].color[1] ||
  600. sky_globals.directional_lights[i].color[2] != sky_globals.last_frame_directional_lights[i].color[2] ||
  601. sky_globals.directional_lights[i].enabled != sky_globals.last_frame_directional_lights[i].enabled ||
  602. sky_globals.directional_lights[i].size != sky_globals.last_frame_directional_lights[i].size) {
  603. light_data_dirty = true;
  604. break;
  605. }
  606. }
  607. }
  608. if (light_data_dirty) {
  609. glBufferData(GL_UNIFORM_BUFFER, sizeof(DirectionalLightData) * sky_globals.max_directional_lights, sky_globals.directional_lights, GL_STREAM_DRAW);
  610. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  611. DirectionalLightData *temp = sky_globals.last_frame_directional_lights;
  612. sky_globals.last_frame_directional_lights = sky_globals.directional_lights;
  613. sky_globals.directional_lights = temp;
  614. sky_globals.last_frame_directional_light_count = sky_globals.directional_light_count;
  615. if (sky) {
  616. sky->reflection_dirty = true;
  617. }
  618. }
  619. }
  620. if (p_render_data->view_count > 1) {
  621. glBindBufferBase(GL_UNIFORM_BUFFER, SKY_MULTIVIEW_UNIFORM_LOCATION, scene_state.multiview_buffer);
  622. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  623. }
  624. if (sky && !sky->radiance) {
  625. _invalidate_sky(sky);
  626. _update_dirty_skys();
  627. }
  628. }
  629. void RasterizerSceneGLES3::_draw_sky(RID p_env, const Projection &p_projection, const Transform3D &p_transform, float p_sky_energy_multiplier, float p_luminance_multiplier, bool p_use_multiview, bool p_flip_y, bool p_apply_color_adjustments_in_post) {
  630. GLES3::MaterialStorage *material_storage = GLES3::MaterialStorage::get_singleton();
  631. ERR_FAIL_COND(p_env.is_null());
  632. Sky *sky = sky_owner.get_or_null(environment_get_sky(p_env));
  633. GLES3::SkyMaterialData *material_data = nullptr;
  634. RID sky_material;
  635. uint64_t spec_constants = p_use_multiview ? SkyShaderGLES3::USE_MULTIVIEW : 0;
  636. if (p_flip_y) {
  637. spec_constants |= SkyShaderGLES3::USE_INVERTED_Y;
  638. }
  639. if (!p_apply_color_adjustments_in_post) {
  640. spec_constants |= SkyShaderGLES3::APPLY_TONEMAPPING;
  641. }
  642. RS::EnvironmentBG background = environment_get_background(p_env);
  643. if (sky) {
  644. sky_material = sky->material;
  645. if (sky_material.is_valid()) {
  646. material_data = static_cast<GLES3::SkyMaterialData *>(material_storage->material_get_data(sky_material, RS::SHADER_SKY));
  647. if (!material_data || !material_data->shader_data->valid) {
  648. material_data = nullptr;
  649. }
  650. }
  651. if (!material_data) {
  652. sky_material = sky_globals.default_material;
  653. material_data = static_cast<GLES3::SkyMaterialData *>(material_storage->material_get_data(sky_material, RS::SHADER_SKY));
  654. }
  655. } else if (background == RS::ENV_BG_CLEAR_COLOR || background == RS::ENV_BG_COLOR) {
  656. sky_material = sky_globals.fog_material;
  657. material_data = static_cast<GLES3::SkyMaterialData *>(material_storage->material_get_data(sky_material, RS::SHADER_SKY));
  658. }
  659. ERR_FAIL_NULL(material_data);
  660. material_data->bind_uniforms();
  661. GLES3::SkyShaderData *shader_data = material_data->shader_data;
  662. ERR_FAIL_NULL(shader_data);
  663. // Camera
  664. Projection camera;
  665. if (environment_get_sky_custom_fov(p_env)) {
  666. float near_plane = p_projection.get_z_near();
  667. float far_plane = p_projection.get_z_far();
  668. float aspect = p_projection.get_aspect();
  669. camera.set_perspective(environment_get_sky_custom_fov(p_env), aspect, near_plane, far_plane);
  670. } else {
  671. camera = p_projection;
  672. }
  673. Projection correction;
  674. correction.set_depth_correction(false, true, false);
  675. camera = correction * camera;
  676. Basis sky_transform = environment_get_sky_orientation(p_env);
  677. sky_transform.invert();
  678. sky_transform = sky_transform * p_transform.basis;
  679. bool success = material_storage->shaders.sky_shader.version_bind_shader(shader_data->version, SkyShaderGLES3::MODE_BACKGROUND, spec_constants);
  680. if (!success) {
  681. return;
  682. }
  683. material_storage->shaders.sky_shader.version_set_uniform(SkyShaderGLES3::ORIENTATION, sky_transform, shader_data->version, SkyShaderGLES3::MODE_BACKGROUND, spec_constants);
  684. material_storage->shaders.sky_shader.version_set_uniform(SkyShaderGLES3::PROJECTION, camera.columns[2][0], camera.columns[0][0], camera.columns[2][1], camera.columns[1][1], shader_data->version, SkyShaderGLES3::MODE_BACKGROUND, spec_constants);
  685. material_storage->shaders.sky_shader.version_set_uniform(SkyShaderGLES3::POSITION, p_transform.origin, shader_data->version, SkyShaderGLES3::MODE_BACKGROUND, spec_constants);
  686. material_storage->shaders.sky_shader.version_set_uniform(SkyShaderGLES3::TIME, time, shader_data->version, SkyShaderGLES3::MODE_BACKGROUND, spec_constants);
  687. material_storage->shaders.sky_shader.version_set_uniform(SkyShaderGLES3::SKY_ENERGY_MULTIPLIER, p_sky_energy_multiplier, shader_data->version, SkyShaderGLES3::MODE_BACKGROUND, spec_constants);
  688. material_storage->shaders.sky_shader.version_set_uniform(SkyShaderGLES3::LUMINANCE_MULTIPLIER, p_luminance_multiplier, shader_data->version, SkyShaderGLES3::MODE_BACKGROUND, spec_constants);
  689. Color fog_color = environment_get_fog_light_color(p_env).srgb_to_linear() * environment_get_fog_light_energy(p_env);
  690. material_storage->shaders.sky_shader.version_set_uniform(SkyShaderGLES3::FOG_ENABLED, environment_get_fog_enabled(p_env), shader_data->version, SkyShaderGLES3::MODE_BACKGROUND, spec_constants);
  691. material_storage->shaders.sky_shader.version_set_uniform(SkyShaderGLES3::FOG_AERIAL_PERSPECTIVE, environment_get_fog_aerial_perspective(p_env), shader_data->version, SkyShaderGLES3::MODE_BACKGROUND, spec_constants);
  692. material_storage->shaders.sky_shader.version_set_uniform(SkyShaderGLES3::FOG_LIGHT_COLOR, fog_color, shader_data->version, SkyShaderGLES3::MODE_BACKGROUND, spec_constants);
  693. material_storage->shaders.sky_shader.version_set_uniform(SkyShaderGLES3::FOG_SUN_SCATTER, environment_get_fog_sun_scatter(p_env), shader_data->version, SkyShaderGLES3::MODE_BACKGROUND, spec_constants);
  694. material_storage->shaders.sky_shader.version_set_uniform(SkyShaderGLES3::FOG_DENSITY, environment_get_fog_density(p_env), shader_data->version, SkyShaderGLES3::MODE_BACKGROUND, spec_constants);
  695. material_storage->shaders.sky_shader.version_set_uniform(SkyShaderGLES3::FOG_SKY_AFFECT, environment_get_fog_sky_affect(p_env), shader_data->version, SkyShaderGLES3::MODE_BACKGROUND, spec_constants);
  696. material_storage->shaders.sky_shader.version_set_uniform(SkyShaderGLES3::DIRECTIONAL_LIGHT_COUNT, sky_globals.directional_light_count, shader_data->version, SkyShaderGLES3::MODE_BACKGROUND, spec_constants);
  697. if (p_use_multiview) {
  698. glBindBufferBase(GL_UNIFORM_BUFFER, SKY_MULTIVIEW_UNIFORM_LOCATION, scene_state.multiview_buffer);
  699. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  700. }
  701. glBindVertexArray(sky_globals.screen_triangle_array);
  702. glDrawArrays(GL_TRIANGLES, 0, 3);
  703. }
  704. void RasterizerSceneGLES3::_update_sky_radiance(RID p_env, const Projection &p_projection, const Transform3D &p_transform, float p_sky_energy_multiplier) {
  705. GLES3::CubemapFilter *cubemap_filter = GLES3::CubemapFilter::get_singleton();
  706. GLES3::MaterialStorage *material_storage = GLES3::MaterialStorage::get_singleton();
  707. ERR_FAIL_COND(p_env.is_null());
  708. Sky *sky = sky_owner.get_or_null(environment_get_sky(p_env));
  709. ERR_FAIL_NULL(sky);
  710. GLES3::SkyMaterialData *material_data = nullptr;
  711. RID sky_material;
  712. RS::EnvironmentBG background = environment_get_background(p_env);
  713. if (sky) {
  714. ERR_FAIL_NULL(sky);
  715. sky_material = sky->material;
  716. if (sky_material.is_valid()) {
  717. material_data = static_cast<GLES3::SkyMaterialData *>(material_storage->material_get_data(sky_material, RS::SHADER_SKY));
  718. if (!material_data || !material_data->shader_data->valid) {
  719. material_data = nullptr;
  720. }
  721. }
  722. if (!material_data) {
  723. sky_material = sky_globals.default_material;
  724. material_data = static_cast<GLES3::SkyMaterialData *>(material_storage->material_get_data(sky_material, RS::SHADER_SKY));
  725. }
  726. } else if (background == RS::ENV_BG_CLEAR_COLOR || background == RS::ENV_BG_COLOR) {
  727. sky_material = sky_globals.fog_material;
  728. material_data = static_cast<GLES3::SkyMaterialData *>(material_storage->material_get_data(sky_material, RS::SHADER_SKY));
  729. }
  730. ERR_FAIL_NULL(material_data);
  731. material_data->bind_uniforms();
  732. GLES3::SkyShaderData *shader_data = material_data->shader_data;
  733. ERR_FAIL_NULL(shader_data);
  734. bool update_single_frame = sky->mode == RS::SKY_MODE_REALTIME || sky->mode == RS::SKY_MODE_QUALITY;
  735. RS::SkyMode sky_mode = sky->mode;
  736. if (sky_mode == RS::SKY_MODE_AUTOMATIC) {
  737. if ((shader_data->uses_time || shader_data->uses_position) && sky->radiance_size == 256) {
  738. update_single_frame = true;
  739. sky_mode = RS::SKY_MODE_REALTIME;
  740. } else if (shader_data->uses_light || shader_data->ubo_size > 0) {
  741. update_single_frame = false;
  742. sky_mode = RS::SKY_MODE_INCREMENTAL;
  743. } else {
  744. update_single_frame = true;
  745. sky_mode = RS::SKY_MODE_QUALITY;
  746. }
  747. }
  748. if (sky->processing_layer == 0 && sky_mode == RS::SKY_MODE_INCREMENTAL) {
  749. // On the first frame after creating sky, rebuild in single frame
  750. update_single_frame = true;
  751. sky_mode = RS::SKY_MODE_QUALITY;
  752. }
  753. int max_processing_layer = sky->mipmap_count;
  754. // Update radiance cubemap
  755. if (sky->reflection_dirty && (sky->processing_layer >= max_processing_layer || update_single_frame)) {
  756. static const Vector3 view_normals[6] = {
  757. Vector3(+1, 0, 0),
  758. Vector3(-1, 0, 0),
  759. Vector3(0, +1, 0),
  760. Vector3(0, -1, 0),
  761. Vector3(0, 0, +1),
  762. Vector3(0, 0, -1)
  763. };
  764. static const Vector3 view_up[6] = {
  765. Vector3(0, -1, 0),
  766. Vector3(0, -1, 0),
  767. Vector3(0, 0, +1),
  768. Vector3(0, 0, -1),
  769. Vector3(0, -1, 0),
  770. Vector3(0, -1, 0)
  771. };
  772. Projection cm;
  773. cm.set_perspective(90, 1, 0.01, 10.0);
  774. Projection correction;
  775. correction.set_depth_correction(true, true, false);
  776. cm = correction * cm;
  777. bool success = material_storage->shaders.sky_shader.version_bind_shader(shader_data->version, SkyShaderGLES3::MODE_CUBEMAP);
  778. if (!success) {
  779. return;
  780. }
  781. material_storage->shaders.sky_shader.version_set_uniform(SkyShaderGLES3::POSITION, p_transform.origin, shader_data->version, SkyShaderGLES3::MODE_CUBEMAP);
  782. material_storage->shaders.sky_shader.version_set_uniform(SkyShaderGLES3::TIME, time, shader_data->version, SkyShaderGLES3::MODE_CUBEMAP);
  783. material_storage->shaders.sky_shader.version_set_uniform(SkyShaderGLES3::PROJECTION, cm.columns[2][0], cm.columns[0][0], cm.columns[2][1], cm.columns[1][1], shader_data->version, SkyShaderGLES3::MODE_CUBEMAP);
  784. material_storage->shaders.sky_shader.version_set_uniform(SkyShaderGLES3::SKY_ENERGY_MULTIPLIER, p_sky_energy_multiplier, shader_data->version, SkyShaderGLES3::MODE_CUBEMAP);
  785. material_storage->shaders.sky_shader.version_set_uniform(SkyShaderGLES3::LUMINANCE_MULTIPLIER, 1.0, shader_data->version, SkyShaderGLES3::MODE_CUBEMAP);
  786. glBindVertexArray(sky_globals.screen_triangle_array);
  787. glViewport(0, 0, sky->radiance_size, sky->radiance_size);
  788. glBindFramebuffer(GL_FRAMEBUFFER, sky->radiance_framebuffer);
  789. scene_state.reset_gl_state();
  790. scene_state.set_gl_cull_mode(RS::CULL_MODE_DISABLED);
  791. scene_state.enable_gl_blend(false);
  792. for (int i = 0; i < 6; i++) {
  793. Basis local_view = Basis::looking_at(view_normals[i], view_up[i]);
  794. material_storage->shaders.sky_shader.version_set_uniform(SkyShaderGLES3::ORIENTATION, local_view, shader_data->version, SkyShaderGLES3::MODE_CUBEMAP);
  795. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, sky->raw_radiance, 0);
  796. glDrawArrays(GL_TRIANGLES, 0, 3);
  797. }
  798. if (update_single_frame) {
  799. for (int i = 0; i < max_processing_layer; i++) {
  800. cubemap_filter->filter_radiance(sky->raw_radiance, sky->radiance, sky->radiance_framebuffer, sky->radiance_size, sky->mipmap_count, i);
  801. }
  802. } else {
  803. cubemap_filter->filter_radiance(sky->raw_radiance, sky->radiance, sky->radiance_framebuffer, sky->radiance_size, sky->mipmap_count, 0); // Just copy over the first mipmap.
  804. }
  805. sky->processing_layer = 1;
  806. sky->baked_exposure = p_sky_energy_multiplier;
  807. sky->reflection_dirty = false;
  808. } else {
  809. if (sky_mode == RS::SKY_MODE_INCREMENTAL && sky->processing_layer < max_processing_layer) {
  810. scene_state.reset_gl_state();
  811. scene_state.set_gl_cull_mode(RS::CULL_MODE_DISABLED);
  812. scene_state.enable_gl_blend(false);
  813. cubemap_filter->filter_radiance(sky->raw_radiance, sky->radiance, sky->radiance_framebuffer, sky->radiance_size, sky->mipmap_count, sky->processing_layer);
  814. sky->processing_layer++;
  815. }
  816. }
  817. glViewport(0, 0, sky->screen_size.x, sky->screen_size.y);
  818. }
  819. Ref<Image> RasterizerSceneGLES3::sky_bake_panorama(RID p_sky, float p_energy, bool p_bake_irradiance, const Size2i &p_size) {
  820. Sky *sky = sky_owner.get_or_null(p_sky);
  821. ERR_FAIL_NULL_V(sky, Ref<Image>());
  822. _update_dirty_skys();
  823. if (sky->radiance == 0) {
  824. return Ref<Image>();
  825. }
  826. GLES3::CopyEffects *copy_effects = GLES3::CopyEffects::get_singleton();
  827. GLES3::Config *config = GLES3::Config::get_singleton();
  828. GLuint rad_tex = 0;
  829. glGenTextures(1, &rad_tex);
  830. glBindTexture(GL_TEXTURE_2D, rad_tex);
  831. if (config->float_texture_supported) {
  832. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, p_size.width, p_size.height, 0, GL_RGBA, GL_FLOAT, nullptr);
  833. GLES3::Utilities::get_singleton()->texture_allocated_data(rad_tex, p_size.width * p_size.height * 16, "Temp sky panorama");
  834. } else {
  835. // Fallback to RGBA8 on devices that don't support rendering to floating point textures. This will look bad, but we have no choice.
  836. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, p_size.width, p_size.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
  837. GLES3::Utilities::get_singleton()->texture_allocated_data(rad_tex, p_size.width * p_size.height * 4, "Temp sky panorama");
  838. }
  839. GLuint rad_fbo = 0;
  840. glGenFramebuffers(1, &rad_fbo);
  841. glBindFramebuffer(GL_FRAMEBUFFER, rad_fbo);
  842. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, rad_tex, 0);
  843. glActiveTexture(GL_TEXTURE0);
  844. glBindTexture(GL_TEXTURE_CUBE_MAP, sky->radiance);
  845. glViewport(0, 0, p_size.width, p_size.height);
  846. glClearColor(0.0, 0.0, 0.0, 1.0);
  847. glClear(GL_COLOR_BUFFER_BIT);
  848. copy_effects->copy_cube_to_panorama(p_bake_irradiance ? float(sky->mipmap_count) : 0.0);
  849. glBindFramebuffer(GL_FRAMEBUFFER, GLES3::TextureStorage::system_fbo);
  850. glDeleteFramebuffers(1, &rad_fbo);
  851. // Create a dummy texture so we can use texture_2d_get.
  852. RID tex_rid = GLES3::TextureStorage::get_singleton()->texture_allocate();
  853. GLES3::Texture texture;
  854. texture.width = p_size.width;
  855. texture.height = p_size.height;
  856. texture.alloc_width = p_size.width;
  857. texture.alloc_height = p_size.height;
  858. texture.format = Image::FORMAT_RGBAF;
  859. texture.real_format = Image::FORMAT_RGBAF;
  860. texture.gl_format_cache = GL_RGBA;
  861. texture.gl_type_cache = GL_FLOAT;
  862. texture.type = GLES3::Texture::TYPE_2D;
  863. texture.target = GL_TEXTURE_2D;
  864. texture.active = true;
  865. texture.tex_id = rad_tex;
  866. texture.is_render_target = true;
  867. GLES3::TextureStorage::get_singleton()->texture_2d_initialize_from_texture(tex_rid, texture);
  868. Ref<Image> img = GLES3::TextureStorage::get_singleton()->texture_2d_get(tex_rid);
  869. GLES3::Utilities::get_singleton()->texture_free_data(rad_tex);
  870. texture.is_render_target = false;
  871. texture.tex_id = 0;
  872. GLES3::TextureStorage::get_singleton()->texture_free(tex_rid);
  873. for (int i = 0; i < p_size.width; i++) {
  874. for (int j = 0; j < p_size.height; j++) {
  875. Color c = img->get_pixel(i, j);
  876. c.r *= p_energy;
  877. c.g *= p_energy;
  878. c.b *= p_energy;
  879. img->set_pixel(i, j, c);
  880. }
  881. }
  882. return img;
  883. }
  884. /* ENVIRONMENT API */
  885. void RasterizerSceneGLES3::environment_glow_set_use_bicubic_upscale(bool p_enable) {
  886. glow_bicubic_upscale = p_enable;
  887. }
  888. void RasterizerSceneGLES3::environment_set_ssr_roughness_quality(RS::EnvironmentSSRRoughnessQuality p_quality) {
  889. }
  890. void RasterizerSceneGLES3::environment_set_ssao_quality(RS::EnvironmentSSAOQuality p_quality, bool p_half_size, float p_adaptive_target, int p_blur_passes, float p_fadeout_from, float p_fadeout_to) {
  891. }
  892. void RasterizerSceneGLES3::environment_set_ssil_quality(RS::EnvironmentSSILQuality p_quality, bool p_half_size, float p_adaptive_target, int p_blur_passes, float p_fadeout_from, float p_fadeout_to) {
  893. }
  894. void RasterizerSceneGLES3::environment_set_sdfgi_ray_count(RS::EnvironmentSDFGIRayCount p_ray_count) {
  895. }
  896. void RasterizerSceneGLES3::environment_set_sdfgi_frames_to_converge(RS::EnvironmentSDFGIFramesToConverge p_frames) {
  897. }
  898. void RasterizerSceneGLES3::environment_set_sdfgi_frames_to_update_light(RS::EnvironmentSDFGIFramesToUpdateLight p_update) {
  899. }
  900. void RasterizerSceneGLES3::environment_set_volumetric_fog_volume_size(int p_size, int p_depth) {
  901. }
  902. void RasterizerSceneGLES3::environment_set_volumetric_fog_filter_active(bool p_enable) {
  903. }
  904. Ref<Image> RasterizerSceneGLES3::environment_bake_panorama(RID p_env, bool p_bake_irradiance, const Size2i &p_size) {
  905. ERR_FAIL_COND_V(p_env.is_null(), Ref<Image>());
  906. RS::EnvironmentBG environment_background = environment_get_background(p_env);
  907. if (environment_background == RS::ENV_BG_CAMERA_FEED || environment_background == RS::ENV_BG_CANVAS || environment_background == RS::ENV_BG_KEEP) {
  908. return Ref<Image>(); // Nothing to bake.
  909. }
  910. RS::EnvironmentAmbientSource ambient_source = environment_get_ambient_source(p_env);
  911. bool use_ambient_light = false;
  912. bool use_cube_map = false;
  913. if (ambient_source == RS::ENV_AMBIENT_SOURCE_BG && (environment_background == RS::ENV_BG_CLEAR_COLOR || environment_background == RS::ENV_BG_COLOR)) {
  914. use_ambient_light = true;
  915. } else {
  916. use_cube_map = (ambient_source == RS::ENV_AMBIENT_SOURCE_BG && environment_background == RS::ENV_BG_SKY) || ambient_source == RS::ENV_AMBIENT_SOURCE_SKY;
  917. use_ambient_light = use_cube_map || ambient_source == RS::ENV_AMBIENT_SOURCE_COLOR;
  918. }
  919. use_cube_map = use_cube_map || (environment_background == RS::ENV_BG_SKY && environment_get_sky(p_env).is_valid());
  920. Color ambient_color;
  921. float ambient_color_sky_mix = 0.0;
  922. if (use_ambient_light) {
  923. ambient_color_sky_mix = environment_get_ambient_sky_contribution(p_env);
  924. const float ambient_energy = environment_get_ambient_light_energy(p_env);
  925. ambient_color = environment_get_ambient_light(p_env);
  926. ambient_color = ambient_color.srgb_to_linear();
  927. ambient_color.r *= ambient_energy;
  928. ambient_color.g *= ambient_energy;
  929. ambient_color.b *= ambient_energy;
  930. }
  931. if (use_cube_map) {
  932. Ref<Image> panorama = sky_bake_panorama(environment_get_sky(p_env), environment_get_bg_energy_multiplier(p_env), p_bake_irradiance, p_size);
  933. if (use_ambient_light) {
  934. for (int x = 0; x < p_size.width; x++) {
  935. for (int y = 0; y < p_size.height; y++) {
  936. panorama->set_pixel(x, y, ambient_color.lerp(panorama->get_pixel(x, y), ambient_color_sky_mix));
  937. }
  938. }
  939. }
  940. return panorama;
  941. } else {
  942. const float bg_energy_multiplier = environment_get_bg_energy_multiplier(p_env);
  943. Color panorama_color = ((environment_background == RS::ENV_BG_CLEAR_COLOR) ? RSG::texture_storage->get_default_clear_color() : environment_get_bg_color(p_env));
  944. panorama_color = panorama_color.srgb_to_linear();
  945. panorama_color.r *= bg_energy_multiplier;
  946. panorama_color.g *= bg_energy_multiplier;
  947. panorama_color.b *= bg_energy_multiplier;
  948. if (use_ambient_light) {
  949. panorama_color = ambient_color.lerp(panorama_color, ambient_color_sky_mix);
  950. }
  951. Ref<Image> panorama = Image::create_empty(p_size.width, p_size.height, false, Image::FORMAT_RGBAF);
  952. panorama->fill(panorama_color);
  953. return panorama;
  954. }
  955. }
  956. void RasterizerSceneGLES3::positional_soft_shadow_filter_set_quality(RS::ShadowQuality p_quality) {
  957. scene_state.positional_shadow_quality = p_quality;
  958. }
  959. void RasterizerSceneGLES3::directional_soft_shadow_filter_set_quality(RS::ShadowQuality p_quality) {
  960. scene_state.directional_shadow_quality = p_quality;
  961. }
  962. RID RasterizerSceneGLES3::fog_volume_instance_create(RID p_fog_volume) {
  963. return RID();
  964. }
  965. void RasterizerSceneGLES3::fog_volume_instance_set_transform(RID p_fog_volume_instance, const Transform3D &p_transform) {
  966. }
  967. void RasterizerSceneGLES3::fog_volume_instance_set_active(RID p_fog_volume_instance, bool p_active) {
  968. }
  969. RID RasterizerSceneGLES3::fog_volume_instance_get_volume(RID p_fog_volume_instance) const {
  970. return RID();
  971. }
  972. Vector3 RasterizerSceneGLES3::fog_volume_instance_get_position(RID p_fog_volume_instance) const {
  973. return Vector3();
  974. }
  975. RID RasterizerSceneGLES3::voxel_gi_instance_create(RID p_voxel_gi) {
  976. return RID();
  977. }
  978. void RasterizerSceneGLES3::voxel_gi_instance_set_transform_to_data(RID p_probe, const Transform3D &p_xform) {
  979. }
  980. bool RasterizerSceneGLES3::voxel_gi_needs_update(RID p_probe) const {
  981. return false;
  982. }
  983. void RasterizerSceneGLES3::voxel_gi_update(RID p_probe, bool p_update_light_instances, const Vector<RID> &p_light_instances, const PagedArray<RenderGeometryInstance *> &p_dynamic_objects) {
  984. }
  985. void RasterizerSceneGLES3::voxel_gi_set_quality(RS::VoxelGIQuality) {
  986. }
  987. _FORCE_INLINE_ static uint32_t _indices_to_primitives(RS::PrimitiveType p_primitive, uint32_t p_indices) {
  988. static const uint32_t divisor[RS::PRIMITIVE_MAX] = { 1, 2, 1, 3, 1 };
  989. static const uint32_t subtractor[RS::PRIMITIVE_MAX] = { 0, 0, 1, 0, 1 };
  990. return (p_indices - subtractor[p_primitive]) / divisor[p_primitive];
  991. }
  992. void RasterizerSceneGLES3::_fill_render_list(RenderListType p_render_list, const RenderDataGLES3 *p_render_data, PassMode p_pass_mode, bool p_append) {
  993. GLES3::MeshStorage *mesh_storage = GLES3::MeshStorage::get_singleton();
  994. GLES3::LightStorage *light_storage = GLES3::LightStorage::get_singleton();
  995. if (p_render_list == RENDER_LIST_OPAQUE) {
  996. scene_state.used_screen_texture = false;
  997. scene_state.used_normal_texture = false;
  998. scene_state.used_depth_texture = false;
  999. }
  1000. Plane near_plane;
  1001. if (p_render_data->cam_orthogonal) {
  1002. near_plane = Plane(-p_render_data->cam_transform.basis.get_column(Vector3::AXIS_Z), p_render_data->cam_transform.origin);
  1003. near_plane.d += p_render_data->cam_projection.get_z_near();
  1004. }
  1005. float z_max = p_render_data->cam_projection.get_z_far() - p_render_data->cam_projection.get_z_near();
  1006. RenderList *rl = &render_list[p_render_list];
  1007. // Parse any updates on our geometry, updates surface caches and such
  1008. _update_dirty_geometry_instances();
  1009. if (!p_append) {
  1010. rl->clear();
  1011. if (p_render_list == RENDER_LIST_OPAQUE) {
  1012. render_list[RENDER_LIST_ALPHA].clear(); //opaque fills alpha too
  1013. }
  1014. }
  1015. //fill list
  1016. for (int i = 0; i < (int)p_render_data->instances->size(); i++) {
  1017. GeometryInstanceGLES3 *inst = static_cast<GeometryInstanceGLES3 *>((*p_render_data->instances)[i]);
  1018. Vector3 center = inst->transform.origin;
  1019. if (p_render_data->cam_orthogonal) {
  1020. if (inst->use_aabb_center) {
  1021. center = inst->transformed_aabb.get_support(-near_plane.normal);
  1022. }
  1023. inst->depth = near_plane.distance_to(center) - inst->sorting_offset;
  1024. } else {
  1025. if (inst->use_aabb_center) {
  1026. center = inst->transformed_aabb.position + (inst->transformed_aabb.size * 0.5);
  1027. }
  1028. inst->depth = p_render_data->cam_transform.origin.distance_to(center) - inst->sorting_offset;
  1029. }
  1030. uint32_t depth_layer = CLAMP(int(inst->depth * 16 / z_max), 0, 15);
  1031. uint32_t flags = inst->base_flags; //fill flags if appropriate
  1032. if (inst->non_uniform_scale) {
  1033. flags |= INSTANCE_DATA_FLAGS_NON_UNIFORM_SCALE;
  1034. }
  1035. // Sets the index values for lookup in the shader
  1036. // This has to be done after _setup_lights was called this frame
  1037. if (p_pass_mode == PASS_MODE_COLOR) {
  1038. inst->light_passes.clear();
  1039. inst->spot_light_gl_cache.clear();
  1040. inst->omni_light_gl_cache.clear();
  1041. inst->reflection_probes_local_transform_cache.clear();
  1042. inst->reflection_probe_rid_cache.clear();
  1043. uint64_t current_frame = RSG::rasterizer->get_frame_number();
  1044. if (inst->paired_omni_light_count) {
  1045. for (uint32_t j = 0; j < inst->paired_omni_light_count; j++) {
  1046. RID light_instance = inst->paired_omni_lights[j];
  1047. if (light_storage->light_instance_get_render_pass(light_instance) != current_frame) {
  1048. continue;
  1049. }
  1050. RID light = light_storage->light_instance_get_base_light(light_instance);
  1051. int32_t shadow_id = light_storage->light_instance_get_shadow_id(light_instance);
  1052. if (light_storage->light_has_shadow(light) && shadow_id >= 0) {
  1053. GeometryInstanceGLES3::LightPass pass;
  1054. pass.light_id = light_storage->light_instance_get_gl_id(light_instance);
  1055. pass.shadow_id = shadow_id;
  1056. pass.light_instance_rid = light_instance;
  1057. pass.is_omni = true;
  1058. inst->light_passes.push_back(pass);
  1059. } else {
  1060. // Lights without shadow can all go in base pass.
  1061. inst->omni_light_gl_cache.push_back((uint32_t)light_storage->light_instance_get_gl_id(light_instance));
  1062. }
  1063. }
  1064. }
  1065. if (inst->paired_spot_light_count) {
  1066. for (uint32_t j = 0; j < inst->paired_spot_light_count; j++) {
  1067. RID light_instance = inst->paired_spot_lights[j];
  1068. if (light_storage->light_instance_get_render_pass(light_instance) != current_frame) {
  1069. continue;
  1070. }
  1071. RID light = light_storage->light_instance_get_base_light(light_instance);
  1072. int32_t shadow_id = light_storage->light_instance_get_shadow_id(light_instance);
  1073. if (light_storage->light_has_shadow(light) && shadow_id >= 0) {
  1074. GeometryInstanceGLES3::LightPass pass;
  1075. pass.light_id = light_storage->light_instance_get_gl_id(light_instance);
  1076. pass.shadow_id = shadow_id;
  1077. pass.light_instance_rid = light_instance;
  1078. inst->light_passes.push_back(pass);
  1079. } else {
  1080. // Lights without shadow can all go in base pass.
  1081. inst->spot_light_gl_cache.push_back((uint32_t)light_storage->light_instance_get_gl_id(light_instance));
  1082. }
  1083. }
  1084. }
  1085. if (p_render_data->reflection_probe.is_null() && inst->paired_reflection_probes.size() > 0) {
  1086. // Do not include if we're rendering reflection probes.
  1087. // We only support two probes for now and we handle them first come, first serve.
  1088. // This should be improved one day, at minimum the list should be sorted by priority.
  1089. for (uint32_t pi = 0; pi < inst->paired_reflection_probes.size(); pi++) {
  1090. RID probe_instance = inst->paired_reflection_probes[pi];
  1091. RID atlas = light_storage->reflection_probe_instance_get_atlas(probe_instance);
  1092. RID probe = light_storage->reflection_probe_instance_get_probe(probe_instance);
  1093. uint32_t reflection_mask = light_storage->reflection_probe_get_reflection_mask(probe);
  1094. if (atlas.is_valid() && (inst->layer_mask & reflection_mask)) {
  1095. Transform3D local_matrix = p_render_data->inv_cam_transform * light_storage->reflection_probe_instance_get_transform(probe_instance);
  1096. inst->reflection_probes_local_transform_cache.push_back(local_matrix.affine_inverse());
  1097. inst->reflection_probe_rid_cache.push_back(probe_instance);
  1098. }
  1099. }
  1100. }
  1101. }
  1102. inst->flags_cache = flags;
  1103. GeometryInstanceSurface *surf = inst->surface_caches;
  1104. float lod_distance = 0.0;
  1105. if (p_render_data->cam_orthogonal) {
  1106. lod_distance = 1.0;
  1107. } else {
  1108. Vector3 aabb_min = inst->transformed_aabb.position;
  1109. Vector3 aabb_max = inst->transformed_aabb.position + inst->transformed_aabb.size;
  1110. Vector3 camera_position = p_render_data->main_cam_transform.origin;
  1111. Vector3 surface_distance = Vector3(0.0, 0.0, 0.0).max(aabb_min - camera_position).max(camera_position - aabb_max);
  1112. lod_distance = surface_distance.length();
  1113. }
  1114. while (surf) {
  1115. // LOD
  1116. if (p_render_data->screen_mesh_lod_threshold > 0.0 && mesh_storage->mesh_surface_has_lod(surf->surface)) {
  1117. uint32_t indices = 0;
  1118. surf->lod_index = mesh_storage->mesh_surface_get_lod(surf->surface, inst->lod_model_scale * inst->lod_bias, lod_distance * p_render_data->lod_distance_multiplier, p_render_data->screen_mesh_lod_threshold, indices);
  1119. surf->index_count = indices;
  1120. if (p_render_data->render_info) {
  1121. indices = _indices_to_primitives(surf->primitive, indices);
  1122. if (p_render_list == RENDER_LIST_OPAQUE) { //opaque
  1123. p_render_data->render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_VISIBLE][RS::VIEWPORT_RENDER_INFO_PRIMITIVES_IN_FRAME] += indices;
  1124. } else if (p_render_list == RENDER_LIST_SECONDARY) { //shadow
  1125. p_render_data->render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_SHADOW][RS::VIEWPORT_RENDER_INFO_PRIMITIVES_IN_FRAME] += indices;
  1126. }
  1127. }
  1128. } else {
  1129. surf->lod_index = 0;
  1130. if (p_render_data->render_info) {
  1131. uint32_t to_draw = mesh_storage->mesh_surface_get_vertices_drawn_count(surf->surface);
  1132. to_draw = _indices_to_primitives(surf->primitive, to_draw);
  1133. to_draw *= inst->instance_count > 0 ? inst->instance_count : 1;
  1134. if (p_render_list == RENDER_LIST_OPAQUE) { //opaque
  1135. p_render_data->render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_VISIBLE][RS::VIEWPORT_RENDER_INFO_PRIMITIVES_IN_FRAME] += to_draw;
  1136. } else if (p_render_list == RENDER_LIST_SECONDARY) { //shadow
  1137. p_render_data->render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_SHADOW][RS::VIEWPORT_RENDER_INFO_PRIMITIVES_IN_FRAME] += to_draw;
  1138. }
  1139. }
  1140. }
  1141. // ADD Element
  1142. if (p_pass_mode == PASS_MODE_COLOR) {
  1143. #ifdef DEBUG_ENABLED
  1144. bool force_alpha = unlikely(get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_OVERDRAW);
  1145. #else
  1146. bool force_alpha = false;
  1147. #endif
  1148. if (!force_alpha && (surf->flags & (GeometryInstanceSurface::FLAG_PASS_DEPTH | GeometryInstanceSurface::FLAG_PASS_OPAQUE))) {
  1149. rl->add_element(surf);
  1150. }
  1151. if (force_alpha || (surf->flags & GeometryInstanceSurface::FLAG_PASS_ALPHA)) {
  1152. render_list[RENDER_LIST_ALPHA].add_element(surf);
  1153. }
  1154. if (surf->flags & GeometryInstanceSurface::FLAG_USES_SCREEN_TEXTURE) {
  1155. scene_state.used_screen_texture = true;
  1156. }
  1157. if (surf->flags & GeometryInstanceSurface::FLAG_USES_NORMAL_TEXTURE) {
  1158. scene_state.used_normal_texture = true;
  1159. }
  1160. if (surf->flags & GeometryInstanceSurface::FLAG_USES_DEPTH_TEXTURE) {
  1161. scene_state.used_depth_texture = true;
  1162. }
  1163. } else if (p_pass_mode == PASS_MODE_SHADOW) {
  1164. if (surf->flags & GeometryInstanceSurface::FLAG_PASS_SHADOW) {
  1165. rl->add_element(surf);
  1166. }
  1167. } else if (p_pass_mode == PASS_MODE_MATERIAL) {
  1168. if (surf->flags & (GeometryInstanceSurface::FLAG_PASS_DEPTH | GeometryInstanceSurface::FLAG_PASS_OPAQUE | GeometryInstanceSurface::FLAG_PASS_ALPHA)) {
  1169. rl->add_element(surf);
  1170. }
  1171. } else {
  1172. if (surf->flags & (GeometryInstanceSurface::FLAG_PASS_DEPTH | GeometryInstanceSurface::FLAG_PASS_OPAQUE)) {
  1173. rl->add_element(surf);
  1174. }
  1175. }
  1176. surf->sort.depth_layer = depth_layer;
  1177. surf->finished_base_pass = false;
  1178. surf->light_pass_index = 0;
  1179. surf = surf->next;
  1180. }
  1181. }
  1182. }
  1183. // Needs to be called after _setup_lights so that directional_light_count is accurate.
  1184. void RasterizerSceneGLES3::_setup_environment(const RenderDataGLES3 *p_render_data, bool p_no_fog, const Size2i &p_screen_size, bool p_flip_y, const Color &p_default_bg_color, bool p_pancake_shadows, float p_shadow_bias) {
  1185. Projection correction;
  1186. correction.set_depth_correction(p_flip_y, true, false);
  1187. Projection projection = correction * p_render_data->cam_projection;
  1188. //store camera into ubo
  1189. GLES3::MaterialStorage::store_camera(projection, scene_state.ubo.projection_matrix);
  1190. GLES3::MaterialStorage::store_camera(projection.inverse(), scene_state.ubo.inv_projection_matrix);
  1191. GLES3::MaterialStorage::store_transform(p_render_data->cam_transform, scene_state.ubo.inv_view_matrix);
  1192. GLES3::MaterialStorage::store_transform(p_render_data->inv_cam_transform, scene_state.ubo.view_matrix);
  1193. GLES3::MaterialStorage::store_transform(p_render_data->main_cam_transform, scene_state.ubo.main_cam_inv_view_matrix);
  1194. scene_state.ubo.camera_visible_layers = p_render_data->camera_visible_layers;
  1195. if (p_render_data->view_count > 1) {
  1196. for (uint32_t v = 0; v < p_render_data->view_count; v++) {
  1197. projection = correction * p_render_data->view_projection[v];
  1198. GLES3::MaterialStorage::store_camera(projection, scene_state.multiview_ubo.projection_matrix_view[v]);
  1199. GLES3::MaterialStorage::store_camera(projection.inverse(), scene_state.multiview_ubo.inv_projection_matrix_view[v]);
  1200. scene_state.multiview_ubo.eye_offset[v][0] = p_render_data->view_eye_offset[v].x;
  1201. scene_state.multiview_ubo.eye_offset[v][1] = p_render_data->view_eye_offset[v].y;
  1202. scene_state.multiview_ubo.eye_offset[v][2] = p_render_data->view_eye_offset[v].z;
  1203. scene_state.multiview_ubo.eye_offset[v][3] = 0.0;
  1204. }
  1205. }
  1206. // Only render the lights without shadows in the base pass.
  1207. scene_state.ubo.directional_light_count = p_render_data->directional_light_count - p_render_data->directional_shadow_count;
  1208. scene_state.ubo.z_far = p_render_data->z_far;
  1209. scene_state.ubo.z_near = p_render_data->z_near;
  1210. scene_state.ubo.viewport_size[0] = p_screen_size.x;
  1211. scene_state.ubo.viewport_size[1] = p_screen_size.y;
  1212. Size2 screen_pixel_size = Vector2(1.0, 1.0) / Size2(p_screen_size);
  1213. scene_state.ubo.screen_pixel_size[0] = screen_pixel_size.x;
  1214. scene_state.ubo.screen_pixel_size[1] = screen_pixel_size.y;
  1215. scene_state.ubo.luminance_multiplier = p_render_data->luminance_multiplier;
  1216. scene_state.ubo.shadow_bias = p_shadow_bias;
  1217. scene_state.ubo.pancake_shadows = p_pancake_shadows;
  1218. //time global variables
  1219. scene_state.ubo.time = time;
  1220. if (get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_UNSHADED) {
  1221. scene_state.ubo.use_ambient_light = true;
  1222. scene_state.ubo.ambient_light_color_energy[0] = 1;
  1223. scene_state.ubo.ambient_light_color_energy[1] = 1;
  1224. scene_state.ubo.ambient_light_color_energy[2] = 1;
  1225. scene_state.ubo.ambient_light_color_energy[3] = 1.0;
  1226. scene_state.ubo.use_ambient_cubemap = false;
  1227. scene_state.ubo.use_reflection_cubemap = false;
  1228. } else if (is_environment(p_render_data->environment)) {
  1229. RS::EnvironmentBG env_bg = environment_get_background(p_render_data->environment);
  1230. RS::EnvironmentAmbientSource ambient_src = environment_get_ambient_source(p_render_data->environment);
  1231. float bg_energy_multiplier = environment_get_bg_energy_multiplier(p_render_data->environment);
  1232. scene_state.ubo.ambient_light_color_energy[3] = bg_energy_multiplier;
  1233. scene_state.ubo.ambient_color_sky_mix = environment_get_ambient_sky_contribution(p_render_data->environment);
  1234. //ambient
  1235. if (ambient_src == RS::ENV_AMBIENT_SOURCE_BG && (env_bg == RS::ENV_BG_CLEAR_COLOR || env_bg == RS::ENV_BG_COLOR)) {
  1236. Color color = env_bg == RS::ENV_BG_CLEAR_COLOR ? p_default_bg_color : environment_get_bg_color(p_render_data->environment);
  1237. color = color.srgb_to_linear();
  1238. scene_state.ubo.ambient_light_color_energy[0] = color.r * bg_energy_multiplier;
  1239. scene_state.ubo.ambient_light_color_energy[1] = color.g * bg_energy_multiplier;
  1240. scene_state.ubo.ambient_light_color_energy[2] = color.b * bg_energy_multiplier;
  1241. scene_state.ubo.use_ambient_light = true;
  1242. scene_state.ubo.use_ambient_cubemap = false;
  1243. } else {
  1244. float energy = environment_get_ambient_light_energy(p_render_data->environment);
  1245. Color color = environment_get_ambient_light(p_render_data->environment);
  1246. color = color.srgb_to_linear();
  1247. scene_state.ubo.ambient_light_color_energy[0] = color.r * energy;
  1248. scene_state.ubo.ambient_light_color_energy[1] = color.g * energy;
  1249. scene_state.ubo.ambient_light_color_energy[2] = color.b * energy;
  1250. Basis sky_transform = environment_get_sky_orientation(p_render_data->environment);
  1251. sky_transform = sky_transform.inverse() * p_render_data->cam_transform.basis;
  1252. GLES3::MaterialStorage::store_transform_3x3(sky_transform, scene_state.ubo.radiance_inverse_xform);
  1253. scene_state.ubo.use_ambient_cubemap = (ambient_src == RS::ENV_AMBIENT_SOURCE_BG && env_bg == RS::ENV_BG_SKY) || ambient_src == RS::ENV_AMBIENT_SOURCE_SKY;
  1254. scene_state.ubo.use_ambient_light = scene_state.ubo.use_ambient_cubemap || ambient_src == RS::ENV_AMBIENT_SOURCE_COLOR;
  1255. }
  1256. //specular
  1257. RS::EnvironmentReflectionSource ref_src = environment_get_reflection_source(p_render_data->environment);
  1258. if ((ref_src == RS::ENV_REFLECTION_SOURCE_BG && env_bg == RS::ENV_BG_SKY) || ref_src == RS::ENV_REFLECTION_SOURCE_SKY) {
  1259. scene_state.ubo.use_reflection_cubemap = true;
  1260. } else {
  1261. scene_state.ubo.use_reflection_cubemap = false;
  1262. }
  1263. scene_state.ubo.fog_enabled = environment_get_fog_enabled(p_render_data->environment);
  1264. scene_state.ubo.fog_mode = environment_get_fog_mode(p_render_data->environment);
  1265. scene_state.ubo.fog_density = environment_get_fog_density(p_render_data->environment);
  1266. scene_state.ubo.fog_height = environment_get_fog_height(p_render_data->environment);
  1267. scene_state.ubo.fog_depth_curve = environment_get_fog_depth_curve(p_render_data->environment);
  1268. scene_state.ubo.fog_depth_end = environment_get_fog_depth_end(p_render_data->environment) > 0.0 ? environment_get_fog_depth_end(p_render_data->environment) : scene_state.ubo.z_far;
  1269. scene_state.ubo.fog_depth_begin = MIN(environment_get_fog_depth_begin(p_render_data->environment), scene_state.ubo.fog_depth_end - 0.001);
  1270. scene_state.ubo.fog_height_density = environment_get_fog_height_density(p_render_data->environment);
  1271. scene_state.ubo.fog_aerial_perspective = environment_get_fog_aerial_perspective(p_render_data->environment);
  1272. Color fog_color = environment_get_fog_light_color(p_render_data->environment).srgb_to_linear();
  1273. float fog_energy = environment_get_fog_light_energy(p_render_data->environment);
  1274. scene_state.ubo.fog_light_color[0] = fog_color.r * fog_energy;
  1275. scene_state.ubo.fog_light_color[1] = fog_color.g * fog_energy;
  1276. scene_state.ubo.fog_light_color[2] = fog_color.b * fog_energy;
  1277. scene_state.ubo.fog_sun_scatter = environment_get_fog_sun_scatter(p_render_data->environment);
  1278. } else {
  1279. }
  1280. if (p_render_data->camera_attributes.is_valid()) {
  1281. scene_state.ubo.emissive_exposure_normalization = RSG::camera_attributes->camera_attributes_get_exposure_normalization_factor(p_render_data->camera_attributes);
  1282. scene_state.ubo.IBL_exposure_normalization = 1.0;
  1283. if (is_environment(p_render_data->environment)) {
  1284. RID sky_rid = environment_get_sky(p_render_data->environment);
  1285. if (sky_rid.is_valid()) {
  1286. float current_exposure = RSG::camera_attributes->camera_attributes_get_exposure_normalization_factor(p_render_data->camera_attributes) * environment_get_bg_intensity(p_render_data->environment);
  1287. scene_state.ubo.IBL_exposure_normalization = current_exposure / MAX(0.001, sky_get_baked_exposure(sky_rid));
  1288. }
  1289. }
  1290. } else if (scene_state.ubo.emissive_exposure_normalization > 0.0) {
  1291. // This branch is triggered when using render_material().
  1292. // Emissive is set outside the function, so don't set it.
  1293. // IBL isn't used don't set it.
  1294. } else {
  1295. scene_state.ubo.emissive_exposure_normalization = 1.0;
  1296. scene_state.ubo.IBL_exposure_normalization = 1.0;
  1297. }
  1298. if (scene_state.ubo_buffer == 0) {
  1299. glGenBuffers(1, &scene_state.ubo_buffer);
  1300. glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_DATA_UNIFORM_LOCATION, scene_state.ubo_buffer);
  1301. GLES3::Utilities::get_singleton()->buffer_allocate_data(GL_UNIFORM_BUFFER, scene_state.ubo_buffer, sizeof(SceneState::UBO), &scene_state.ubo, GL_STREAM_DRAW, "Scene state UBO");
  1302. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  1303. } else {
  1304. glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_DATA_UNIFORM_LOCATION, scene_state.ubo_buffer);
  1305. glBufferData(GL_UNIFORM_BUFFER, sizeof(SceneState::UBO), &scene_state.ubo, GL_STREAM_DRAW);
  1306. }
  1307. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  1308. if (p_render_data->view_count > 1) {
  1309. if (scene_state.multiview_buffer == 0) {
  1310. glGenBuffers(1, &scene_state.multiview_buffer);
  1311. glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_MULTIVIEW_UNIFORM_LOCATION, scene_state.multiview_buffer);
  1312. GLES3::Utilities::get_singleton()->buffer_allocate_data(GL_UNIFORM_BUFFER, scene_state.multiview_buffer, sizeof(SceneState::MultiviewUBO), &scene_state.multiview_ubo, GL_STREAM_DRAW, "Multiview UBO");
  1313. } else {
  1314. glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_MULTIVIEW_UNIFORM_LOCATION, scene_state.multiview_buffer);
  1315. glBufferData(GL_UNIFORM_BUFFER, sizeof(SceneState::MultiviewUBO), &scene_state.multiview_ubo, GL_STREAM_DRAW);
  1316. }
  1317. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  1318. }
  1319. }
  1320. // Puts lights into Uniform Buffers. Needs to be called before _fill_list as this caches the index of each light in the Uniform Buffer
  1321. void RasterizerSceneGLES3::_setup_lights(const RenderDataGLES3 *p_render_data, bool p_using_shadows, uint32_t &r_directional_light_count, uint32_t &r_omni_light_count, uint32_t &r_spot_light_count, uint32_t &r_directional_shadow_count) {
  1322. GLES3::LightStorage *light_storage = GLES3::LightStorage::get_singleton();
  1323. GLES3::Config *config = GLES3::Config::get_singleton();
  1324. const Transform3D inverse_transform = p_render_data->inv_cam_transform;
  1325. const PagedArray<RID> &lights = *p_render_data->lights;
  1326. r_directional_light_count = 0;
  1327. r_omni_light_count = 0;
  1328. r_spot_light_count = 0;
  1329. r_directional_shadow_count = 0;
  1330. int num_lights = lights.size();
  1331. for (int i = 0; i < num_lights; i++) {
  1332. GLES3::LightInstance *li = GLES3::LightStorage::get_singleton()->get_light_instance(lights[i]);
  1333. if (!li) {
  1334. continue;
  1335. }
  1336. RID base = li->light;
  1337. ERR_CONTINUE(base.is_null());
  1338. RS::LightType type = light_storage->light_get_type(base);
  1339. switch (type) {
  1340. case RS::LIGHT_DIRECTIONAL: {
  1341. if (r_directional_light_count >= RendererSceneRender::MAX_DIRECTIONAL_LIGHTS || light_storage->light_directional_get_sky_mode(base) == RS::LIGHT_DIRECTIONAL_SKY_MODE_SKY_ONLY) {
  1342. continue;
  1343. }
  1344. // If a DirectionalLight has shadows, we will add it to the end of the array and work in.
  1345. bool has_shadow = light_storage->light_has_shadow(base);
  1346. int index = r_directional_light_count - r_directional_shadow_count;
  1347. if (has_shadow) {
  1348. // Lights with shadow are incremented from the end of the array.
  1349. index = MAX_DIRECTIONAL_LIGHTS - 1 - r_directional_shadow_count;
  1350. }
  1351. DirectionalLightData &light_data = scene_state.directional_lights[index];
  1352. Transform3D light_transform = li->transform;
  1353. Vector3 direction = inverse_transform.basis.xform(light_transform.basis.xform(Vector3(0, 0, 1))).normalized();
  1354. light_data.direction[0] = direction.x;
  1355. light_data.direction[1] = direction.y;
  1356. light_data.direction[2] = direction.z;
  1357. light_data.bake_mode = light_storage->light_get_bake_mode(base);
  1358. float sign = light_storage->light_is_negative(base) ? -1 : 1;
  1359. light_data.energy = sign * light_storage->light_get_param(base, RS::LIGHT_PARAM_ENERGY);
  1360. if (is_using_physical_light_units()) {
  1361. light_data.energy *= light_storage->light_get_param(base, RS::LIGHT_PARAM_INTENSITY);
  1362. } else {
  1363. light_data.energy *= Math_PI;
  1364. }
  1365. if (p_render_data->camera_attributes.is_valid()) {
  1366. light_data.energy *= RSG::camera_attributes->camera_attributes_get_exposure_normalization_factor(p_render_data->camera_attributes);
  1367. }
  1368. Color linear_col = light_storage->light_get_color(base).srgb_to_linear();
  1369. light_data.color[0] = linear_col.r;
  1370. light_data.color[1] = linear_col.g;
  1371. light_data.color[2] = linear_col.b;
  1372. float size = light_storage->light_get_param(base, RS::LIGHT_PARAM_SIZE);
  1373. light_data.size = 1.0 - Math::cos(Math::deg_to_rad(size)); //angle to cosine offset
  1374. light_data.specular = light_storage->light_get_param(base, RS::LIGHT_PARAM_SPECULAR);
  1375. light_data.shadow_opacity = (p_using_shadows && light_storage->light_has_shadow(base))
  1376. ? light_storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_OPACITY)
  1377. : 0.0;
  1378. if (has_shadow) {
  1379. DirectionalShadowData &shadow_data = scene_state.directional_shadows[MAX_DIRECTIONAL_LIGHTS - 1 - r_directional_shadow_count];
  1380. RS::LightDirectionalShadowMode shadow_mode = light_storage->light_directional_get_shadow_mode(base);
  1381. int limit = shadow_mode == RS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL ? 0 : (shadow_mode == RS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS ? 1 : 3);
  1382. shadow_data.shadow_atlas_pixel_size = 1.0 / light_storage->directional_shadow_get_size();
  1383. shadow_data.blend_splits = uint32_t((shadow_mode != RS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL) && light_storage->light_directional_get_blend_splits(base));
  1384. for (int j = 0; j < 4; j++) {
  1385. Rect2 atlas_rect = li->shadow_transform[j].atlas_rect;
  1386. Projection correction;
  1387. correction.set_depth_correction(false, true, false);
  1388. Projection matrix = correction * li->shadow_transform[j].camera;
  1389. float split = li->shadow_transform[MIN(limit, j)].split;
  1390. Projection bias;
  1391. bias.set_light_bias();
  1392. Projection rectm;
  1393. rectm.set_light_atlas_rect(atlas_rect);
  1394. Transform3D modelview = (inverse_transform * li->shadow_transform[j].transform).inverse();
  1395. shadow_data.direction[0] = light_data.direction[0];
  1396. shadow_data.direction[1] = light_data.direction[1];
  1397. shadow_data.direction[2] = light_data.direction[2];
  1398. Projection shadow_mtx = rectm * bias * matrix * modelview;
  1399. shadow_data.shadow_split_offsets[j] = split;
  1400. shadow_data.shadow_normal_bias[j] = light_storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_NORMAL_BIAS) * li->shadow_transform[j].shadow_texel_size;
  1401. GLES3::MaterialStorage::store_camera(shadow_mtx, shadow_data.shadow_matrices[j]);
  1402. }
  1403. float fade_start = light_storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_FADE_START);
  1404. shadow_data.fade_from = -shadow_data.shadow_split_offsets[3] * MIN(fade_start, 0.999);
  1405. shadow_data.fade_to = -shadow_data.shadow_split_offsets[3];
  1406. r_directional_shadow_count++;
  1407. }
  1408. r_directional_light_count++;
  1409. } break;
  1410. case RS::LIGHT_OMNI: {
  1411. if (r_omni_light_count >= (uint32_t)config->max_renderable_lights) {
  1412. continue;
  1413. }
  1414. const real_t distance = p_render_data->cam_transform.origin.distance_to(li->transform.origin);
  1415. if (light_storage->light_is_distance_fade_enabled(li->light)) {
  1416. const float fade_begin = light_storage->light_get_distance_fade_begin(li->light);
  1417. const float fade_length = light_storage->light_get_distance_fade_length(li->light);
  1418. if (distance > fade_begin) {
  1419. if (distance > fade_begin + fade_length) {
  1420. // Out of range, don't draw this light to improve performance.
  1421. continue;
  1422. }
  1423. }
  1424. }
  1425. scene_state.omni_light_sort[r_omni_light_count].instance = li;
  1426. scene_state.omni_light_sort[r_omni_light_count].depth = distance;
  1427. r_omni_light_count++;
  1428. } break;
  1429. case RS::LIGHT_SPOT: {
  1430. if (r_spot_light_count >= (uint32_t)config->max_renderable_lights) {
  1431. continue;
  1432. }
  1433. const real_t distance = p_render_data->cam_transform.origin.distance_to(li->transform.origin);
  1434. if (light_storage->light_is_distance_fade_enabled(li->light)) {
  1435. const float fade_begin = light_storage->light_get_distance_fade_begin(li->light);
  1436. const float fade_length = light_storage->light_get_distance_fade_length(li->light);
  1437. if (distance > fade_begin) {
  1438. if (distance > fade_begin + fade_length) {
  1439. // Out of range, don't draw this light to improve performance.
  1440. continue;
  1441. }
  1442. }
  1443. }
  1444. scene_state.spot_light_sort[r_spot_light_count].instance = li;
  1445. scene_state.spot_light_sort[r_spot_light_count].depth = distance;
  1446. r_spot_light_count++;
  1447. } break;
  1448. }
  1449. li->last_pass = RSG::rasterizer->get_frame_number();
  1450. }
  1451. if (r_omni_light_count) {
  1452. SortArray<InstanceSort<GLES3::LightInstance>> sorter;
  1453. sorter.sort(scene_state.omni_light_sort, r_omni_light_count);
  1454. }
  1455. if (r_spot_light_count) {
  1456. SortArray<InstanceSort<GLES3::LightInstance>> sorter;
  1457. sorter.sort(scene_state.spot_light_sort, r_spot_light_count);
  1458. }
  1459. int num_positional_shadows = 0;
  1460. for (uint32_t i = 0; i < (r_omni_light_count + r_spot_light_count); i++) {
  1461. uint32_t index = (i < r_omni_light_count) ? i : i - (r_omni_light_count);
  1462. LightData &light_data = (i < r_omni_light_count) ? scene_state.omni_lights[index] : scene_state.spot_lights[index];
  1463. RS::LightType type = (i < r_omni_light_count) ? RS::LIGHT_OMNI : RS::LIGHT_SPOT;
  1464. GLES3::LightInstance *li = (i < r_omni_light_count) ? scene_state.omni_light_sort[index].instance : scene_state.spot_light_sort[index].instance;
  1465. real_t distance = (i < r_omni_light_count) ? scene_state.omni_light_sort[index].depth : scene_state.spot_light_sort[index].depth;
  1466. RID base = li->light;
  1467. li->gl_id = index;
  1468. Transform3D light_transform = li->transform;
  1469. Vector3 pos = inverse_transform.xform(light_transform.origin);
  1470. light_data.position[0] = pos.x;
  1471. light_data.position[1] = pos.y;
  1472. light_data.position[2] = pos.z;
  1473. light_data.bake_mode = light_storage->light_get_bake_mode(base);
  1474. float radius = MAX(0.001, light_storage->light_get_param(base, RS::LIGHT_PARAM_RANGE));
  1475. light_data.inv_radius = 1.0 / radius;
  1476. Vector3 direction = inverse_transform.basis.xform(light_transform.basis.xform(Vector3(0, 0, -1))).normalized();
  1477. light_data.direction[0] = direction.x;
  1478. light_data.direction[1] = direction.y;
  1479. light_data.direction[2] = direction.z;
  1480. float size = light_storage->light_get_param(base, RS::LIGHT_PARAM_SIZE);
  1481. light_data.size = size;
  1482. float sign = light_storage->light_is_negative(base) ? -1 : 1;
  1483. Color linear_col = light_storage->light_get_color(base).srgb_to_linear();
  1484. // Reuse fade begin, fade length and distance for shadow LOD determination later.
  1485. float fade_begin = 0.0;
  1486. float fade_shadow = 0.0;
  1487. float fade_length = 0.0;
  1488. float fade = 1.0;
  1489. float shadow_opacity_fade = 1.0;
  1490. if (light_storage->light_is_distance_fade_enabled(base)) {
  1491. fade_begin = light_storage->light_get_distance_fade_begin(base);
  1492. fade_shadow = light_storage->light_get_distance_fade_shadow(base);
  1493. fade_length = light_storage->light_get_distance_fade_length(base);
  1494. if (distance > fade_begin) {
  1495. // Use `smoothstep()` to make opacity changes more gradual and less noticeable to the player.
  1496. fade = Math::smoothstep(0.0f, 1.0f, 1.0f - float(distance - fade_begin) / fade_length);
  1497. }
  1498. if (distance > fade_shadow) {
  1499. shadow_opacity_fade = Math::smoothstep(0.0f, 1.0f, 1.0f - float(distance - fade_shadow) / fade_length);
  1500. }
  1501. }
  1502. float energy = sign * light_storage->light_get_param(base, RS::LIGHT_PARAM_ENERGY) * fade;
  1503. if (is_using_physical_light_units()) {
  1504. energy *= light_storage->light_get_param(base, RS::LIGHT_PARAM_INTENSITY);
  1505. // Convert from Luminous Power to Luminous Intensity
  1506. if (type == RS::LIGHT_OMNI) {
  1507. energy *= 1.0 / (Math_PI * 4.0);
  1508. } else {
  1509. // Spot Lights are not physically accurate, Luminous Intensity should change in relation to the cone angle.
  1510. // We make this assumption to keep them easy to control.
  1511. energy *= 1.0 / Math_PI;
  1512. }
  1513. } else {
  1514. energy *= Math_PI;
  1515. }
  1516. if (p_render_data->camera_attributes.is_valid()) {
  1517. energy *= RSG::camera_attributes->camera_attributes_get_exposure_normalization_factor(p_render_data->camera_attributes);
  1518. }
  1519. light_data.color[0] = linear_col.r * energy;
  1520. light_data.color[1] = linear_col.g * energy;
  1521. light_data.color[2] = linear_col.b * energy;
  1522. light_data.attenuation = light_storage->light_get_param(base, RS::LIGHT_PARAM_ATTENUATION);
  1523. light_data.inv_spot_attenuation = 1.0f / light_storage->light_get_param(base, RS::LIGHT_PARAM_SPOT_ATTENUATION);
  1524. float spot_angle = light_storage->light_get_param(base, RS::LIGHT_PARAM_SPOT_ANGLE);
  1525. light_data.cos_spot_angle = Math::cos(Math::deg_to_rad(spot_angle));
  1526. light_data.specular_amount = light_storage->light_get_param(base, RS::LIGHT_PARAM_SPECULAR) * 2.0;
  1527. // Setup shadows
  1528. const bool needs_shadow =
  1529. p_using_shadows &&
  1530. light_storage->owns_shadow_atlas(p_render_data->shadow_atlas) &&
  1531. light_storage->shadow_atlas_owns_light_instance(p_render_data->shadow_atlas, li->self) &&
  1532. light_storage->light_has_shadow(base);
  1533. bool in_shadow_range = true;
  1534. if (needs_shadow && light_storage->light_is_distance_fade_enabled(base)) {
  1535. if (distance > fade_shadow + fade_length) {
  1536. // Out of range, don't draw shadows to improve performance.
  1537. in_shadow_range = false;
  1538. }
  1539. }
  1540. // Fill in the shadow information.
  1541. if (needs_shadow && in_shadow_range) {
  1542. if (num_positional_shadows >= config->max_renderable_lights) {
  1543. continue;
  1544. }
  1545. ShadowData &shadow_data = scene_state.positional_shadows[num_positional_shadows];
  1546. li->shadow_id = num_positional_shadows;
  1547. num_positional_shadows++;
  1548. light_data.shadow_opacity = light_storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_OPACITY) * shadow_opacity_fade;
  1549. float shadow_texel_size = light_storage->light_instance_get_shadow_texel_size(li->self, p_render_data->shadow_atlas);
  1550. shadow_data.shadow_atlas_pixel_size = shadow_texel_size;
  1551. shadow_data.shadow_normal_bias = light_storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_NORMAL_BIAS) * shadow_texel_size * 10.0;
  1552. shadow_data.light_position[0] = light_data.position[0];
  1553. shadow_data.light_position[1] = light_data.position[1];
  1554. shadow_data.light_position[2] = light_data.position[2];
  1555. if (type == RS::LIGHT_OMNI) {
  1556. Transform3D proj = (inverse_transform * light_transform).inverse();
  1557. GLES3::MaterialStorage::store_transform(proj, shadow_data.shadow_matrix);
  1558. } else if (type == RS::LIGHT_SPOT) {
  1559. Transform3D modelview = (inverse_transform * light_transform).inverse();
  1560. Projection bias;
  1561. bias.set_light_bias();
  1562. Projection correction;
  1563. correction.set_depth_correction(false, true, false);
  1564. Projection cm = correction * li->shadow_transform[0].camera;
  1565. Projection shadow_mtx = bias * cm * modelview;
  1566. GLES3::MaterialStorage::store_camera(shadow_mtx, shadow_data.shadow_matrix);
  1567. }
  1568. }
  1569. }
  1570. // TODO, to avoid stalls, should rotate between 3 buffers based on frame index.
  1571. // TODO, consider mapping the buffer as in 2D
  1572. glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_OMNILIGHT_UNIFORM_LOCATION, scene_state.omni_light_buffer);
  1573. if (r_omni_light_count) {
  1574. glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(LightData) * r_omni_light_count, scene_state.omni_lights);
  1575. }
  1576. glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_SPOTLIGHT_UNIFORM_LOCATION, scene_state.spot_light_buffer);
  1577. if (r_spot_light_count) {
  1578. glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(LightData) * r_spot_light_count, scene_state.spot_lights);
  1579. }
  1580. glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_DIRECTIONAL_LIGHT_UNIFORM_LOCATION, scene_state.directional_light_buffer);
  1581. if (r_directional_light_count) {
  1582. glBufferData(GL_UNIFORM_BUFFER, sizeof(DirectionalLightData) * MAX_DIRECTIONAL_LIGHTS, scene_state.directional_lights, GL_STREAM_DRAW);
  1583. }
  1584. glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_POSITIONAL_SHADOW_UNIFORM_LOCATION, scene_state.positional_shadow_buffer);
  1585. if (num_positional_shadows) {
  1586. glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(ShadowData) * num_positional_shadows, scene_state.positional_shadows);
  1587. }
  1588. glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_DIRECTIONAL_SHADOW_UNIFORM_LOCATION, scene_state.directional_shadow_buffer);
  1589. if (r_directional_shadow_count) {
  1590. glBufferData(GL_UNIFORM_BUFFER, sizeof(DirectionalShadowData) * MAX_DIRECTIONAL_LIGHTS, scene_state.directional_shadows, GL_STREAM_DRAW);
  1591. }
  1592. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  1593. }
  1594. // Render shadows
  1595. void RasterizerSceneGLES3::_render_shadows(const RenderDataGLES3 *p_render_data, const Size2i &p_viewport_size) {
  1596. GLES3::LightStorage *light_storage = GLES3::LightStorage::get_singleton();
  1597. LocalVector<int> cube_shadows;
  1598. LocalVector<int> shadows;
  1599. LocalVector<int> directional_shadows;
  1600. float lod_distance_multiplier = p_render_data->cam_projection.get_lod_multiplier();
  1601. // Put lights into buckets for omni (cube shadows), directional, and spot.
  1602. {
  1603. for (int i = 0; i < p_render_data->render_shadow_count; i++) {
  1604. RID li = p_render_data->render_shadows[i].light;
  1605. RID base = light_storage->light_instance_get_base_light(li);
  1606. if (light_storage->light_get_type(base) == RS::LIGHT_DIRECTIONAL) {
  1607. directional_shadows.push_back(i);
  1608. } else if (light_storage->light_get_type(base) == RS::LIGHT_OMNI && light_storage->light_omni_get_shadow_mode(base) == RS::LIGHT_OMNI_SHADOW_CUBE) {
  1609. cube_shadows.push_back(i);
  1610. } else {
  1611. shadows.push_back(i);
  1612. }
  1613. }
  1614. if (directional_shadows.size()) {
  1615. light_storage->update_directional_shadow_atlas();
  1616. }
  1617. }
  1618. bool render_shadows = directional_shadows.size() || shadows.size() || cube_shadows.size();
  1619. if (render_shadows) {
  1620. RENDER_TIMESTAMP("Render Shadows");
  1621. // Render cubemap shadows.
  1622. for (const int &index : cube_shadows) {
  1623. _render_shadow_pass(p_render_data->render_shadows[index].light, p_render_data->shadow_atlas, p_render_data->render_shadows[index].pass, p_render_data->render_shadows[index].instances, lod_distance_multiplier, p_render_data->screen_mesh_lod_threshold, p_render_data->render_info, p_viewport_size, p_render_data->cam_transform);
  1624. }
  1625. // Render directional shadows.
  1626. for (uint32_t i = 0; i < directional_shadows.size(); i++) {
  1627. _render_shadow_pass(p_render_data->render_shadows[directional_shadows[i]].light, p_render_data->shadow_atlas, p_render_data->render_shadows[directional_shadows[i]].pass, p_render_data->render_shadows[directional_shadows[i]].instances, lod_distance_multiplier, p_render_data->screen_mesh_lod_threshold, p_render_data->render_info, p_viewport_size, p_render_data->cam_transform);
  1628. }
  1629. // Render positional shadows (Spotlight and Omnilight with dual-paraboloid).
  1630. for (uint32_t i = 0; i < shadows.size(); i++) {
  1631. _render_shadow_pass(p_render_data->render_shadows[shadows[i]].light, p_render_data->shadow_atlas, p_render_data->render_shadows[shadows[i]].pass, p_render_data->render_shadows[shadows[i]].instances, lod_distance_multiplier, p_render_data->screen_mesh_lod_threshold, p_render_data->render_info, p_viewport_size, p_render_data->cam_transform);
  1632. }
  1633. }
  1634. }
  1635. void RasterizerSceneGLES3::_render_shadow_pass(RID p_light, RID p_shadow_atlas, int p_pass, const PagedArray<RenderGeometryInstance *> &p_instances, float p_lod_distance_multiplier, float p_screen_mesh_lod_threshold, RenderingMethod::RenderInfo *p_render_info, const Size2i &p_viewport_size, const Transform3D &p_main_cam_transform) {
  1636. GLES3::LightStorage *light_storage = GLES3::LightStorage::get_singleton();
  1637. ERR_FAIL_COND(!light_storage->owns_light_instance(p_light));
  1638. RID base = light_storage->light_instance_get_base_light(p_light);
  1639. float zfar = 0.0;
  1640. bool use_pancake = false;
  1641. float shadow_bias = 0.0;
  1642. bool reverse_cull = false;
  1643. bool needs_clear = false;
  1644. Projection light_projection;
  1645. Transform3D light_transform;
  1646. GLuint shadow_fb = 0;
  1647. Rect2i atlas_rect;
  1648. if (light_storage->light_get_type(base) == RS::LIGHT_DIRECTIONAL) {
  1649. // Set pssm stuff.
  1650. uint64_t last_scene_shadow_pass = light_storage->light_instance_get_shadow_pass(p_light);
  1651. if (last_scene_shadow_pass != get_scene_pass()) {
  1652. light_storage->light_instance_set_directional_rect(p_light, light_storage->get_directional_shadow_rect());
  1653. light_storage->directional_shadow_increase_current_light();
  1654. light_storage->light_instance_set_shadow_pass(p_light, get_scene_pass());
  1655. }
  1656. atlas_rect = light_storage->light_instance_get_directional_rect(p_light);
  1657. if (light_storage->light_directional_get_shadow_mode(base) == RS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS) {
  1658. atlas_rect.size.width /= 2;
  1659. atlas_rect.size.height /= 2;
  1660. if (p_pass == 1) {
  1661. atlas_rect.position.x += atlas_rect.size.width;
  1662. } else if (p_pass == 2) {
  1663. atlas_rect.position.y += atlas_rect.size.height;
  1664. } else if (p_pass == 3) {
  1665. atlas_rect.position += atlas_rect.size;
  1666. }
  1667. } else if (light_storage->light_directional_get_shadow_mode(base) == RS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS) {
  1668. atlas_rect.size.height /= 2;
  1669. if (p_pass == 0) {
  1670. } else {
  1671. atlas_rect.position.y += atlas_rect.size.height;
  1672. }
  1673. }
  1674. use_pancake = light_storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_PANCAKE_SIZE) > 0;
  1675. light_projection = light_storage->light_instance_get_shadow_camera(p_light, p_pass);
  1676. light_transform = light_storage->light_instance_get_shadow_transform(p_light, p_pass);
  1677. float directional_shadow_size = light_storage->directional_shadow_get_size();
  1678. Rect2 atlas_rect_norm = atlas_rect;
  1679. atlas_rect_norm.position /= directional_shadow_size;
  1680. atlas_rect_norm.size /= directional_shadow_size;
  1681. light_storage->light_instance_set_directional_shadow_atlas_rect(p_light, p_pass, atlas_rect_norm);
  1682. zfar = RSG::light_storage->light_get_param(base, RS::LIGHT_PARAM_RANGE);
  1683. shadow_fb = light_storage->direction_shadow_get_fb();
  1684. reverse_cull = !light_storage->light_get_reverse_cull_face_mode(base);
  1685. float bias_scale = light_storage->light_instance_get_shadow_bias_scale(p_light, p_pass);
  1686. shadow_bias = light_storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_BIAS) / 100.0 * bias_scale;
  1687. } else {
  1688. // Set from shadow atlas.
  1689. ERR_FAIL_COND(!light_storage->owns_shadow_atlas(p_shadow_atlas));
  1690. ERR_FAIL_COND(!light_storage->shadow_atlas_owns_light_instance(p_shadow_atlas, p_light));
  1691. uint32_t key = light_storage->shadow_atlas_get_light_instance_key(p_shadow_atlas, p_light);
  1692. uint32_t quadrant = (key >> GLES3::LightStorage::QUADRANT_SHIFT) & 0x3;
  1693. uint32_t shadow = key & GLES3::LightStorage::SHADOW_INDEX_MASK;
  1694. ERR_FAIL_INDEX((int)shadow, light_storage->shadow_atlas_get_quadrant_shadows_length(p_shadow_atlas, quadrant));
  1695. int shadow_size = light_storage->shadow_atlas_get_quadrant_shadow_size(p_shadow_atlas, quadrant);
  1696. shadow_fb = light_storage->shadow_atlas_get_quadrant_shadow_fb(p_shadow_atlas, quadrant, shadow);
  1697. zfar = light_storage->light_get_param(base, RS::LIGHT_PARAM_RANGE);
  1698. reverse_cull = !light_storage->light_get_reverse_cull_face_mode(base);
  1699. if (light_storage->light_get_type(base) == RS::LIGHT_OMNI) {
  1700. if (light_storage->light_omni_get_shadow_mode(base) == RS::LIGHT_OMNI_SHADOW_CUBE) {
  1701. GLuint shadow_texture = light_storage->shadow_atlas_get_quadrant_shadow_texture(p_shadow_atlas, quadrant, shadow);
  1702. glBindFramebuffer(GL_FRAMEBUFFER, shadow_fb);
  1703. static GLenum cube_map_faces[6] = {
  1704. GL_TEXTURE_CUBE_MAP_POSITIVE_X,
  1705. GL_TEXTURE_CUBE_MAP_NEGATIVE_X,
  1706. // Flipped order for Y to match what the RD renderer expects
  1707. // (and thus what is given to us by the Rendering Server).
  1708. GL_TEXTURE_CUBE_MAP_NEGATIVE_Y,
  1709. GL_TEXTURE_CUBE_MAP_POSITIVE_Y,
  1710. GL_TEXTURE_CUBE_MAP_POSITIVE_Z,
  1711. GL_TEXTURE_CUBE_MAP_NEGATIVE_Z
  1712. };
  1713. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, cube_map_faces[p_pass], shadow_texture, 0);
  1714. light_projection = light_storage->light_instance_get_shadow_camera(p_light, p_pass);
  1715. light_transform = light_storage->light_instance_get_shadow_transform(p_light, p_pass);
  1716. shadow_size = shadow_size / 2;
  1717. } else {
  1718. ERR_FAIL_MSG("Dual paraboloid shadow mode not supported in the Compatibility renderer. Please use CubeMap shadow mode instead.");
  1719. }
  1720. shadow_bias = light_storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_BIAS);
  1721. } else if (light_storage->light_get_type(base) == RS::LIGHT_SPOT) {
  1722. light_projection = light_storage->light_instance_get_shadow_camera(p_light, 0);
  1723. light_transform = light_storage->light_instance_get_shadow_transform(p_light, 0);
  1724. shadow_bias = light_storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_BIAS) / 10.0;
  1725. // Prebake range into bias so we can scale based on distance easily.
  1726. shadow_bias *= light_storage->light_get_param(base, RS::LIGHT_PARAM_RANGE);
  1727. }
  1728. atlas_rect.size.x = shadow_size;
  1729. atlas_rect.size.y = shadow_size;
  1730. needs_clear = true;
  1731. }
  1732. RenderDataGLES3 render_data;
  1733. render_data.cam_projection = light_projection;
  1734. render_data.cam_transform = light_transform;
  1735. render_data.inv_cam_transform = light_transform.affine_inverse();
  1736. render_data.z_far = zfar; // Only used by OmniLights.
  1737. render_data.z_near = 0.0;
  1738. render_data.lod_distance_multiplier = p_lod_distance_multiplier;
  1739. render_data.main_cam_transform = p_main_cam_transform;
  1740. render_data.instances = &p_instances;
  1741. render_data.render_info = p_render_info;
  1742. _setup_environment(&render_data, true, p_viewport_size, false, Color(), use_pancake, shadow_bias);
  1743. if (get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_DISABLE_LOD) {
  1744. render_data.screen_mesh_lod_threshold = 0.0;
  1745. } else {
  1746. render_data.screen_mesh_lod_threshold = p_screen_mesh_lod_threshold;
  1747. }
  1748. _fill_render_list(RENDER_LIST_SECONDARY, &render_data, PASS_MODE_SHADOW);
  1749. render_list[RENDER_LIST_SECONDARY].sort_by_key();
  1750. glBindFramebuffer(GL_FRAMEBUFFER, shadow_fb);
  1751. glViewport(atlas_rect.position.x, atlas_rect.position.y, atlas_rect.size.x, atlas_rect.size.y);
  1752. GLuint global_buffer = GLES3::MaterialStorage::get_singleton()->global_shader_parameters_get_uniform_buffer();
  1753. glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_GLOBALS_UNIFORM_LOCATION, global_buffer);
  1754. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  1755. scene_state.reset_gl_state();
  1756. scene_state.enable_gl_depth_test(true);
  1757. scene_state.enable_gl_depth_draw(true);
  1758. glDepthFunc(GL_GREATER);
  1759. glColorMask(0, 0, 0, 0);
  1760. glDrawBuffers(0, nullptr);
  1761. RasterizerGLES3::clear_depth(0.0);
  1762. if (needs_clear) {
  1763. glClear(GL_DEPTH_BUFFER_BIT);
  1764. }
  1765. uint64_t spec_constant_base_flags = SceneShaderGLES3::DISABLE_LIGHTMAP |
  1766. SceneShaderGLES3::DISABLE_LIGHT_DIRECTIONAL |
  1767. SceneShaderGLES3::DISABLE_LIGHT_OMNI |
  1768. SceneShaderGLES3::DISABLE_LIGHT_SPOT |
  1769. SceneShaderGLES3::DISABLE_FOG |
  1770. SceneShaderGLES3::RENDER_SHADOWS;
  1771. if (light_storage->light_get_type(base) == RS::LIGHT_OMNI) {
  1772. spec_constant_base_flags |= SceneShaderGLES3::RENDER_SHADOWS_LINEAR;
  1773. }
  1774. RenderListParameters render_list_params(render_list[RENDER_LIST_SECONDARY].elements.ptr(), render_list[RENDER_LIST_SECONDARY].elements.size(), reverse_cull, spec_constant_base_flags, false);
  1775. _render_list_template<PASS_MODE_SHADOW>(&render_list_params, &render_data, 0, render_list[RENDER_LIST_SECONDARY].elements.size());
  1776. glColorMask(1, 1, 1, 1);
  1777. scene_state.enable_gl_depth_test(false);
  1778. scene_state.enable_gl_depth_draw(true);
  1779. glDisable(GL_CULL_FACE);
  1780. scene_state.cull_mode = RS::CULL_MODE_DISABLED;
  1781. glBindFramebuffer(GL_FRAMEBUFFER, GLES3::TextureStorage::system_fbo);
  1782. }
  1783. void RasterizerSceneGLES3::render_scene(const Ref<RenderSceneBuffers> &p_render_buffers, const CameraData *p_camera_data, const CameraData *p_prev_camera_data, const PagedArray<RenderGeometryInstance *> &p_instances, const PagedArray<RID> &p_lights, const PagedArray<RID> &p_reflection_probes, const PagedArray<RID> &p_voxel_gi_instances, const PagedArray<RID> &p_decals, const PagedArray<RID> &p_lightmaps, const PagedArray<RID> &p_fog_volumes, RID p_environment, RID p_camera_attributes, RID p_compositor, RID p_shadow_atlas, RID p_occluder_debug_tex, RID p_reflection_atlas, RID p_reflection_probe, int p_reflection_probe_pass, float p_screen_mesh_lod_threshold, const RenderShadowData *p_render_shadows, int p_render_shadow_count, const RenderSDFGIData *p_render_sdfgi_regions, int p_render_sdfgi_region_count, const RenderSDFGIUpdateData *p_sdfgi_update_data, RenderingMethod::RenderInfo *r_render_info) {
  1784. GLES3::TextureStorage *texture_storage = GLES3::TextureStorage::get_singleton();
  1785. GLES3::Config *config = GLES3::Config::get_singleton();
  1786. RENDER_TIMESTAMP("Setup 3D Scene");
  1787. bool apply_color_adjustments_in_post = false;
  1788. bool is_reflection_probe = p_reflection_probe.is_valid();
  1789. Ref<RenderSceneBuffersGLES3> rb = p_render_buffers;
  1790. ERR_FAIL_COND(rb.is_null());
  1791. if (rb->get_scaling_3d_mode() != RS::VIEWPORT_SCALING_3D_MODE_OFF) {
  1792. // If we're scaling, we apply tonemapping etc. in post, so disable it during rendering
  1793. apply_color_adjustments_in_post = true;
  1794. }
  1795. GLES3::RenderTarget *rt = nullptr; // No render target for reflection probe
  1796. if (!is_reflection_probe) {
  1797. rt = texture_storage->get_render_target(rb->render_target);
  1798. ERR_FAIL_NULL(rt);
  1799. }
  1800. bool glow_enabled = false;
  1801. if (p_environment.is_valid()) {
  1802. glow_enabled = environment_get_glow_enabled(p_environment);
  1803. if (glow_enabled) {
  1804. // If glow is enabled, we apply tonemapping etc. in post, so disable it during rendering
  1805. apply_color_adjustments_in_post = true;
  1806. }
  1807. }
  1808. // Assign render data
  1809. // Use the format from rendererRD
  1810. RenderDataGLES3 render_data;
  1811. {
  1812. render_data.render_buffers = rb;
  1813. if (rt) {
  1814. render_data.transparent_bg = rt->is_transparent;
  1815. render_data.render_region = rt->render_region;
  1816. }
  1817. // Our first camera is used by default
  1818. render_data.cam_transform = p_camera_data->main_transform;
  1819. render_data.inv_cam_transform = render_data.cam_transform.affine_inverse();
  1820. render_data.cam_projection = p_camera_data->main_projection;
  1821. render_data.cam_orthogonal = p_camera_data->is_orthogonal;
  1822. render_data.cam_frustum = p_camera_data->is_frustum;
  1823. render_data.camera_visible_layers = p_camera_data->visible_layers;
  1824. render_data.main_cam_transform = p_camera_data->main_transform;
  1825. render_data.view_count = p_camera_data->view_count;
  1826. for (uint32_t v = 0; v < p_camera_data->view_count; v++) {
  1827. render_data.view_eye_offset[v] = p_camera_data->view_offset[v].origin;
  1828. render_data.view_projection[v] = p_camera_data->view_projection[v];
  1829. }
  1830. render_data.z_near = p_camera_data->main_projection.get_z_near();
  1831. render_data.z_far = p_camera_data->main_projection.get_z_far();
  1832. render_data.instances = &p_instances;
  1833. render_data.lights = &p_lights;
  1834. render_data.reflection_probes = &p_reflection_probes;
  1835. render_data.environment = p_environment;
  1836. render_data.camera_attributes = p_camera_attributes;
  1837. render_data.shadow_atlas = p_shadow_atlas;
  1838. render_data.reflection_probe = p_reflection_probe;
  1839. render_data.reflection_probe_pass = p_reflection_probe_pass;
  1840. // this should be the same for all cameras..
  1841. render_data.lod_distance_multiplier = p_camera_data->main_projection.get_lod_multiplier();
  1842. if (rt != nullptr && rt->color_type == GL_UNSIGNED_INT_2_10_10_10_REV && glow_enabled) {
  1843. // As our output is in sRGB and we're using 10bit color space, we can fake a little HDR to do glow...
  1844. render_data.luminance_multiplier = 0.25;
  1845. } else {
  1846. render_data.luminance_multiplier = 1.0;
  1847. }
  1848. if (get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_DISABLE_LOD) {
  1849. render_data.screen_mesh_lod_threshold = 0.0;
  1850. } else {
  1851. render_data.screen_mesh_lod_threshold = p_screen_mesh_lod_threshold;
  1852. }
  1853. render_data.render_info = r_render_info;
  1854. render_data.render_shadows = p_render_shadows;
  1855. render_data.render_shadow_count = p_render_shadow_count;
  1856. }
  1857. PagedArray<RID> empty;
  1858. if (get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_UNSHADED) {
  1859. render_data.lights = &empty;
  1860. render_data.reflection_probes = &empty;
  1861. }
  1862. bool reverse_cull = render_data.cam_transform.basis.determinant() < 0;
  1863. ///////////
  1864. // Fill Light lists here
  1865. //////////
  1866. GLuint global_buffer = GLES3::MaterialStorage::get_singleton()->global_shader_parameters_get_uniform_buffer();
  1867. glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_GLOBALS_UNIFORM_LOCATION, global_buffer);
  1868. Color clear_color;
  1869. if (!is_reflection_probe && rb->render_target.is_valid()) {
  1870. clear_color = texture_storage->render_target_get_clear_request_color(rb->render_target);
  1871. } else {
  1872. clear_color = texture_storage->get_default_clear_color();
  1873. }
  1874. bool fb_cleared = false;
  1875. Size2i screen_size = rb->internal_size;
  1876. bool use_wireframe = get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_WIREFRAME;
  1877. SceneState::TonemapUBO tonemap_ubo;
  1878. if (render_data.environment.is_valid()) {
  1879. bool use_bcs = environment_get_adjustments_enabled(render_data.environment);
  1880. if (use_bcs) {
  1881. apply_color_adjustments_in_post = true;
  1882. }
  1883. tonemap_ubo.exposure = environment_get_exposure(render_data.environment);
  1884. tonemap_ubo.white = environment_get_white(render_data.environment);
  1885. tonemap_ubo.tonemapper = int32_t(environment_get_tone_mapper(render_data.environment));
  1886. tonemap_ubo.brightness = environment_get_adjustments_brightness(render_data.environment);
  1887. tonemap_ubo.contrast = environment_get_adjustments_contrast(render_data.environment);
  1888. tonemap_ubo.saturation = environment_get_adjustments_saturation(render_data.environment);
  1889. }
  1890. if (scene_state.tonemap_buffer == 0) {
  1891. // Only create if using 3D
  1892. glGenBuffers(1, &scene_state.tonemap_buffer);
  1893. glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_TONEMAP_UNIFORM_LOCATION, scene_state.tonemap_buffer);
  1894. GLES3::Utilities::get_singleton()->buffer_allocate_data(GL_UNIFORM_BUFFER, scene_state.tonemap_buffer, sizeof(SceneState::TonemapUBO), &tonemap_ubo, GL_STREAM_DRAW, "Tonemap UBO");
  1895. } else {
  1896. glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_TONEMAP_UNIFORM_LOCATION, scene_state.tonemap_buffer);
  1897. glBufferData(GL_UNIFORM_BUFFER, sizeof(SceneState::TonemapUBO), &tonemap_ubo, GL_STREAM_DRAW);
  1898. }
  1899. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  1900. scene_state.ubo.emissive_exposure_normalization = -1.0; // Use default exposure normalization.
  1901. bool flip_y = !is_reflection_probe;
  1902. if (rt && rt->overridden.color.is_valid()) {
  1903. // If we've overridden the render target's color texture, then don't render upside down.
  1904. // We're probably rendering directly to an XR device.
  1905. flip_y = false;
  1906. }
  1907. if (!flip_y) {
  1908. // If we're rendering right-side up, then we need to change the winding order.
  1909. glFrontFace(GL_CW);
  1910. }
  1911. _render_shadows(&render_data, screen_size);
  1912. _setup_lights(&render_data, true, render_data.directional_light_count, render_data.omni_light_count, render_data.spot_light_count, render_data.directional_shadow_count);
  1913. _setup_environment(&render_data, is_reflection_probe, screen_size, flip_y, clear_color, false);
  1914. _fill_render_list(RENDER_LIST_OPAQUE, &render_data, PASS_MODE_COLOR);
  1915. render_list[RENDER_LIST_OPAQUE].sort_by_key();
  1916. render_list[RENDER_LIST_ALPHA].sort_by_reverse_depth_and_priority();
  1917. bool draw_sky = false;
  1918. bool draw_sky_fog_only = false;
  1919. bool keep_color = false;
  1920. bool draw_canvas = false;
  1921. bool draw_feed = false;
  1922. float sky_energy_multiplier = 1.0;
  1923. int camera_feed_id = -1;
  1924. if (unlikely(get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_OVERDRAW)) {
  1925. clear_color = Color(0, 0, 0, 1); //in overdraw mode, BG should always be black
  1926. } else if (render_data.environment.is_valid()) {
  1927. RS::EnvironmentBG bg_mode = environment_get_background(render_data.environment);
  1928. float bg_energy_multiplier = environment_get_bg_energy_multiplier(render_data.environment);
  1929. bg_energy_multiplier *= environment_get_bg_intensity(render_data.environment);
  1930. RS::EnvironmentReflectionSource reflection_source = environment_get_reflection_source(render_data.environment);
  1931. RS::EnvironmentAmbientSource ambient_source = environment_get_ambient_source(render_data.environment);
  1932. if (render_data.camera_attributes.is_valid()) {
  1933. bg_energy_multiplier *= RSG::camera_attributes->camera_attributes_get_exposure_normalization_factor(render_data.camera_attributes);
  1934. }
  1935. switch (bg_mode) {
  1936. case RS::ENV_BG_CLEAR_COLOR: {
  1937. clear_color.r *= bg_energy_multiplier;
  1938. clear_color.g *= bg_energy_multiplier;
  1939. clear_color.b *= bg_energy_multiplier;
  1940. if (!render_data.transparent_bg && environment_get_fog_enabled(render_data.environment)) {
  1941. draw_sky_fog_only = true;
  1942. GLES3::MaterialStorage::get_singleton()->material_set_param(sky_globals.fog_material, "clear_color", Variant(clear_color));
  1943. }
  1944. } break;
  1945. case RS::ENV_BG_COLOR: {
  1946. clear_color = environment_get_bg_color(render_data.environment);
  1947. clear_color.r *= bg_energy_multiplier;
  1948. clear_color.g *= bg_energy_multiplier;
  1949. clear_color.b *= bg_energy_multiplier;
  1950. if (!render_data.transparent_bg && environment_get_fog_enabled(render_data.environment)) {
  1951. draw_sky_fog_only = true;
  1952. GLES3::MaterialStorage::get_singleton()->material_set_param(sky_globals.fog_material, "clear_color", Variant(clear_color));
  1953. }
  1954. } break;
  1955. case RS::ENV_BG_SKY: {
  1956. draw_sky = !render_data.transparent_bg;
  1957. } break;
  1958. case RS::ENV_BG_CANVAS: {
  1959. draw_canvas = true;
  1960. } break;
  1961. case RS::ENV_BG_KEEP: {
  1962. keep_color = true;
  1963. } break;
  1964. case RS::ENV_BG_CAMERA_FEED: {
  1965. camera_feed_id = environment_get_camera_feed_id(render_data.environment);
  1966. draw_feed = true;
  1967. keep_color = true;
  1968. } break;
  1969. default: {
  1970. }
  1971. }
  1972. bool sky_reflections = reflection_source == RS::ENV_REFLECTION_SOURCE_SKY;
  1973. sky_reflections |= reflection_source == RS::ENV_REFLECTION_SOURCE_BG && bg_mode == RS::ENV_BG_SKY;
  1974. bool sky_ambient = ambient_source == RS::ENV_AMBIENT_SOURCE_SKY;
  1975. sky_ambient |= ambient_source == RS::ENV_AMBIENT_SOURCE_BG && bg_mode == RS::ENV_BG_SKY;
  1976. // setup sky if used for ambient, reflections, or background
  1977. if (draw_sky || draw_sky_fog_only || sky_reflections || sky_ambient) {
  1978. RENDER_TIMESTAMP("Setup Sky");
  1979. Projection projection = render_data.cam_projection;
  1980. if (is_reflection_probe) {
  1981. Projection correction;
  1982. correction.set_depth_correction(true, true, false);
  1983. projection = correction * render_data.cam_projection;
  1984. }
  1985. sky_energy_multiplier *= bg_energy_multiplier;
  1986. _setup_sky(&render_data, *render_data.lights, projection, render_data.cam_transform, screen_size);
  1987. if (environment_get_sky(render_data.environment).is_valid()) {
  1988. if (sky_reflections || sky_ambient) {
  1989. _update_sky_radiance(render_data.environment, projection, render_data.cam_transform, sky_energy_multiplier);
  1990. }
  1991. } else {
  1992. // do not try to draw sky if invalid
  1993. draw_sky = false;
  1994. }
  1995. }
  1996. }
  1997. GLuint fbo = 0;
  1998. if (is_reflection_probe) {
  1999. fbo = GLES3::LightStorage::get_singleton()->reflection_probe_instance_get_framebuffer(render_data.reflection_probe, render_data.reflection_probe_pass);
  2000. } else {
  2001. rb->set_apply_color_adjustments_in_post(apply_color_adjustments_in_post);
  2002. fbo = rb->get_render_fbo();
  2003. }
  2004. glBindFramebuffer(GL_FRAMEBUFFER, fbo);
  2005. glViewport(0, 0, rb->internal_size.x, rb->internal_size.y);
  2006. scene_state.reset_gl_state();
  2007. // Do depth prepass if it's explicitly enabled
  2008. bool use_depth_prepass = config->use_depth_prepass;
  2009. // Don't do depth prepass we are rendering overdraw
  2010. use_depth_prepass = use_depth_prepass && get_debug_draw_mode() != RS::VIEWPORT_DEBUG_DRAW_OVERDRAW;
  2011. if (use_depth_prepass) {
  2012. RENDER_TIMESTAMP("Depth Prepass");
  2013. //pre z pass
  2014. if (render_data.render_region != Rect2i()) {
  2015. glViewport(render_data.render_region.position.x, render_data.render_region.position.y, render_data.render_region.size.width, render_data.render_region.size.height);
  2016. }
  2017. scene_state.enable_gl_depth_test(true);
  2018. scene_state.enable_gl_depth_draw(true);
  2019. scene_state.enable_gl_blend(false);
  2020. glDepthFunc(GL_GEQUAL);
  2021. scene_state.enable_gl_scissor_test(false);
  2022. glColorMask(0, 0, 0, 0);
  2023. RasterizerGLES3::clear_depth(0.0);
  2024. glClear(GL_DEPTH_BUFFER_BIT);
  2025. // Some desktop GL implementations fall apart when using Multiview with GL_NONE.
  2026. GLuint db = p_camera_data->view_count > 1 ? GL_COLOR_ATTACHMENT0 : GL_NONE;
  2027. glDrawBuffers(1, &db);
  2028. uint64_t spec_constant = SceneShaderGLES3::DISABLE_FOG | SceneShaderGLES3::DISABLE_LIGHT_DIRECTIONAL |
  2029. SceneShaderGLES3::DISABLE_LIGHTMAP | SceneShaderGLES3::DISABLE_LIGHT_OMNI |
  2030. SceneShaderGLES3::DISABLE_LIGHT_SPOT;
  2031. RenderListParameters render_list_params(render_list[RENDER_LIST_OPAQUE].elements.ptr(), render_list[RENDER_LIST_OPAQUE].elements.size(), reverse_cull, spec_constant, use_wireframe);
  2032. _render_list_template<PASS_MODE_DEPTH>(&render_list_params, &render_data, 0, render_list[RENDER_LIST_OPAQUE].elements.size());
  2033. glColorMask(1, 1, 1, 1);
  2034. fb_cleared = true;
  2035. scene_state.used_depth_prepass = true;
  2036. } else {
  2037. scene_state.used_depth_prepass = false;
  2038. }
  2039. glBlendEquation(GL_FUNC_ADD);
  2040. if (render_data.transparent_bg) {
  2041. glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
  2042. scene_state.enable_gl_blend(true);
  2043. } else {
  2044. glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ZERO, GL_ONE);
  2045. scene_state.enable_gl_blend(false);
  2046. }
  2047. scene_state.current_blend_mode = GLES3::SceneShaderData::BLEND_MODE_MIX;
  2048. scene_state.enable_gl_scissor_test(false);
  2049. scene_state.enable_gl_depth_test(true);
  2050. scene_state.enable_gl_depth_draw(true);
  2051. glDepthFunc(GL_GEQUAL);
  2052. {
  2053. GLuint db = GL_COLOR_ATTACHMENT0;
  2054. glDrawBuffers(1, &db);
  2055. }
  2056. if (!fb_cleared) {
  2057. RasterizerGLES3::clear_depth(0.0);
  2058. glClear(GL_DEPTH_BUFFER_BIT);
  2059. }
  2060. // Need to clear framebuffer unless:
  2061. // a) We explicitly request not to (i.e. ENV_BG_KEEP).
  2062. // b) We are rendering to a non-intermediate framebuffer with ENV_BG_CANVAS (shared between 2D and 3D).
  2063. if (!keep_color && (!draw_canvas || fbo != rt->fbo)) {
  2064. clear_color.a = render_data.transparent_bg ? 0.0f : 1.0f;
  2065. glClearBufferfv(GL_COLOR, 0, clear_color.components);
  2066. }
  2067. if ((keep_color || draw_canvas) && fbo != rt->fbo) {
  2068. // Need to copy our current contents to our intermediate/MSAA buffer
  2069. GLES3::CopyEffects *copy_effects = GLES3::CopyEffects::get_singleton();
  2070. scene_state.enable_gl_depth_test(false);
  2071. scene_state.enable_gl_depth_draw(false);
  2072. glActiveTexture(GL_TEXTURE0);
  2073. glBindTexture(rt->view_count > 1 ? GL_TEXTURE_2D_ARRAY : GL_TEXTURE_2D, rt->color);
  2074. copy_effects->copy_screen(render_data.luminance_multiplier);
  2075. scene_state.enable_gl_depth_test(true);
  2076. scene_state.enable_gl_depth_draw(true);
  2077. }
  2078. RENDER_TIMESTAMP("Render Opaque Pass");
  2079. uint64_t spec_constant_base_flags = 0;
  2080. if (render_data.render_region != Rect2i()) {
  2081. glViewport(render_data.render_region.position.x, render_data.render_region.position.y, render_data.render_region.size.width, render_data.render_region.size.height);
  2082. }
  2083. {
  2084. // Specialization Constants that apply for entire rendering pass.
  2085. if (render_data.directional_light_count == 0) {
  2086. spec_constant_base_flags |= SceneShaderGLES3::DISABLE_LIGHT_DIRECTIONAL;
  2087. }
  2088. if (render_data.environment.is_null() || (render_data.environment.is_valid() && !environment_get_fog_enabled(render_data.environment))) {
  2089. spec_constant_base_flags |= SceneShaderGLES3::DISABLE_FOG;
  2090. }
  2091. if (render_data.environment.is_valid() && environment_get_fog_mode(render_data.environment) == RS::EnvironmentFogMode::ENV_FOG_MODE_DEPTH) {
  2092. spec_constant_base_flags |= SceneShaderGLES3::USE_DEPTH_FOG;
  2093. }
  2094. if (!apply_color_adjustments_in_post) {
  2095. spec_constant_base_flags |= SceneShaderGLES3::APPLY_TONEMAPPING;
  2096. }
  2097. }
  2098. if (draw_feed && camera_feed_id > -1) {
  2099. RENDER_TIMESTAMP("Render Camera feed");
  2100. scene_state.enable_gl_depth_draw(false);
  2101. scene_state.enable_gl_depth_test(false);
  2102. scene_state.enable_gl_blend(false);
  2103. scene_state.set_gl_cull_mode(RS::CULL_MODE_BACK);
  2104. Ref<CameraFeed> feed = CameraServer::get_singleton()->get_feed_by_id(camera_feed_id);
  2105. if (feed.is_valid()) {
  2106. RID camera_YCBCR = feed->get_texture(CameraServer::FEED_YCBCR_IMAGE);
  2107. GLES3::TextureStorage::get_singleton()->texture_bind(camera_YCBCR, 0);
  2108. GLES3::FeedEffects *feed_effects = GLES3::FeedEffects::get_singleton();
  2109. feed_effects->draw();
  2110. }
  2111. scene_state.enable_gl_depth_draw(true);
  2112. scene_state.enable_gl_depth_test(true);
  2113. scene_state.enable_gl_blend(true);
  2114. }
  2115. // Render Opaque Objects.
  2116. RenderListParameters render_list_params(render_list[RENDER_LIST_OPAQUE].elements.ptr(), render_list[RENDER_LIST_OPAQUE].elements.size(), reverse_cull, spec_constant_base_flags, use_wireframe);
  2117. _render_list_template<PASS_MODE_COLOR>(&render_list_params, &render_data, 0, render_list[RENDER_LIST_OPAQUE].elements.size());
  2118. scene_state.enable_gl_depth_draw(false);
  2119. if (draw_sky || draw_sky_fog_only) {
  2120. RENDER_TIMESTAMP("Render Sky");
  2121. scene_state.enable_gl_depth_test(true);
  2122. scene_state.enable_gl_blend(false);
  2123. scene_state.set_gl_cull_mode(RS::CULL_MODE_BACK);
  2124. Transform3D transform = render_data.cam_transform;
  2125. Projection projection = render_data.cam_projection;
  2126. if (is_reflection_probe) {
  2127. Projection correction;
  2128. correction.columns[1][1] = -1.0;
  2129. projection = correction * render_data.cam_projection;
  2130. } else if (render_data.cam_frustum) {
  2131. // Sky is drawn upside down, the frustum offset doesn't know the image is upside down so needs a flip.
  2132. projection[2].y = -projection[2].y;
  2133. }
  2134. _draw_sky(render_data.environment, projection, transform, sky_energy_multiplier, render_data.luminance_multiplier, p_camera_data->view_count > 1, flip_y, apply_color_adjustments_in_post);
  2135. }
  2136. if (rt && (scene_state.used_screen_texture || scene_state.used_depth_texture)) {
  2137. Size2i size;
  2138. GLuint backbuffer_fbo = 0;
  2139. GLuint backbuffer = 0;
  2140. GLuint backbuffer_depth = 0;
  2141. if (rb->get_scaling_3d_mode() == RS::VIEWPORT_SCALING_3D_MODE_OFF) {
  2142. texture_storage->check_backbuffer(rt, scene_state.used_screen_texture, scene_state.used_depth_texture); // note, badly names, this just allocates!
  2143. size = rt->size;
  2144. backbuffer_fbo = rt->backbuffer_fbo;
  2145. backbuffer = rt->backbuffer;
  2146. backbuffer_depth = rt->backbuffer_depth;
  2147. } else {
  2148. rb->check_backbuffer(scene_state.used_screen_texture, scene_state.used_depth_texture);
  2149. size = rb->get_internal_size();
  2150. backbuffer_fbo = rb->get_backbuffer_fbo();
  2151. backbuffer = rb->get_backbuffer();
  2152. backbuffer_depth = rb->get_backbuffer_depth();
  2153. }
  2154. if (backbuffer_fbo != 0) {
  2155. glBindFramebuffer(GL_READ_FRAMEBUFFER, fbo);
  2156. glReadBuffer(GL_COLOR_ATTACHMENT0);
  2157. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, backbuffer_fbo);
  2158. if (scene_state.used_screen_texture) {
  2159. glBlitFramebuffer(0, 0, size.x, size.y,
  2160. 0, 0, size.x, size.y,
  2161. GL_COLOR_BUFFER_BIT, GL_NEAREST);
  2162. glActiveTexture(GL_TEXTURE0 + config->max_texture_image_units - 6);
  2163. glBindTexture(GL_TEXTURE_2D, backbuffer);
  2164. }
  2165. if (scene_state.used_depth_texture) {
  2166. glBlitFramebuffer(0, 0, size.x, size.y,
  2167. 0, 0, size.x, size.y,
  2168. GL_DEPTH_BUFFER_BIT, GL_NEAREST);
  2169. glActiveTexture(GL_TEXTURE0 + config->max_texture_image_units - 7);
  2170. glBindTexture(GL_TEXTURE_2D, backbuffer_depth);
  2171. }
  2172. }
  2173. // Bound framebuffer may have changed, so change it back
  2174. glBindFramebuffer(GL_FRAMEBUFFER, fbo);
  2175. }
  2176. RENDER_TIMESTAMP("Render 3D Transparent Pass");
  2177. scene_state.enable_gl_blend(true);
  2178. //Render transparent pass
  2179. RenderListParameters render_list_params_alpha(render_list[RENDER_LIST_ALPHA].elements.ptr(), render_list[RENDER_LIST_ALPHA].elements.size(), reverse_cull, spec_constant_base_flags, use_wireframe);
  2180. _render_list_template<PASS_MODE_COLOR_TRANSPARENT>(&render_list_params_alpha, &render_data, 0, render_list[RENDER_LIST_ALPHA].elements.size(), true);
  2181. if (!flip_y) {
  2182. // Restore the default winding order.
  2183. glFrontFace(GL_CCW);
  2184. }
  2185. if (!is_reflection_probe && rb.is_valid()) {
  2186. _render_buffers_debug_draw(rb, p_shadow_atlas, fbo);
  2187. }
  2188. // Reset stuff that may trip up the next process.
  2189. scene_state.reset_gl_state();
  2190. glUseProgram(0);
  2191. if (!is_reflection_probe) {
  2192. _render_post_processing(&render_data);
  2193. texture_storage->render_target_disable_clear_request(rb->render_target);
  2194. }
  2195. glActiveTexture(GL_TEXTURE0);
  2196. }
  2197. void RasterizerSceneGLES3::_render_post_processing(const RenderDataGLES3 *p_render_data) {
  2198. GLES3::TextureStorage *texture_storage = GLES3::TextureStorage::get_singleton();
  2199. GLES3::Glow *glow = GLES3::Glow::get_singleton();
  2200. GLES3::PostEffects *post_effects = GLES3::PostEffects::get_singleton();
  2201. Ref<RenderSceneBuffersGLES3> rb = p_render_data->render_buffers;
  2202. ERR_FAIL_COND(rb.is_null());
  2203. RID render_target = rb->get_render_target();
  2204. Size2i internal_size = rb->get_internal_size();
  2205. Size2i target_size = rb->get_target_size();
  2206. uint32_t view_count = rb->get_view_count();
  2207. // bool msaa2d_needs_resolve = texture_storage->render_target_get_msaa(render_target) != RS::VIEWPORT_MSAA_DISABLED && !GLES3::Config::get_singleton()->rt_msaa_supported;
  2208. bool msaa3d_needs_resolve = rb->get_msaa_needs_resolve();
  2209. GLuint fbo_msaa_3d = rb->get_msaa3d_fbo();
  2210. GLuint fbo_int = rb->get_internal_fbo();
  2211. GLuint fbo_rt = texture_storage->render_target_get_fbo(render_target); // TODO if MSAA 2D is enabled and we're not using rt_msaa, get 2D render target here.
  2212. // Check if we have glow enabled and if so, check if our buffers were allocated
  2213. bool glow_enabled = false;
  2214. float glow_intensity = 1.0;
  2215. float glow_bloom = 0.0;
  2216. float glow_hdr_bleed_threshold = 1.0;
  2217. float glow_hdr_bleed_scale = 2.0;
  2218. float glow_hdr_luminance_cap = 12.0;
  2219. if (p_render_data->environment.is_valid()) {
  2220. glow_enabled = environment_get_glow_enabled(p_render_data->environment);
  2221. glow_intensity = environment_get_glow_intensity(p_render_data->environment);
  2222. glow_bloom = environment_get_glow_bloom(p_render_data->environment);
  2223. glow_hdr_bleed_threshold = environment_get_glow_hdr_bleed_threshold(p_render_data->environment);
  2224. glow_hdr_bleed_scale = environment_get_glow_hdr_bleed_scale(p_render_data->environment);
  2225. glow_hdr_luminance_cap = environment_get_glow_hdr_luminance_cap(p_render_data->environment);
  2226. }
  2227. if (glow_enabled) {
  2228. rb->check_glow_buffers();
  2229. }
  2230. uint64_t bcs_spec_constants = 0;
  2231. if (p_render_data->environment.is_valid()) {
  2232. bool use_bcs = environment_get_adjustments_enabled(p_render_data->environment);
  2233. RID color_correction_texture = environment_get_color_correction(p_render_data->environment);
  2234. if (use_bcs) {
  2235. bcs_spec_constants |= PostShaderGLES3::USE_BCS;
  2236. if (color_correction_texture.is_valid()) {
  2237. bcs_spec_constants |= PostShaderGLES3::USE_COLOR_CORRECTION;
  2238. bool use_1d_lut = environment_get_use_1d_color_correction(p_render_data->environment);
  2239. GLenum texture_target = GL_TEXTURE_3D;
  2240. if (use_1d_lut) {
  2241. bcs_spec_constants |= PostShaderGLES3::USE_1D_LUT;
  2242. texture_target = GL_TEXTURE_2D;
  2243. }
  2244. glActiveTexture(GL_TEXTURE2);
  2245. glBindTexture(texture_target, texture_storage->texture_get_texid(color_correction_texture));
  2246. glTexParameteri(texture_target, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  2247. glTexParameteri(texture_target, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  2248. glTexParameteri(texture_target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  2249. glTexParameteri(texture_target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  2250. glTexParameteri(texture_target, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
  2251. }
  2252. }
  2253. }
  2254. if (view_count == 1) {
  2255. // Resolve if needed.
  2256. if (fbo_msaa_3d != 0 && msaa3d_needs_resolve) {
  2257. // We can use blit to copy things over
  2258. glBindFramebuffer(GL_READ_FRAMEBUFFER, fbo_msaa_3d);
  2259. if (fbo_int != 0) {
  2260. // We can't combine resolve and scaling, so resolve into our internal buffer
  2261. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo_int);
  2262. } else {
  2263. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo_rt);
  2264. }
  2265. glBlitFramebuffer(0, 0, internal_size.x, internal_size.y, 0, 0, internal_size.x, internal_size.y, GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, GL_NEAREST);
  2266. }
  2267. // Rendered to intermediate buffer, must copy to our render target
  2268. if (fbo_int != 0) {
  2269. // Apply glow/bloom if requested? then populate our glow buffers
  2270. GLuint color = fbo_int != 0 ? rb->get_internal_color() : texture_storage->render_target_get_color(render_target);
  2271. const GLES3::Glow::GLOWLEVEL *glow_buffers = nullptr;
  2272. if (glow_enabled) {
  2273. glow_buffers = rb->get_glow_buffers();
  2274. glow->set_luminance_multiplier(p_render_data->luminance_multiplier);
  2275. glow->set_intensity(glow_intensity);
  2276. glow->set_glow_bloom(glow_bloom);
  2277. glow->set_glow_hdr_bleed_threshold(glow_hdr_bleed_threshold);
  2278. glow->set_glow_hdr_bleed_scale(glow_hdr_bleed_scale);
  2279. glow->set_glow_hdr_luminance_cap(glow_hdr_luminance_cap);
  2280. glow->process_glow(color, internal_size, glow_buffers);
  2281. }
  2282. // Copy color buffer
  2283. post_effects->post_copy(fbo_rt, target_size, color, internal_size, p_render_data->luminance_multiplier, glow_buffers, glow_intensity, 0, false, bcs_spec_constants);
  2284. // Copy depth buffer
  2285. glBindFramebuffer(GL_READ_FRAMEBUFFER, fbo_int);
  2286. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo_rt);
  2287. glBlitFramebuffer(0, 0, internal_size.x, internal_size.y, 0, 0, target_size.x, target_size.y, GL_DEPTH_BUFFER_BIT, GL_NEAREST);
  2288. }
  2289. glBindFramebuffer(GL_FRAMEBUFFER, fbo_rt);
  2290. } else if ((fbo_msaa_3d != 0 && msaa3d_needs_resolve) || (fbo_int != 0)) {
  2291. // TODO investigate if it's smarter to cache these FBOs
  2292. GLuint fbos[3]; // read, write and post
  2293. glGenFramebuffers(3, fbos);
  2294. // Resolve if needed.
  2295. if (fbo_msaa_3d != 0 && msaa3d_needs_resolve) {
  2296. GLuint read_color = rb->get_msaa3d_color();
  2297. GLuint read_depth = rb->get_msaa3d_depth();
  2298. GLuint write_color = 0;
  2299. GLuint write_depth = 0;
  2300. if (fbo_int != 0) {
  2301. write_color = rb->get_internal_color();
  2302. write_depth = rb->get_internal_depth();
  2303. } else {
  2304. write_color = texture_storage->render_target_get_color(render_target);
  2305. write_depth = texture_storage->render_target_get_depth(render_target);
  2306. }
  2307. glBindFramebuffer(GL_READ_FRAMEBUFFER, fbos[0]);
  2308. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbos[1]);
  2309. for (uint32_t v = 0; v < view_count; v++) {
  2310. glFramebufferTextureLayer(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, read_color, 0, v);
  2311. glFramebufferTextureLayer(GL_READ_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, read_depth, 0, v);
  2312. glFramebufferTextureLayer(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, write_color, 0, v);
  2313. glFramebufferTextureLayer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, write_depth, 0, v);
  2314. glBlitFramebuffer(0, 0, internal_size.x, internal_size.y, 0, 0, internal_size.x, internal_size.y, GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, GL_NEAREST);
  2315. }
  2316. }
  2317. // Rendered to intermediate buffer, must copy to our render target
  2318. if (fbo_int != 0) {
  2319. // Apply glow/bloom if requested? then populate our glow buffers
  2320. const GLES3::Glow::GLOWLEVEL *glow_buffers = nullptr;
  2321. GLuint source_color = fbo_int != 0 ? rb->get_internal_color() : texture_storage->render_target_get_color(render_target);
  2322. if (glow_enabled) {
  2323. glow_buffers = rb->get_glow_buffers();
  2324. glow->set_luminance_multiplier(p_render_data->luminance_multiplier);
  2325. glow->set_intensity(glow_intensity);
  2326. glow->set_glow_bloom(glow_bloom);
  2327. glow->set_glow_hdr_bleed_threshold(glow_hdr_bleed_threshold);
  2328. glow->set_glow_hdr_bleed_scale(glow_hdr_bleed_scale);
  2329. glow->set_glow_hdr_luminance_cap(glow_hdr_luminance_cap);
  2330. }
  2331. GLuint write_color = texture_storage->render_target_get_color(render_target);
  2332. for (uint32_t v = 0; v < view_count; v++) {
  2333. if (glow_enabled) {
  2334. glow->process_glow(source_color, internal_size, glow_buffers, v, true);
  2335. }
  2336. glBindFramebuffer(GL_FRAMEBUFFER, fbos[2]);
  2337. glFramebufferTextureLayer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, write_color, 0, v);
  2338. post_effects->post_copy(fbos[2], target_size, source_color, internal_size, p_render_data->luminance_multiplier, glow_buffers, glow_intensity, v, true, bcs_spec_constants);
  2339. }
  2340. // Copy depth
  2341. GLuint read_depth = rb->get_internal_depth();
  2342. GLuint write_depth = texture_storage->render_target_get_depth(render_target);
  2343. glBindFramebuffer(GL_READ_FRAMEBUFFER, fbos[0]);
  2344. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbos[1]);
  2345. for (uint32_t v = 0; v < view_count; v++) {
  2346. glFramebufferTextureLayer(GL_READ_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, read_depth, 0, v);
  2347. glFramebufferTextureLayer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, write_depth, 0, v);
  2348. glBlitFramebuffer(0, 0, internal_size.x, internal_size.y, 0, 0, target_size.x, target_size.y, GL_DEPTH_BUFFER_BIT, GL_NEAREST);
  2349. }
  2350. }
  2351. glBindFramebuffer(GL_FRAMEBUFFER, fbo_rt);
  2352. glDeleteFramebuffers(3, fbos);
  2353. }
  2354. glActiveTexture(GL_TEXTURE2);
  2355. glBindTexture(GL_TEXTURE_2D, 0);
  2356. }
  2357. template <PassMode p_pass_mode>
  2358. void RasterizerSceneGLES3::_render_list_template(RenderListParameters *p_params, const RenderDataGLES3 *p_render_data, uint32_t p_from_element, uint32_t p_to_element, bool p_alpha_pass) {
  2359. GLES3::MeshStorage *mesh_storage = GLES3::MeshStorage::get_singleton();
  2360. GLES3::ParticlesStorage *particles_storage = GLES3::ParticlesStorage::get_singleton();
  2361. GLES3::MaterialStorage *material_storage = GLES3::MaterialStorage::get_singleton();
  2362. GLuint prev_vertex_array_gl = 0;
  2363. GLuint prev_index_array_gl = 0;
  2364. GLES3::SceneMaterialData *prev_material_data = nullptr;
  2365. GLES3::SceneShaderData *prev_shader = nullptr;
  2366. GeometryInstanceGLES3 *prev_inst = nullptr;
  2367. SceneShaderGLES3::ShaderVariant prev_variant = SceneShaderGLES3::ShaderVariant::MODE_COLOR;
  2368. SceneShaderGLES3::ShaderVariant shader_variant = SceneShaderGLES3::MODE_COLOR; // Assigned to silence wrong -Wmaybe-initialized
  2369. uint64_t prev_spec_constants = 0;
  2370. // Specializations constants used by all instances in the scene.
  2371. uint64_t base_spec_constants = p_params->spec_constant_base_flags;
  2372. if constexpr (p_pass_mode == PASS_MODE_COLOR || p_pass_mode == PASS_MODE_COLOR_TRANSPARENT) {
  2373. GLES3::TextureStorage *texture_storage = GLES3::TextureStorage::get_singleton();
  2374. GLES3::Config *config = GLES3::Config::get_singleton();
  2375. glActiveTexture(GL_TEXTURE0 + config->max_texture_image_units - 2);
  2376. GLuint texture_to_bind = texture_storage->get_texture(texture_storage->texture_gl_get_default(GLES3::DEFAULT_GL_TEXTURE_CUBEMAP_BLACK))->tex_id;
  2377. if (p_render_data->environment.is_valid()) {
  2378. Sky *sky = sky_owner.get_or_null(environment_get_sky(p_render_data->environment));
  2379. if (sky && sky->radiance != 0) {
  2380. texture_to_bind = sky->radiance;
  2381. base_spec_constants |= SceneShaderGLES3::USE_RADIANCE_MAP;
  2382. }
  2383. glBindTexture(GL_TEXTURE_CUBE_MAP, texture_to_bind);
  2384. }
  2385. } else if constexpr (p_pass_mode == PASS_MODE_DEPTH || p_pass_mode == PASS_MODE_SHADOW) {
  2386. shader_variant = SceneShaderGLES3::MODE_DEPTH;
  2387. }
  2388. if (p_render_data->view_count > 1) {
  2389. base_spec_constants |= SceneShaderGLES3::USE_MULTIVIEW;
  2390. }
  2391. bool should_request_redraw = false;
  2392. if constexpr (p_pass_mode != PASS_MODE_DEPTH) {
  2393. // Don't count elements during depth pre-pass to match the RD renderers.
  2394. if (p_render_data->render_info) {
  2395. p_render_data->render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_VISIBLE][RS::VIEWPORT_RENDER_INFO_OBJECTS_IN_FRAME] += p_to_element - p_from_element;
  2396. }
  2397. }
  2398. for (uint32_t i = p_from_element; i < p_to_element; i++) {
  2399. GeometryInstanceSurface *surf = p_params->elements[i];
  2400. GeometryInstanceGLES3 *inst = surf->owner;
  2401. if (p_pass_mode == PASS_MODE_COLOR && !(surf->flags & GeometryInstanceSurface::FLAG_PASS_OPAQUE)) {
  2402. continue; // Objects with "Depth-prepass" transparency are included in both render lists, but should only be rendered in the transparent pass
  2403. }
  2404. if (inst->instance_count == 0) {
  2405. continue;
  2406. }
  2407. GLES3::SceneShaderData *shader;
  2408. GLES3::SceneMaterialData *material_data;
  2409. void *mesh_surface;
  2410. if constexpr (p_pass_mode == PASS_MODE_SHADOW) {
  2411. shader = surf->shader_shadow;
  2412. material_data = surf->material_shadow;
  2413. mesh_surface = surf->surface_shadow;
  2414. } else {
  2415. if (unlikely(get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_OVERDRAW)) {
  2416. material_data = overdraw_material_data_ptr;
  2417. shader = material_data->shader_data;
  2418. } else if (unlikely(get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_LIGHTING)) {
  2419. material_data = default_material_data_ptr;
  2420. shader = material_data->shader_data;
  2421. } else {
  2422. shader = surf->shader;
  2423. material_data = surf->material;
  2424. }
  2425. mesh_surface = surf->surface;
  2426. }
  2427. if (!mesh_surface) {
  2428. continue;
  2429. }
  2430. //request a redraw if one of the shaders uses TIME
  2431. if (shader->uses_time) {
  2432. should_request_redraw = true;
  2433. }
  2434. if constexpr (p_pass_mode == PASS_MODE_COLOR_TRANSPARENT) {
  2435. scene_state.enable_gl_depth_test(shader->depth_test == GLES3::SceneShaderData::DEPTH_TEST_ENABLED);
  2436. }
  2437. if constexpr (p_pass_mode != PASS_MODE_SHADOW) {
  2438. if (shader->depth_draw == GLES3::SceneShaderData::DEPTH_DRAW_OPAQUE) {
  2439. scene_state.enable_gl_depth_draw((p_pass_mode == PASS_MODE_COLOR && !GLES3::Config::get_singleton()->use_depth_prepass) || p_pass_mode == PASS_MODE_DEPTH);
  2440. } else {
  2441. scene_state.enable_gl_depth_draw(shader->depth_draw == GLES3::SceneShaderData::DEPTH_DRAW_ALWAYS);
  2442. }
  2443. }
  2444. bool uses_additive_lighting = (inst->light_passes.size() + p_render_data->directional_shadow_count) > 0;
  2445. uses_additive_lighting = uses_additive_lighting && !shader->unshaded;
  2446. // TODOS
  2447. /*
  2448. * Still a bug when atlas space is limited. Somehow need to evict light when it doesn't have a spot on the atlas, current check isn't enough
  2449. * Disable depth draw
  2450. */
  2451. for (int32_t pass = 0; pass < MAX(1, int32_t(inst->light_passes.size() + p_render_data->directional_shadow_count)); pass++) {
  2452. if constexpr (p_pass_mode == PASS_MODE_DEPTH || p_pass_mode == PASS_MODE_SHADOW) {
  2453. if (pass > 0) {
  2454. // Don't render shadow passes when doing depth or shadow pass.
  2455. break;
  2456. }
  2457. }
  2458. if constexpr (p_pass_mode == PASS_MODE_COLOR || p_pass_mode == PASS_MODE_COLOR_TRANSPARENT) {
  2459. if (!uses_additive_lighting && pass == 1) {
  2460. // Don't render additive passes if not using additive lighting.
  2461. break;
  2462. }
  2463. if (uses_additive_lighting && pass == 1 && !p_render_data->transparent_bg) {
  2464. // Enable blending if in opaque pass and not already enabled.
  2465. scene_state.enable_gl_blend(true);
  2466. }
  2467. if (pass < int32_t(inst->light_passes.size())) {
  2468. RID light_instance_rid = inst->light_passes[pass].light_instance_rid;
  2469. if (!GLES3::LightStorage::get_singleton()->light_instance_has_shadow_atlas(light_instance_rid, p_render_data->shadow_atlas)) {
  2470. // Shadow wasn't able to get a spot on the atlas. So skip it.
  2471. continue;
  2472. }
  2473. } else if (pass > 0) {
  2474. uint32_t shadow_id = MAX_DIRECTIONAL_LIGHTS - 1 - (pass - int32_t(inst->light_passes.size()));
  2475. if (inst->lightmap_instance.is_valid() && scene_state.directional_lights[shadow_id].bake_mode == RenderingServer::LIGHT_BAKE_STATIC) {
  2476. // Skip shadows for static lights on meshes with a lightmap.
  2477. continue;
  2478. }
  2479. }
  2480. }
  2481. if constexpr (p_pass_mode == PASS_MODE_COLOR || p_pass_mode == PASS_MODE_COLOR_TRANSPARENT) {
  2482. GLES3::SceneShaderData::BlendMode desired_blend_mode;
  2483. if (pass > 0) {
  2484. desired_blend_mode = GLES3::SceneShaderData::BLEND_MODE_ADD;
  2485. } else {
  2486. desired_blend_mode = shader->blend_mode;
  2487. }
  2488. if (desired_blend_mode != scene_state.current_blend_mode) {
  2489. switch (desired_blend_mode) {
  2490. case GLES3::SceneShaderData::BLEND_MODE_MIX: {
  2491. glBlendEquation(GL_FUNC_ADD);
  2492. if (p_render_data->transparent_bg) {
  2493. glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
  2494. } else {
  2495. glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ZERO, GL_ONE);
  2496. }
  2497. } break;
  2498. case GLES3::SceneShaderData::BLEND_MODE_ADD: {
  2499. glBlendEquation(GL_FUNC_ADD);
  2500. glBlendFunc(p_pass_mode == PASS_MODE_COLOR_TRANSPARENT ? GL_SRC_ALPHA : GL_ONE, GL_ONE);
  2501. } break;
  2502. case GLES3::SceneShaderData::BLEND_MODE_SUB: {
  2503. glBlendEquation(GL_FUNC_REVERSE_SUBTRACT);
  2504. glBlendFunc(GL_SRC_ALPHA, GL_ONE);
  2505. } break;
  2506. case GLES3::SceneShaderData::BLEND_MODE_MUL: {
  2507. glBlendEquation(GL_FUNC_ADD);
  2508. if (p_render_data->transparent_bg) {
  2509. glBlendFuncSeparate(GL_DST_COLOR, GL_ZERO, GL_DST_ALPHA, GL_ZERO);
  2510. } else {
  2511. glBlendFuncSeparate(GL_DST_COLOR, GL_ZERO, GL_ZERO, GL_ONE);
  2512. }
  2513. } break;
  2514. case GLES3::SceneShaderData::BLEND_MODE_PREMULT_ALPHA: {
  2515. glBlendEquation(GL_FUNC_ADD);
  2516. glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
  2517. } break;
  2518. case GLES3::SceneShaderData::BLEND_MODE_ALPHA_TO_COVERAGE: {
  2519. // Do nothing for now.
  2520. } break;
  2521. }
  2522. scene_state.current_blend_mode = desired_blend_mode;
  2523. }
  2524. }
  2525. // Find cull variant.
  2526. RS::CullMode cull_mode = shader->cull_mode;
  2527. if (p_pass_mode == PASS_MODE_MATERIAL || (surf->flags & GeometryInstanceSurface::FLAG_USES_DOUBLE_SIDED_SHADOWS)) {
  2528. cull_mode = RS::CULL_MODE_DISABLED;
  2529. } else {
  2530. bool mirror = inst->mirror;
  2531. if (p_params->reverse_cull) {
  2532. mirror = !mirror;
  2533. }
  2534. if (cull_mode == RS::CULL_MODE_FRONT && mirror) {
  2535. cull_mode = RS::CULL_MODE_BACK;
  2536. } else if (cull_mode == RS::CULL_MODE_BACK && mirror) {
  2537. cull_mode = RS::CULL_MODE_FRONT;
  2538. }
  2539. }
  2540. scene_state.set_gl_cull_mode(cull_mode);
  2541. RS::PrimitiveType primitive = surf->primitive;
  2542. if (shader->uses_point_size) {
  2543. primitive = RS::PRIMITIVE_POINTS;
  2544. }
  2545. static const GLenum prim[5] = { GL_POINTS, GL_LINES, GL_LINE_STRIP, GL_TRIANGLES, GL_TRIANGLE_STRIP };
  2546. GLenum primitive_gl = prim[int(primitive)];
  2547. GLuint vertex_array_gl = 0;
  2548. GLuint index_array_gl = 0;
  2549. uint64_t vertex_input_mask = shader->vertex_input_mask;
  2550. if (inst->lightmap_instance.is_valid() || p_pass_mode == PASS_MODE_MATERIAL) {
  2551. vertex_input_mask |= 1 << RS::ARRAY_TEX_UV2;
  2552. }
  2553. // Skeleton and blend shapes.
  2554. if (surf->owner->mesh_instance.is_valid()) {
  2555. mesh_storage->mesh_instance_surface_get_vertex_arrays_and_format(surf->owner->mesh_instance, surf->surface_index, vertex_input_mask, vertex_array_gl);
  2556. } else {
  2557. mesh_storage->mesh_surface_get_vertex_arrays_and_format(mesh_surface, vertex_input_mask, vertex_array_gl);
  2558. }
  2559. index_array_gl = mesh_storage->mesh_surface_get_index_buffer(mesh_surface, surf->lod_index);
  2560. if (prev_vertex_array_gl != vertex_array_gl) {
  2561. if (vertex_array_gl != 0) {
  2562. glBindVertexArray(vertex_array_gl);
  2563. }
  2564. prev_vertex_array_gl = vertex_array_gl;
  2565. // Invalidate the previous index array
  2566. prev_index_array_gl = 0;
  2567. }
  2568. bool use_wireframe = false;
  2569. if (p_params->force_wireframe || shader->wireframe) {
  2570. GLuint wireframe_index_array_gl = mesh_storage->mesh_surface_get_index_buffer_wireframe(mesh_surface);
  2571. if (wireframe_index_array_gl) {
  2572. index_array_gl = wireframe_index_array_gl;
  2573. use_wireframe = true;
  2574. }
  2575. }
  2576. bool use_index_buffer = index_array_gl != 0;
  2577. if (prev_index_array_gl != index_array_gl) {
  2578. if (index_array_gl != 0) {
  2579. // Bind index each time so we can use LODs
  2580. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, index_array_gl);
  2581. }
  2582. prev_index_array_gl = index_array_gl;
  2583. }
  2584. Transform3D world_transform;
  2585. if (inst->store_transform_cache) {
  2586. world_transform = inst->transform;
  2587. }
  2588. if (prev_material_data != material_data) {
  2589. material_data->bind_uniforms();
  2590. prev_material_data = material_data;
  2591. }
  2592. SceneShaderGLES3::ShaderVariant instance_variant = shader_variant;
  2593. if (inst->instance_count > 0) {
  2594. // Will need to use instancing to draw (either MultiMesh or Particles).
  2595. instance_variant = SceneShaderGLES3::ShaderVariant(1 + int(instance_variant));
  2596. }
  2597. uint64_t spec_constants = base_spec_constants;
  2598. // Set up spec constants for lighting.
  2599. if constexpr (p_pass_mode == PASS_MODE_COLOR || p_pass_mode == PASS_MODE_COLOR_TRANSPARENT) {
  2600. // Only check during color passes as light shader code is compiled out during depth-only pass anyway.
  2601. if (pass == 0) {
  2602. spec_constants |= SceneShaderGLES3::BASE_PASS;
  2603. if (get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_UNSHADED) {
  2604. spec_constants |= SceneShaderGLES3::DISABLE_LIGHT_OMNI;
  2605. spec_constants |= SceneShaderGLES3::DISABLE_LIGHT_SPOT;
  2606. spec_constants |= SceneShaderGLES3::DISABLE_LIGHT_DIRECTIONAL;
  2607. spec_constants |= SceneShaderGLES3::DISABLE_LIGHTMAP;
  2608. } else {
  2609. if (inst->omni_light_gl_cache.size() == 0) {
  2610. spec_constants |= SceneShaderGLES3::DISABLE_LIGHT_OMNI;
  2611. }
  2612. if (inst->spot_light_gl_cache.size() == 0) {
  2613. spec_constants |= SceneShaderGLES3::DISABLE_LIGHT_SPOT;
  2614. }
  2615. if (p_render_data->directional_light_count == p_render_data->directional_shadow_count) {
  2616. spec_constants |= SceneShaderGLES3::DISABLE_LIGHT_DIRECTIONAL;
  2617. }
  2618. if (inst->reflection_probe_rid_cache.size() == 0) {
  2619. // We don't have any probes.
  2620. spec_constants |= SceneShaderGLES3::DISABLE_REFLECTION_PROBE;
  2621. } else if (inst->reflection_probe_rid_cache.size() > 1) {
  2622. // We have a second probe.
  2623. spec_constants |= SceneShaderGLES3::SECOND_REFLECTION_PROBE;
  2624. }
  2625. if (inst->lightmap_instance.is_valid()) {
  2626. spec_constants |= SceneShaderGLES3::USE_LIGHTMAP;
  2627. GLES3::LightmapInstance *li = GLES3::LightStorage::get_singleton()->get_lightmap_instance(inst->lightmap_instance);
  2628. GLES3::Lightmap *lm = GLES3::LightStorage::get_singleton()->get_lightmap(li->lightmap);
  2629. if (lm->uses_spherical_harmonics) {
  2630. spec_constants |= SceneShaderGLES3::USE_SH_LIGHTMAP;
  2631. }
  2632. if (lightmap_bicubic_upscale) {
  2633. spec_constants |= SceneShaderGLES3::LIGHTMAP_BICUBIC_FILTER;
  2634. }
  2635. } else if (inst->lightmap_sh) {
  2636. spec_constants |= SceneShaderGLES3::USE_LIGHTMAP_CAPTURE;
  2637. } else {
  2638. spec_constants |= SceneShaderGLES3::DISABLE_LIGHTMAP;
  2639. }
  2640. }
  2641. } else {
  2642. // Only base pass uses the radiance map.
  2643. spec_constants &= ~SceneShaderGLES3::USE_RADIANCE_MAP;
  2644. spec_constants |= SceneShaderGLES3::DISABLE_LIGHT_OMNI;
  2645. spec_constants |= SceneShaderGLES3::DISABLE_LIGHT_SPOT;
  2646. spec_constants |= SceneShaderGLES3::DISABLE_LIGHT_DIRECTIONAL;
  2647. spec_constants |= SceneShaderGLES3::DISABLE_REFLECTION_PROBE;
  2648. bool disable_lightmaps = true;
  2649. // Additive directional passes may use shadowmasks, so enable lightmaps for them.
  2650. if (pass >= int32_t(inst->light_passes.size()) && inst->lightmap_instance.is_valid()) {
  2651. GLES3::LightmapInstance *li = GLES3::LightStorage::get_singleton()->get_lightmap_instance(inst->lightmap_instance);
  2652. GLES3::Lightmap *lm = GLES3::LightStorage::get_singleton()->get_lightmap(li->lightmap);
  2653. if (lm->shadowmask_mode != RS::SHADOWMASK_MODE_NONE) {
  2654. spec_constants |= SceneShaderGLES3::USE_LIGHTMAP;
  2655. disable_lightmaps = false;
  2656. if (lightmap_bicubic_upscale) {
  2657. spec_constants |= SceneShaderGLES3::LIGHTMAP_BICUBIC_FILTER;
  2658. }
  2659. }
  2660. }
  2661. if (disable_lightmaps) {
  2662. spec_constants |= SceneShaderGLES3::DISABLE_LIGHTMAP;
  2663. }
  2664. }
  2665. if (uses_additive_lighting) {
  2666. spec_constants |= SceneShaderGLES3::USE_ADDITIVE_LIGHTING;
  2667. if (pass < int32_t(inst->light_passes.size())) {
  2668. // Rendering positional lights.
  2669. if (inst->light_passes[pass].is_omni) {
  2670. spec_constants |= SceneShaderGLES3::ADDITIVE_OMNI;
  2671. } else {
  2672. spec_constants |= SceneShaderGLES3::ADDITIVE_SPOT;
  2673. }
  2674. if (scene_state.positional_shadow_quality >= RS::SHADOW_QUALITY_SOFT_HIGH) {
  2675. spec_constants |= SceneShaderGLES3::SHADOW_MODE_PCF_13;
  2676. } else if (scene_state.positional_shadow_quality >= RS::SHADOW_QUALITY_SOFT_LOW) {
  2677. spec_constants |= SceneShaderGLES3::SHADOW_MODE_PCF_5;
  2678. }
  2679. } else {
  2680. // Render directional lights.
  2681. uint32_t shadow_id = MAX_DIRECTIONAL_LIGHTS - 1 - (pass - int32_t(inst->light_passes.size()));
  2682. if (pass == 0 && inst->lightmap_instance.is_valid() && scene_state.directional_lights[shadow_id].bake_mode == RenderingServer::LIGHT_BAKE_STATIC) {
  2683. // Disable additive lighting with a static light and a lightmap.
  2684. spec_constants &= ~SceneShaderGLES3::USE_ADDITIVE_LIGHTING;
  2685. }
  2686. if (scene_state.directional_shadows[shadow_id].shadow_split_offsets[0] == scene_state.directional_shadows[shadow_id].shadow_split_offsets[1]) {
  2687. // Orthogonal, do nothing.
  2688. } else if (scene_state.directional_shadows[shadow_id].shadow_split_offsets[1] == scene_state.directional_shadows[shadow_id].shadow_split_offsets[2]) {
  2689. spec_constants |= SceneShaderGLES3::LIGHT_USE_PSSM2;
  2690. } else {
  2691. spec_constants |= SceneShaderGLES3::LIGHT_USE_PSSM4;
  2692. }
  2693. if (scene_state.directional_shadows[shadow_id].blend_splits) {
  2694. spec_constants |= SceneShaderGLES3::LIGHT_USE_PSSM_BLEND;
  2695. }
  2696. if (scene_state.directional_shadow_quality >= RS::SHADOW_QUALITY_SOFT_HIGH) {
  2697. spec_constants |= SceneShaderGLES3::SHADOW_MODE_PCF_13;
  2698. } else if (scene_state.directional_shadow_quality >= RS::SHADOW_QUALITY_SOFT_LOW) {
  2699. spec_constants |= SceneShaderGLES3::SHADOW_MODE_PCF_5;
  2700. }
  2701. }
  2702. }
  2703. }
  2704. if (prev_shader != shader || prev_variant != instance_variant || spec_constants != prev_spec_constants) {
  2705. bool success = material_storage->shaders.scene_shader.version_bind_shader(shader->version, instance_variant, spec_constants);
  2706. if (!success) {
  2707. break;
  2708. }
  2709. float opaque_prepass_threshold = 0.0;
  2710. if constexpr (p_pass_mode == PASS_MODE_DEPTH) {
  2711. opaque_prepass_threshold = 0.99;
  2712. } else if constexpr (p_pass_mode == PASS_MODE_SHADOW) {
  2713. opaque_prepass_threshold = 0.1;
  2714. }
  2715. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::OPAQUE_PREPASS_THRESHOLD, opaque_prepass_threshold, shader->version, instance_variant, spec_constants);
  2716. }
  2717. // Pass in lighting uniforms.
  2718. if constexpr (p_pass_mode == PASS_MODE_COLOR || p_pass_mode == PASS_MODE_COLOR_TRANSPARENT) {
  2719. GLES3::Config *config = GLES3::Config::get_singleton();
  2720. // Pass light and shadow index and bind shadow texture.
  2721. if (uses_additive_lighting) {
  2722. if (pass < int32_t(inst->light_passes.size())) {
  2723. int32_t shadow_id = inst->light_passes[pass].shadow_id;
  2724. if (shadow_id >= 0) {
  2725. uint32_t light_id = inst->light_passes[pass].light_id;
  2726. bool is_omni = inst->light_passes[pass].is_omni;
  2727. SceneShaderGLES3::Uniforms uniform_name = is_omni ? SceneShaderGLES3::OMNI_LIGHT_INDEX : SceneShaderGLES3::SPOT_LIGHT_INDEX;
  2728. material_storage->shaders.scene_shader.version_set_uniform(uniform_name, uint32_t(light_id), shader->version, instance_variant, spec_constants);
  2729. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::POSITIONAL_SHADOW_INDEX, uint32_t(shadow_id), shader->version, instance_variant, spec_constants);
  2730. glActiveTexture(GL_TEXTURE0 + config->max_texture_image_units - 3);
  2731. RID light_instance_rid = inst->light_passes[pass].light_instance_rid;
  2732. GLuint tex = GLES3::LightStorage::get_singleton()->light_instance_get_shadow_texture(light_instance_rid, p_render_data->shadow_atlas);
  2733. if (is_omni) {
  2734. glBindTexture(GL_TEXTURE_CUBE_MAP, tex);
  2735. } else {
  2736. glBindTexture(GL_TEXTURE_2D, tex);
  2737. }
  2738. }
  2739. } else {
  2740. uint32_t shadow_id = MAX_DIRECTIONAL_LIGHTS - 1 - (pass - int32_t(inst->light_passes.size()));
  2741. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::DIRECTIONAL_SHADOW_INDEX, shadow_id, shader->version, instance_variant, spec_constants);
  2742. GLuint tex = GLES3::LightStorage::get_singleton()->directional_shadow_get_texture();
  2743. glActiveTexture(GL_TEXTURE0 + config->max_texture_image_units - 3);
  2744. glBindTexture(GL_TEXTURE_2D, tex);
  2745. if (inst->lightmap_instance.is_valid()) {
  2746. // Use shadowmasks for directional light passes.
  2747. GLES3::LightmapInstance *li = GLES3::LightStorage::get_singleton()->get_lightmap_instance(inst->lightmap_instance);
  2748. GLES3::Lightmap *lm = GLES3::LightStorage::get_singleton()->get_lightmap(li->lightmap);
  2749. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::LIGHTMAP_SLICE, inst->lightmap_slice_index, shader->version, instance_variant, spec_constants);
  2750. Vector4 uv_scale(inst->lightmap_uv_scale.position.x, inst->lightmap_uv_scale.position.y, inst->lightmap_uv_scale.size.x, inst->lightmap_uv_scale.size.y);
  2751. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::LIGHTMAP_UV_SCALE, uv_scale, shader->version, instance_variant, spec_constants);
  2752. if (lightmap_bicubic_upscale) {
  2753. Vector2 light_texture_size(lm->light_texture_size.x, lm->light_texture_size.y);
  2754. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::LIGHTMAP_TEXTURE_SIZE, light_texture_size, shader->version, instance_variant, spec_constants);
  2755. }
  2756. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::LIGHTMAP_SHADOWMASK_MODE, (uint32_t)lm->shadowmask_mode, shader->version, instance_variant, spec_constants);
  2757. if (lm->shadow_texture.is_valid()) {
  2758. tex = GLES3::TextureStorage::get_singleton()->texture_get_texid(lm->shadow_texture);
  2759. } else {
  2760. tex = GLES3::TextureStorage::get_singleton()->texture_get_texid(GLES3::TextureStorage::get_singleton()->texture_gl_get_default(GLES3::DEFAULT_GL_TEXTURE_2D_ARRAY_WHITE));
  2761. }
  2762. glActiveTexture(GL_TEXTURE0 + config->max_texture_image_units - 5);
  2763. glBindTexture(GL_TEXTURE_2D_ARRAY, tex);
  2764. }
  2765. }
  2766. }
  2767. // Pass light count and array of light indices for base pass.
  2768. if ((prev_inst != inst || prev_shader != shader || prev_variant != instance_variant || prev_spec_constants != spec_constants) && pass == 0) {
  2769. // Rebind the light indices.
  2770. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::OMNI_LIGHT_COUNT, inst->omni_light_gl_cache.size(), shader->version, instance_variant, spec_constants);
  2771. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::SPOT_LIGHT_COUNT, inst->spot_light_gl_cache.size(), shader->version, instance_variant, spec_constants);
  2772. if (inst->omni_light_gl_cache.size()) {
  2773. glUniform1uiv(material_storage->shaders.scene_shader.version_get_uniform(SceneShaderGLES3::OMNI_LIGHT_INDICES, shader->version, instance_variant, spec_constants), inst->omni_light_gl_cache.size(), inst->omni_light_gl_cache.ptr());
  2774. }
  2775. if (inst->spot_light_gl_cache.size()) {
  2776. glUniform1uiv(material_storage->shaders.scene_shader.version_get_uniform(SceneShaderGLES3::SPOT_LIGHT_INDICES, shader->version, instance_variant, spec_constants), inst->spot_light_gl_cache.size(), inst->spot_light_gl_cache.ptr());
  2777. }
  2778. if (inst->lightmap_instance.is_valid()) {
  2779. GLES3::LightmapInstance *li = GLES3::LightStorage::get_singleton()->get_lightmap_instance(inst->lightmap_instance);
  2780. GLES3::Lightmap *lm = GLES3::LightStorage::get_singleton()->get_lightmap(li->lightmap);
  2781. GLuint tex = GLES3::TextureStorage::get_singleton()->texture_get_texid(lm->light_texture);
  2782. glActiveTexture(GL_TEXTURE0 + config->max_texture_image_units - 4);
  2783. glBindTexture(GL_TEXTURE_2D_ARRAY, tex);
  2784. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::LIGHTMAP_SLICE, inst->lightmap_slice_index, shader->version, instance_variant, spec_constants);
  2785. Vector4 uv_scale(inst->lightmap_uv_scale.position.x, inst->lightmap_uv_scale.position.y, inst->lightmap_uv_scale.size.x, inst->lightmap_uv_scale.size.y);
  2786. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::LIGHTMAP_UV_SCALE, uv_scale, shader->version, instance_variant, spec_constants);
  2787. if (lightmap_bicubic_upscale) {
  2788. Vector2 light_texture_size(lm->light_texture_size.x, lm->light_texture_size.y);
  2789. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::LIGHTMAP_TEXTURE_SIZE, light_texture_size, shader->version, instance_variant, spec_constants);
  2790. }
  2791. float exposure_normalization = 1.0;
  2792. if (p_render_data->camera_attributes.is_valid()) {
  2793. float enf = RSG::camera_attributes->camera_attributes_get_exposure_normalization_factor(p_render_data->camera_attributes);
  2794. exposure_normalization = enf / lm->baked_exposure;
  2795. }
  2796. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::LIGHTMAP_EXPOSURE_NORMALIZATION, exposure_normalization, shader->version, instance_variant, spec_constants);
  2797. if (lm->uses_spherical_harmonics) {
  2798. Basis to_lm = li->transform.basis.inverse() * p_render_data->cam_transform.basis;
  2799. to_lm = to_lm.inverse().transposed();
  2800. GLfloat matrix[9] = {
  2801. (GLfloat)to_lm.rows[0][0],
  2802. (GLfloat)to_lm.rows[1][0],
  2803. (GLfloat)to_lm.rows[2][0],
  2804. (GLfloat)to_lm.rows[0][1],
  2805. (GLfloat)to_lm.rows[1][1],
  2806. (GLfloat)to_lm.rows[2][1],
  2807. (GLfloat)to_lm.rows[0][2],
  2808. (GLfloat)to_lm.rows[1][2],
  2809. (GLfloat)to_lm.rows[2][2],
  2810. };
  2811. glUniformMatrix3fv(material_storage->shaders.scene_shader.version_get_uniform(SceneShaderGLES3::LIGHTMAP_NORMAL_XFORM, shader->version, instance_variant, spec_constants), 1, GL_FALSE, matrix);
  2812. }
  2813. } else if (inst->lightmap_sh) {
  2814. glUniform4fv(material_storage->shaders.scene_shader.version_get_uniform(SceneShaderGLES3::LIGHTMAP_CAPTURES, shader->version, instance_variant, spec_constants), 9, reinterpret_cast<const GLfloat *>(inst->lightmap_sh->sh));
  2815. }
  2816. prev_inst = inst;
  2817. }
  2818. }
  2819. prev_shader = shader;
  2820. prev_variant = instance_variant;
  2821. prev_spec_constants = spec_constants;
  2822. // Pass in reflection probe data
  2823. if constexpr (p_pass_mode == PASS_MODE_COLOR || p_pass_mode == PASS_MODE_COLOR_TRANSPARENT) {
  2824. if (pass == 0 && inst->reflection_probe_rid_cache.size() > 0) {
  2825. GLES3::Config *config = GLES3::Config::get_singleton();
  2826. GLES3::LightStorage *light_storage = GLES3::LightStorage::get_singleton();
  2827. // Setup first probe.
  2828. {
  2829. RID probe_rid = light_storage->reflection_probe_instance_get_probe(inst->reflection_probe_rid_cache[0]);
  2830. GLES3::ReflectionProbe *probe = light_storage->get_reflection_probe(probe_rid);
  2831. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::REFPROBE1_USE_BOX_PROJECT, probe->box_projection, shader->version, instance_variant, spec_constants);
  2832. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::REFPROBE1_BOX_EXTENTS, probe->size * 0.5, shader->version, instance_variant, spec_constants);
  2833. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::REFPROBE1_BOX_OFFSET, probe->origin_offset, shader->version, instance_variant, spec_constants);
  2834. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::REFPROBE1_EXTERIOR, !probe->interior, shader->version, instance_variant, spec_constants);
  2835. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::REFPROBE1_INTENSITY, probe->intensity, shader->version, instance_variant, spec_constants);
  2836. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::REFPROBE1_AMBIENT_MODE, int(probe->ambient_mode), shader->version, instance_variant, spec_constants);
  2837. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::REFPROBE1_AMBIENT_COLOR, probe->ambient_color * probe->ambient_color_energy, shader->version, instance_variant, spec_constants);
  2838. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::REFPROBE1_LOCAL_MATRIX, inst->reflection_probes_local_transform_cache[0], shader->version, instance_variant, spec_constants);
  2839. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::REFPROBE1_BLEND_DISTANCE, probe->blend_distance, shader->version, instance_variant, spec_constants);
  2840. glActiveTexture(GL_TEXTURE0 + config->max_texture_image_units - 8);
  2841. glBindTexture(GL_TEXTURE_CUBE_MAP, light_storage->reflection_probe_instance_get_texture(inst->reflection_probe_rid_cache[0]));
  2842. }
  2843. if (inst->reflection_probe_rid_cache.size() > 1) {
  2844. // Setup second probe.
  2845. RID probe_rid = light_storage->reflection_probe_instance_get_probe(inst->reflection_probe_rid_cache[1]);
  2846. GLES3::ReflectionProbe *probe = light_storage->get_reflection_probe(probe_rid);
  2847. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::REFPROBE2_USE_BOX_PROJECT, probe->box_projection, shader->version, instance_variant, spec_constants);
  2848. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::REFPROBE2_BOX_EXTENTS, probe->size * 0.5, shader->version, instance_variant, spec_constants);
  2849. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::REFPROBE2_BOX_OFFSET, probe->origin_offset, shader->version, instance_variant, spec_constants);
  2850. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::REFPROBE2_EXTERIOR, !probe->interior, shader->version, instance_variant, spec_constants);
  2851. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::REFPROBE2_INTENSITY, probe->intensity, shader->version, instance_variant, spec_constants);
  2852. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::REFPROBE2_AMBIENT_MODE, int(probe->ambient_mode), shader->version, instance_variant, spec_constants);
  2853. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::REFPROBE2_AMBIENT_COLOR, probe->ambient_color * probe->ambient_color_energy, shader->version, instance_variant, spec_constants);
  2854. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::REFPROBE2_LOCAL_MATRIX, inst->reflection_probes_local_transform_cache[1], shader->version, instance_variant, spec_constants);
  2855. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::REFPROBE2_BLEND_DISTANCE, probe->blend_distance, shader->version, instance_variant, spec_constants);
  2856. glActiveTexture(GL_TEXTURE0 + config->max_texture_image_units - 9);
  2857. glBindTexture(GL_TEXTURE_CUBE_MAP, light_storage->reflection_probe_instance_get_texture(inst->reflection_probe_rid_cache[1]));
  2858. spec_constants |= SceneShaderGLES3::SECOND_REFLECTION_PROBE;
  2859. }
  2860. }
  2861. }
  2862. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::WORLD_TRANSFORM, world_transform, shader->version, instance_variant, spec_constants);
  2863. {
  2864. GLES3::Mesh::Surface *s = reinterpret_cast<GLES3::Mesh::Surface *>(surf->surface);
  2865. if (s->format & RS::ARRAY_FLAG_COMPRESS_ATTRIBUTES) {
  2866. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::COMPRESSED_AABB_POSITION, s->aabb.position, shader->version, instance_variant, spec_constants);
  2867. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::COMPRESSED_AABB_SIZE, s->aabb.size, shader->version, instance_variant, spec_constants);
  2868. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::UV_SCALE, s->uv_scale, shader->version, instance_variant, spec_constants);
  2869. } else {
  2870. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::COMPRESSED_AABB_POSITION, Vector3(0.0, 0.0, 0.0), shader->version, instance_variant, spec_constants);
  2871. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::COMPRESSED_AABB_SIZE, Vector3(1.0, 1.0, 1.0), shader->version, instance_variant, spec_constants);
  2872. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::UV_SCALE, Vector4(0.0, 0.0, 0.0, 0.0), shader->version, instance_variant, spec_constants);
  2873. }
  2874. }
  2875. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::MODEL_FLAGS, inst->flags_cache, shader->version, instance_variant, spec_constants);
  2876. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::INSTANCE_OFFSET, uint32_t(inst->shader_uniforms_offset), shader->version, instance_variant, spec_constants);
  2877. if (p_pass_mode == PASS_MODE_MATERIAL) {
  2878. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::UV_OFFSET, p_params->uv_offset, shader->version, instance_variant, spec_constants);
  2879. }
  2880. // Can be index count or vertex count
  2881. uint32_t count = 0;
  2882. if (surf->lod_index > 0) {
  2883. count = surf->index_count;
  2884. } else {
  2885. count = mesh_storage->mesh_surface_get_vertices_drawn_count(mesh_surface);
  2886. }
  2887. if (use_wireframe) {
  2888. // In this case we are using index count, and we need double the indices for the wireframe mesh.
  2889. count = count * 2;
  2890. }
  2891. if constexpr (p_pass_mode != PASS_MODE_DEPTH) {
  2892. // Don't count draw calls during depth pre-pass to match the RD renderers.
  2893. if (p_render_data->render_info) {
  2894. p_render_data->render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_VISIBLE][RS::VIEWPORT_RENDER_INFO_DRAW_CALLS_IN_FRAME]++;
  2895. }
  2896. }
  2897. if (inst->instance_count > 0) {
  2898. // Using MultiMesh or Particles.
  2899. // Bind instance buffers.
  2900. GLuint instance_buffer = 0;
  2901. uint32_t stride = 0;
  2902. if (inst->flags_cache & INSTANCE_DATA_FLAG_PARTICLES) {
  2903. instance_buffer = particles_storage->particles_get_gl_buffer(inst->data->base);
  2904. stride = 16; // 12 bytes for instance transform and 4 bytes for packed color and custom.
  2905. } else {
  2906. instance_buffer = mesh_storage->multimesh_get_gl_buffer(inst->data->base);
  2907. stride = mesh_storage->multimesh_get_stride(inst->data->base);
  2908. }
  2909. if (instance_buffer == 0) {
  2910. // Instance buffer not initialized yet. Skip rendering for now.
  2911. break;
  2912. }
  2913. glBindBuffer(GL_ARRAY_BUFFER, instance_buffer);
  2914. glEnableVertexAttribArray(12);
  2915. glVertexAttribPointer(12, 4, GL_FLOAT, GL_FALSE, stride * sizeof(float), CAST_INT_TO_UCHAR_PTR(0));
  2916. glVertexAttribDivisor(12, 1);
  2917. glEnableVertexAttribArray(13);
  2918. glVertexAttribPointer(13, 4, GL_FLOAT, GL_FALSE, stride * sizeof(float), CAST_INT_TO_UCHAR_PTR(sizeof(float) * 4));
  2919. glVertexAttribDivisor(13, 1);
  2920. if (!(inst->flags_cache & INSTANCE_DATA_FLAG_MULTIMESH_FORMAT_2D)) {
  2921. glEnableVertexAttribArray(14);
  2922. glVertexAttribPointer(14, 4, GL_FLOAT, GL_FALSE, stride * sizeof(float), CAST_INT_TO_UCHAR_PTR(sizeof(float) * 8));
  2923. glVertexAttribDivisor(14, 1);
  2924. }
  2925. if ((inst->flags_cache & INSTANCE_DATA_FLAG_MULTIMESH_HAS_COLOR) || (inst->flags_cache & INSTANCE_DATA_FLAG_MULTIMESH_HAS_CUSTOM_DATA)) {
  2926. uint32_t color_custom_offset = inst->flags_cache & INSTANCE_DATA_FLAG_MULTIMESH_FORMAT_2D ? 8 : 12;
  2927. glEnableVertexAttribArray(15);
  2928. glVertexAttribIPointer(15, 4, GL_UNSIGNED_INT, stride * sizeof(float), CAST_INT_TO_UCHAR_PTR(color_custom_offset * sizeof(float)));
  2929. glVertexAttribDivisor(15, 1);
  2930. } else {
  2931. // Set all default instance color and custom data values to 1.0 or 0.0 using a compressed format.
  2932. uint16_t zero = Math::make_half_float(0.0f);
  2933. uint16_t one = Math::make_half_float(1.0f);
  2934. GLuint default_color = (uint32_t(one) << 16) | one;
  2935. GLuint default_custom = (uint32_t(zero) << 16) | zero;
  2936. glVertexAttribI4ui(15, default_color, default_color, default_custom, default_custom);
  2937. }
  2938. if (use_wireframe) {
  2939. glDrawElementsInstanced(GL_LINES, count, GL_UNSIGNED_INT, nullptr, inst->instance_count);
  2940. } else {
  2941. if (use_index_buffer) {
  2942. glDrawElementsInstanced(primitive_gl, count, mesh_storage->mesh_surface_get_index_type(mesh_surface), nullptr, inst->instance_count);
  2943. } else {
  2944. glDrawArraysInstanced(primitive_gl, 0, count, inst->instance_count);
  2945. }
  2946. }
  2947. } else {
  2948. // Using regular Mesh.
  2949. if (use_wireframe) {
  2950. glDrawElements(GL_LINES, count, GL_UNSIGNED_INT, nullptr);
  2951. } else {
  2952. if (use_index_buffer) {
  2953. glDrawElements(primitive_gl, count, mesh_storage->mesh_surface_get_index_type(mesh_surface), nullptr);
  2954. } else {
  2955. glDrawArrays(primitive_gl, 0, count);
  2956. }
  2957. }
  2958. }
  2959. if (inst->instance_count > 0) {
  2960. glDisableVertexAttribArray(12);
  2961. glDisableVertexAttribArray(13);
  2962. glDisableVertexAttribArray(14);
  2963. glDisableVertexAttribArray(15);
  2964. }
  2965. }
  2966. if constexpr (p_pass_mode == PASS_MODE_COLOR) {
  2967. if (uses_additive_lighting && !p_render_data->transparent_bg) {
  2968. // Disable additive blending if enabled for additive lights.
  2969. scene_state.enable_gl_blend(false);
  2970. }
  2971. }
  2972. }
  2973. // Make the actual redraw request
  2974. if (should_request_redraw) {
  2975. RenderingServerDefault::redraw_request();
  2976. }
  2977. }
  2978. void RasterizerSceneGLES3::render_material(const Transform3D &p_cam_transform, const Projection &p_cam_projection, bool p_cam_orthogonal, const PagedArray<RenderGeometryInstance *> &p_instances, RID p_framebuffer, const Rect2i &p_region) {
  2979. }
  2980. void RasterizerSceneGLES3::render_particle_collider_heightfield(RID p_collider, const Transform3D &p_transform, const PagedArray<RenderGeometryInstance *> &p_instances) {
  2981. GLES3::ParticlesStorage *particles_storage = GLES3::ParticlesStorage::get_singleton();
  2982. ERR_FAIL_COND(!particles_storage->particles_collision_is_heightfield(p_collider));
  2983. Vector3 extents = particles_storage->particles_collision_get_extents(p_collider) * p_transform.basis.get_scale();
  2984. Projection cm;
  2985. cm.set_orthogonal(-extents.x, extents.x, -extents.z, extents.z, 0, extents.y * 2.0);
  2986. Vector3 cam_pos = p_transform.origin;
  2987. cam_pos.y += extents.y;
  2988. Transform3D cam_xform;
  2989. cam_xform.set_look_at(cam_pos, cam_pos - p_transform.basis.get_column(Vector3::AXIS_Y), -p_transform.basis.get_column(Vector3::AXIS_Z).normalized());
  2990. GLuint fb = particles_storage->particles_collision_get_heightfield_framebuffer(p_collider);
  2991. Size2i fb_size = particles_storage->particles_collision_get_heightfield_size(p_collider);
  2992. RENDER_TIMESTAMP("Setup GPUParticlesCollisionHeightField3D");
  2993. RenderDataGLES3 render_data;
  2994. render_data.cam_projection = cm;
  2995. render_data.cam_transform = cam_xform;
  2996. render_data.view_projection[0] = cm;
  2997. render_data.inv_cam_transform = render_data.cam_transform.affine_inverse();
  2998. render_data.cam_orthogonal = true;
  2999. render_data.z_near = 0.0;
  3000. render_data.z_far = cm.get_z_far();
  3001. render_data.main_cam_transform = cam_xform;
  3002. render_data.instances = &p_instances;
  3003. _setup_environment(&render_data, true, Vector2(fb_size), true, Color(), false);
  3004. PassMode pass_mode = PASS_MODE_SHADOW;
  3005. _fill_render_list(RENDER_LIST_SECONDARY, &render_data, pass_mode);
  3006. render_list[RENDER_LIST_SECONDARY].sort_by_key();
  3007. RENDER_TIMESTAMP("Render Collider Heightfield");
  3008. glBindFramebuffer(GL_FRAMEBUFFER, fb);
  3009. glViewport(0, 0, fb_size.width, fb_size.height);
  3010. GLuint global_buffer = GLES3::MaterialStorage::get_singleton()->global_shader_parameters_get_uniform_buffer();
  3011. glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_GLOBALS_UNIFORM_LOCATION, global_buffer);
  3012. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  3013. scene_state.reset_gl_state();
  3014. scene_state.enable_gl_depth_test(true);
  3015. scene_state.enable_gl_depth_draw(true);
  3016. glDepthFunc(GL_GREATER);
  3017. glDrawBuffers(0, nullptr);
  3018. glColorMask(0, 0, 0, 0);
  3019. RasterizerGLES3::clear_depth(0.0);
  3020. glClear(GL_DEPTH_BUFFER_BIT);
  3021. RenderListParameters render_list_params(render_list[RENDER_LIST_SECONDARY].elements.ptr(), render_list[RENDER_LIST_SECONDARY].elements.size(), false, 31, false);
  3022. _render_list_template<PASS_MODE_SHADOW>(&render_list_params, &render_data, 0, render_list[RENDER_LIST_SECONDARY].elements.size());
  3023. glColorMask(1, 1, 1, 1);
  3024. glBindFramebuffer(GL_FRAMEBUFFER, GLES3::TextureStorage::system_fbo);
  3025. }
  3026. void RasterizerSceneGLES3::_render_uv2(const PagedArray<RenderGeometryInstance *> &p_instances, GLuint p_framebuffer, const Rect2i &p_region) {
  3027. RENDER_TIMESTAMP("Setup Rendering UV2");
  3028. RenderDataGLES3 render_data;
  3029. render_data.instances = &p_instances;
  3030. scene_state.ubo.emissive_exposure_normalization = -1.0; // Use default exposure normalization.
  3031. _setup_environment(&render_data, true, Vector2(1, 1), true, Color(), false);
  3032. PassMode pass_mode = PASS_MODE_MATERIAL;
  3033. _fill_render_list(RENDER_LIST_SECONDARY, &render_data, pass_mode);
  3034. render_list[RENDER_LIST_SECONDARY].sort_by_key();
  3035. RENDER_TIMESTAMP("Render 3D Material");
  3036. {
  3037. glBindFramebuffer(GL_FRAMEBUFFER, p_framebuffer);
  3038. glViewport(p_region.position.x, p_region.position.y, p_region.size.x, p_region.size.y);
  3039. GLuint global_buffer = GLES3::MaterialStorage::get_singleton()->global_shader_parameters_get_uniform_buffer();
  3040. glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_GLOBALS_UNIFORM_LOCATION, global_buffer);
  3041. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  3042. scene_state.reset_gl_state();
  3043. scene_state.enable_gl_depth_test(true);
  3044. scene_state.enable_gl_depth_draw(true);
  3045. glDepthFunc(GL_GREATER);
  3046. TightLocalVector<GLenum> draw_buffers;
  3047. draw_buffers.push_back(GL_COLOR_ATTACHMENT0);
  3048. draw_buffers.push_back(GL_COLOR_ATTACHMENT1);
  3049. draw_buffers.push_back(GL_COLOR_ATTACHMENT2);
  3050. draw_buffers.push_back(GL_COLOR_ATTACHMENT3);
  3051. glDrawBuffers(draw_buffers.size(), draw_buffers.ptr());
  3052. glClearColor(0.0, 0.0, 0.0, 0.0);
  3053. RasterizerGLES3::clear_depth(0.0);
  3054. glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
  3055. uint64_t base_spec_constant = 0;
  3056. base_spec_constant |= SceneShaderGLES3::RENDER_MATERIAL;
  3057. base_spec_constant |= SceneShaderGLES3::DISABLE_FOG;
  3058. base_spec_constant |= SceneShaderGLES3::DISABLE_LIGHT_DIRECTIONAL;
  3059. base_spec_constant |= SceneShaderGLES3::DISABLE_LIGHT_OMNI;
  3060. base_spec_constant |= SceneShaderGLES3::DISABLE_LIGHT_SPOT;
  3061. base_spec_constant |= SceneShaderGLES3::DISABLE_LIGHTMAP;
  3062. RenderListParameters render_list_params(render_list[RENDER_LIST_SECONDARY].elements.ptr(), render_list[RENDER_LIST_SECONDARY].elements.size(), false, base_spec_constant, true, Vector2(0, 0));
  3063. const int uv_offset_count = 9;
  3064. static const Vector2 uv_offsets[uv_offset_count] = {
  3065. Vector2(-1, 1),
  3066. Vector2(1, 1),
  3067. Vector2(1, -1),
  3068. Vector2(-1, -1),
  3069. Vector2(-1, 0),
  3070. Vector2(1, 0),
  3071. Vector2(0, -1),
  3072. Vector2(0, 1),
  3073. Vector2(0, 0),
  3074. };
  3075. for (int i = 0; i < uv_offset_count; i++) {
  3076. Vector2 ofs = uv_offsets[i];
  3077. ofs.x /= p_region.size.width;
  3078. ofs.y /= p_region.size.height;
  3079. render_list_params.uv_offset = ofs;
  3080. _render_list_template<PASS_MODE_MATERIAL>(&render_list_params, &render_data, 0, render_list[RENDER_LIST_SECONDARY].elements.size());
  3081. }
  3082. render_list_params.uv_offset = Vector2(0, 0);
  3083. render_list_params.force_wireframe = false;
  3084. _render_list_template<PASS_MODE_MATERIAL>(&render_list_params, &render_data, 0, render_list[RENDER_LIST_SECONDARY].elements.size());
  3085. GLuint db = GL_COLOR_ATTACHMENT0;
  3086. glDrawBuffers(1, &db);
  3087. glBindFramebuffer(GL_FRAMEBUFFER, GLES3::TextureStorage::system_fbo);
  3088. }
  3089. }
  3090. void RasterizerSceneGLES3::set_time(double p_time, double p_step) {
  3091. time = p_time;
  3092. time_step = p_step;
  3093. }
  3094. void RasterizerSceneGLES3::set_debug_draw_mode(RS::ViewportDebugDraw p_debug_draw) {
  3095. debug_draw = p_debug_draw;
  3096. }
  3097. Ref<RenderSceneBuffers> RasterizerSceneGLES3::render_buffers_create() {
  3098. Ref<RenderSceneBuffersGLES3> rb;
  3099. rb.instantiate();
  3100. return rb;
  3101. }
  3102. void RasterizerSceneGLES3::_render_buffers_debug_draw(Ref<RenderSceneBuffersGLES3> p_render_buffers, RID p_shadow_atlas, GLuint p_fbo) {
  3103. GLES3::TextureStorage *texture_storage = GLES3::TextureStorage::get_singleton();
  3104. GLES3::LightStorage *light_storage = GLES3::LightStorage::get_singleton();
  3105. GLES3::CopyEffects *copy_effects = GLES3::CopyEffects::get_singleton();
  3106. ERR_FAIL_COND(p_render_buffers.is_null());
  3107. RID render_target = p_render_buffers->render_target;
  3108. GLES3::RenderTarget *rt = texture_storage->get_render_target(render_target);
  3109. ERR_FAIL_NULL(rt);
  3110. if (debug_draw == RS::VIEWPORT_DEBUG_DRAW_SHADOW_ATLAS) {
  3111. if (p_shadow_atlas.is_valid()) {
  3112. // Get or create debug textures to display shadow maps as an atlas.
  3113. GLuint shadow_atlas_texture = light_storage->shadow_atlas_get_debug_texture(p_shadow_atlas);
  3114. GLuint shadow_atlas_fb = light_storage->shadow_atlas_get_debug_fb(p_shadow_atlas);
  3115. uint32_t shadow_atlas_size = light_storage->shadow_atlas_get_size(p_shadow_atlas);
  3116. uint32_t quadrant_size = shadow_atlas_size >> 1;
  3117. glBindFramebuffer(GL_FRAMEBUFFER, shadow_atlas_fb);
  3118. glViewport(0, 0, shadow_atlas_size, shadow_atlas_size);
  3119. glActiveTexture(GL_TEXTURE0);
  3120. scene_state.enable_gl_depth_draw(true);
  3121. glDepthFunc(GL_ALWAYS);
  3122. scene_state.set_gl_cull_mode(RS::CULL_MODE_DISABLED);
  3123. // Loop through quadrants and copy shadows over.
  3124. for (int quadrant = 0; quadrant < 4; quadrant++) {
  3125. uint32_t subdivision = light_storage->shadow_atlas_get_quadrant_subdivision(p_shadow_atlas, quadrant);
  3126. if (subdivision == 0) {
  3127. continue;
  3128. }
  3129. Rect2i atlas_rect;
  3130. Rect2 atlas_uv_rect;
  3131. uint32_t shadow_size = (quadrant_size / subdivision);
  3132. float size = float(shadow_size) / float(shadow_atlas_size);
  3133. uint32_t length = light_storage->shadow_atlas_get_quadrant_shadows_allocated(p_shadow_atlas, quadrant);
  3134. for (uint32_t shadow_idx = 0; shadow_idx < length; shadow_idx++) {
  3135. bool is_omni = light_storage->shadow_atlas_get_quadrant_shadow_is_omni(p_shadow_atlas, quadrant, shadow_idx);
  3136. // Calculate shadow's position in the debug atlas.
  3137. atlas_rect.position.x = (quadrant & 1) * quadrant_size;
  3138. atlas_rect.position.y = (quadrant >> 1) * quadrant_size;
  3139. atlas_rect.position.x += (shadow_idx % subdivision) * shadow_size;
  3140. atlas_rect.position.y += (shadow_idx / subdivision) * shadow_size;
  3141. atlas_uv_rect.position = Vector2(atlas_rect.position) / float(shadow_atlas_size);
  3142. atlas_uv_rect.size = Vector2(size, size);
  3143. GLuint shadow_tex = light_storage->shadow_atlas_get_quadrant_shadow_texture(p_shadow_atlas, quadrant, shadow_idx);
  3144. // Copy from shadowmap to debug atlas.
  3145. if (is_omni) {
  3146. glBindTexture(GL_TEXTURE_CUBE_MAP, shadow_tex);
  3147. glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_COMPARE_MODE, GL_NONE);
  3148. copy_effects->copy_cube_to_rect(atlas_uv_rect);
  3149. glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
  3150. glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_COMPARE_FUNC, GL_GREATER);
  3151. } else {
  3152. glBindTexture(GL_TEXTURE_2D, shadow_tex);
  3153. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE);
  3154. copy_effects->copy_to_rect(atlas_uv_rect);
  3155. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
  3156. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_GREATER);
  3157. }
  3158. }
  3159. }
  3160. // Set back to FBO
  3161. glBindFramebuffer(GL_FRAMEBUFFER, p_fbo);
  3162. Size2i size = p_render_buffers->get_internal_size();
  3163. glViewport(0, 0, size.width, size.height);
  3164. glBindTexture(GL_TEXTURE_2D, shadow_atlas_texture);
  3165. copy_effects->copy_to_rect(Rect2(Vector2(), Vector2(0.5, 0.5)));
  3166. glBindTexture(GL_TEXTURE_2D, 0);
  3167. glBindFramebuffer(GL_FRAMEBUFFER, GLES3::TextureStorage::system_fbo);
  3168. }
  3169. }
  3170. if (debug_draw == RS::VIEWPORT_DEBUG_DRAW_DIRECTIONAL_SHADOW_ATLAS) {
  3171. if (light_storage->directional_shadow_get_texture() != 0) {
  3172. GLuint shadow_atlas_texture = light_storage->directional_shadow_get_texture();
  3173. glActiveTexture(GL_TEXTURE0);
  3174. glBindTexture(GL_TEXTURE_2D, shadow_atlas_texture);
  3175. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE);
  3176. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_R, GL_RED);
  3177. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_G, GL_RED);
  3178. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, GL_RED);
  3179. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_A, GL_ONE);
  3180. scene_state.enable_gl_depth_test(false);
  3181. scene_state.enable_gl_depth_draw(false);
  3182. copy_effects->copy_to_rect(Rect2(Vector2(), Vector2(0.5, 0.5)));
  3183. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_R, GL_RED);
  3184. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_G, GL_GREEN);
  3185. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, GL_BLUE);
  3186. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_A, GL_ALPHA);
  3187. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
  3188. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_GREATER);
  3189. glBindTexture(GL_TEXTURE_2D, 0);
  3190. }
  3191. }
  3192. }
  3193. void RasterizerSceneGLES3::gi_set_use_half_resolution(bool p_enable) {
  3194. }
  3195. void RasterizerSceneGLES3::screen_space_roughness_limiter_set_active(bool p_enable, float p_amount, float p_curve) {
  3196. }
  3197. bool RasterizerSceneGLES3::screen_space_roughness_limiter_is_active() const {
  3198. return false;
  3199. }
  3200. void RasterizerSceneGLES3::sub_surface_scattering_set_quality(RS::SubSurfaceScatteringQuality p_quality) {
  3201. }
  3202. void RasterizerSceneGLES3::sub_surface_scattering_set_scale(float p_scale, float p_depth_scale) {
  3203. }
  3204. TypedArray<Image> RasterizerSceneGLES3::bake_render_uv2(RID p_base, const TypedArray<RID> &p_material_overrides, const Size2i &p_image_size) {
  3205. GLES3::Config *config = GLES3::Config::get_singleton();
  3206. ERR_FAIL_COND_V_MSG(p_image_size.width <= 0, TypedArray<Image>(), "Image width must be greater than 0.");
  3207. ERR_FAIL_COND_V_MSG(p_image_size.height <= 0, TypedArray<Image>(), "Image height must be greater than 0.");
  3208. GLuint albedo_alpha_tex = 0;
  3209. GLuint normal_tex = 0;
  3210. GLuint orm_tex = 0;
  3211. GLuint emission_tex = 0;
  3212. GLuint depth_tex = 0;
  3213. glGenTextures(1, &albedo_alpha_tex);
  3214. glGenTextures(1, &normal_tex);
  3215. glGenTextures(1, &orm_tex);
  3216. glGenTextures(1, &emission_tex);
  3217. glGenTextures(1, &depth_tex);
  3218. glBindTexture(GL_TEXTURE_2D, albedo_alpha_tex);
  3219. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, p_image_size.width, p_image_size.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
  3220. GLES3::Utilities::get_singleton()->texture_allocated_data(albedo_alpha_tex, p_image_size.width * p_image_size.height * 4, "Lightmap albedo texture");
  3221. glBindTexture(GL_TEXTURE_2D, normal_tex);
  3222. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, p_image_size.width, p_image_size.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
  3223. GLES3::Utilities::get_singleton()->texture_allocated_data(normal_tex, p_image_size.width * p_image_size.height * 4, "Lightmap normal texture");
  3224. glBindTexture(GL_TEXTURE_2D, orm_tex);
  3225. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, p_image_size.width, p_image_size.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
  3226. GLES3::Utilities::get_singleton()->texture_allocated_data(orm_tex, p_image_size.width * p_image_size.height * 4, "Lightmap ORM texture");
  3227. // Consider rendering to RGBA8 encoded as RGBE, then manually convert to RGBAH on CPU.
  3228. glBindTexture(GL_TEXTURE_2D, emission_tex);
  3229. if (config->float_texture_supported) {
  3230. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, p_image_size.width, p_image_size.height, 0, GL_RGBA, GL_FLOAT, nullptr);
  3231. GLES3::Utilities::get_singleton()->texture_allocated_data(emission_tex, p_image_size.width * p_image_size.height * 16, "Lightmap emission texture");
  3232. } else {
  3233. // Fallback to RGBA8 on devices that don't support rendering to floating point textures. This will look bad, but we have no choice.
  3234. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, p_image_size.width, p_image_size.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
  3235. GLES3::Utilities::get_singleton()->texture_allocated_data(emission_tex, p_image_size.width * p_image_size.height * 4, "Lightmap emission texture");
  3236. }
  3237. glBindTexture(GL_TEXTURE_2D, depth_tex);
  3238. glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, p_image_size.width, p_image_size.height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, nullptr);
  3239. GLES3::Utilities::get_singleton()->texture_allocated_data(depth_tex, p_image_size.width * p_image_size.height * 3, "Lightmap depth texture");
  3240. GLuint fbo = 0;
  3241. glGenFramebuffers(1, &fbo);
  3242. glBindFramebuffer(GL_FRAMEBUFFER, fbo);
  3243. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, albedo_alpha_tex, 0);
  3244. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, normal_tex, 0);
  3245. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, orm_tex, 0);
  3246. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT3, GL_TEXTURE_2D, emission_tex, 0);
  3247. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depth_tex, 0);
  3248. GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
  3249. if (status != GL_FRAMEBUFFER_COMPLETE) {
  3250. glDeleteFramebuffers(1, &fbo);
  3251. GLES3::Utilities::get_singleton()->texture_free_data(albedo_alpha_tex);
  3252. GLES3::Utilities::get_singleton()->texture_free_data(normal_tex);
  3253. GLES3::Utilities::get_singleton()->texture_free_data(orm_tex);
  3254. GLES3::Utilities::get_singleton()->texture_free_data(emission_tex);
  3255. GLES3::Utilities::get_singleton()->texture_free_data(depth_tex);
  3256. WARN_PRINT("Could not create render target, status: " + GLES3::TextureStorage::get_singleton()->get_framebuffer_error(status));
  3257. return TypedArray<Image>();
  3258. }
  3259. RenderGeometryInstance *gi_inst = geometry_instance_create(p_base);
  3260. ERR_FAIL_NULL_V(gi_inst, TypedArray<Image>());
  3261. uint32_t sc = RSG::mesh_storage->mesh_get_surface_count(p_base);
  3262. Vector<RID> materials;
  3263. materials.resize(sc);
  3264. for (uint32_t i = 0; i < sc; i++) {
  3265. if (i < (uint32_t)p_material_overrides.size()) {
  3266. materials.write[i] = p_material_overrides[i];
  3267. }
  3268. }
  3269. gi_inst->set_surface_materials(materials);
  3270. if (cull_argument.size() == 0) {
  3271. cull_argument.push_back(nullptr);
  3272. }
  3273. cull_argument[0] = gi_inst;
  3274. _render_uv2(cull_argument, fbo, Rect2i(0, 0, p_image_size.width, p_image_size.height));
  3275. geometry_instance_free(gi_inst);
  3276. TypedArray<Image> ret;
  3277. // Create a dummy texture so we can use texture_2d_get.
  3278. RID tex_rid = GLES3::TextureStorage::get_singleton()->texture_allocate();
  3279. GLES3::Texture texture;
  3280. texture.width = p_image_size.width;
  3281. texture.height = p_image_size.height;
  3282. texture.alloc_width = p_image_size.width;
  3283. texture.alloc_height = p_image_size.height;
  3284. texture.format = Image::FORMAT_RGBA8;
  3285. texture.real_format = Image::FORMAT_RGBA8;
  3286. texture.gl_format_cache = GL_RGBA;
  3287. texture.gl_type_cache = GL_UNSIGNED_BYTE;
  3288. texture.type = GLES3::Texture::TYPE_2D;
  3289. texture.target = GL_TEXTURE_2D;
  3290. texture.active = true;
  3291. texture.is_render_target = true; // Enable this so the texture isn't cached in the editor.
  3292. GLES3::TextureStorage::get_singleton()->texture_2d_initialize_from_texture(tex_rid, texture);
  3293. GLES3::Texture *tex = GLES3::TextureStorage::get_singleton()->get_texture(tex_rid);
  3294. {
  3295. tex->tex_id = albedo_alpha_tex;
  3296. Ref<Image> img = GLES3::TextureStorage::get_singleton()->texture_2d_get(tex_rid);
  3297. GLES3::Utilities::get_singleton()->texture_free_data(albedo_alpha_tex);
  3298. ret.push_back(img);
  3299. }
  3300. {
  3301. tex->tex_id = normal_tex;
  3302. Ref<Image> img = GLES3::TextureStorage::get_singleton()->texture_2d_get(tex_rid);
  3303. GLES3::Utilities::get_singleton()->texture_free_data(normal_tex);
  3304. ret.push_back(img);
  3305. }
  3306. {
  3307. tex->tex_id = orm_tex;
  3308. Ref<Image> img = GLES3::TextureStorage::get_singleton()->texture_2d_get(tex_rid);
  3309. GLES3::Utilities::get_singleton()->texture_free_data(orm_tex);
  3310. ret.push_back(img);
  3311. }
  3312. {
  3313. tex->tex_id = emission_tex;
  3314. if (config->float_texture_supported) {
  3315. tex->format = Image::FORMAT_RGBAH;
  3316. tex->real_format = Image::FORMAT_RGBAH;
  3317. tex->gl_type_cache = GL_HALF_FLOAT;
  3318. }
  3319. Ref<Image> img = GLES3::TextureStorage::get_singleton()->texture_2d_get(tex_rid);
  3320. GLES3::Utilities::get_singleton()->texture_free_data(emission_tex);
  3321. ret.push_back(img);
  3322. }
  3323. tex->is_render_target = false;
  3324. tex->tex_id = 0;
  3325. GLES3::TextureStorage::get_singleton()->texture_free(tex_rid);
  3326. GLES3::Utilities::get_singleton()->texture_free_data(depth_tex);
  3327. glDeleteFramebuffers(1, &fbo);
  3328. return ret;
  3329. }
  3330. bool RasterizerSceneGLES3::free(RID p_rid) {
  3331. if (is_environment(p_rid)) {
  3332. environment_free(p_rid);
  3333. } else if (sky_owner.owns(p_rid)) {
  3334. Sky *sky = sky_owner.get_or_null(p_rid);
  3335. ERR_FAIL_NULL_V(sky, false);
  3336. _free_sky_data(sky);
  3337. sky_owner.free(p_rid);
  3338. } else if (GLES3::LightStorage::get_singleton()->owns_light_instance(p_rid)) {
  3339. GLES3::LightStorage::get_singleton()->light_instance_free(p_rid);
  3340. } else if (RSG::camera_attributes->owns_camera_attributes(p_rid)) {
  3341. //not much to delete, just free it
  3342. RSG::camera_attributes->camera_attributes_free(p_rid);
  3343. } else if (is_compositor(p_rid)) {
  3344. compositor_free(p_rid);
  3345. } else if (is_compositor_effect(p_rid)) {
  3346. compositor_effect_free(p_rid);
  3347. } else {
  3348. return false;
  3349. }
  3350. return true;
  3351. }
  3352. void RasterizerSceneGLES3::update() {
  3353. _update_dirty_skys();
  3354. }
  3355. void RasterizerSceneGLES3::sdfgi_set_debug_probe_select(const Vector3 &p_position, const Vector3 &p_dir) {
  3356. }
  3357. void RasterizerSceneGLES3::decals_set_filter(RS::DecalFilter p_filter) {
  3358. }
  3359. void RasterizerSceneGLES3::light_projectors_set_filter(RS::LightProjectorFilter p_filter) {
  3360. }
  3361. void RasterizerSceneGLES3::lightmaps_set_bicubic_filter(bool p_enable) {
  3362. lightmap_bicubic_upscale = p_enable;
  3363. }
  3364. RasterizerSceneGLES3::RasterizerSceneGLES3() {
  3365. singleton = this;
  3366. GLES3::MaterialStorage *material_storage = GLES3::MaterialStorage::get_singleton();
  3367. GLES3::Config *config = GLES3::Config::get_singleton();
  3368. cull_argument.set_page_pool(&cull_argument_pool);
  3369. // Quality settings.
  3370. use_physical_light_units = GLOBAL_GET("rendering/lights_and_shadows/use_physical_light_units");
  3371. positional_soft_shadow_filter_set_quality((RS::ShadowQuality)(int)GLOBAL_GET("rendering/lights_and_shadows/positional_shadow/soft_shadow_filter_quality"));
  3372. directional_soft_shadow_filter_set_quality((RS::ShadowQuality)(int)GLOBAL_GET("rendering/lights_and_shadows/directional_shadow/soft_shadow_filter_quality"));
  3373. lightmaps_set_bicubic_filter(GLOBAL_GET("rendering/lightmapping/lightmap_gi/use_bicubic_filter"));
  3374. {
  3375. // Setup Lights
  3376. config->max_renderable_lights = MIN(config->max_renderable_lights, config->max_uniform_buffer_size / (int)sizeof(RasterizerSceneGLES3::LightData));
  3377. config->max_lights_per_object = MIN(config->max_lights_per_object, config->max_renderable_lights);
  3378. uint32_t light_buffer_size = config->max_renderable_lights * sizeof(LightData);
  3379. scene_state.omni_lights = memnew_arr(LightData, config->max_renderable_lights);
  3380. scene_state.omni_light_sort = memnew_arr(InstanceSort<GLES3::LightInstance>, config->max_renderable_lights);
  3381. glGenBuffers(1, &scene_state.omni_light_buffer);
  3382. glBindBuffer(GL_UNIFORM_BUFFER, scene_state.omni_light_buffer);
  3383. GLES3::Utilities::get_singleton()->buffer_allocate_data(GL_UNIFORM_BUFFER, scene_state.omni_light_buffer, light_buffer_size, nullptr, GL_STREAM_DRAW, "OmniLight UBO");
  3384. scene_state.spot_lights = memnew_arr(LightData, config->max_renderable_lights);
  3385. scene_state.spot_light_sort = memnew_arr(InstanceSort<GLES3::LightInstance>, config->max_renderable_lights);
  3386. glGenBuffers(1, &scene_state.spot_light_buffer);
  3387. glBindBuffer(GL_UNIFORM_BUFFER, scene_state.spot_light_buffer);
  3388. GLES3::Utilities::get_singleton()->buffer_allocate_data(GL_UNIFORM_BUFFER, scene_state.spot_light_buffer, light_buffer_size, nullptr, GL_STREAM_DRAW, "SpotLight UBO");
  3389. uint32_t directional_light_buffer_size = MAX_DIRECTIONAL_LIGHTS * sizeof(DirectionalLightData);
  3390. scene_state.directional_lights = memnew_arr(DirectionalLightData, MAX_DIRECTIONAL_LIGHTS);
  3391. glGenBuffers(1, &scene_state.directional_light_buffer);
  3392. glBindBuffer(GL_UNIFORM_BUFFER, scene_state.directional_light_buffer);
  3393. GLES3::Utilities::get_singleton()->buffer_allocate_data(GL_UNIFORM_BUFFER, scene_state.directional_light_buffer, directional_light_buffer_size, nullptr, GL_STREAM_DRAW, "DirectionalLight UBO");
  3394. uint32_t shadow_buffer_size = config->max_renderable_lights * sizeof(ShadowData) * 2;
  3395. scene_state.positional_shadows = memnew_arr(ShadowData, config->max_renderable_lights * 2);
  3396. glGenBuffers(1, &scene_state.positional_shadow_buffer);
  3397. glBindBuffer(GL_UNIFORM_BUFFER, scene_state.positional_shadow_buffer);
  3398. GLES3::Utilities::get_singleton()->buffer_allocate_data(GL_UNIFORM_BUFFER, scene_state.positional_shadow_buffer, shadow_buffer_size, nullptr, GL_STREAM_DRAW, "Positional Shadow UBO");
  3399. uint32_t directional_shadow_buffer_size = MAX_DIRECTIONAL_LIGHTS * sizeof(DirectionalShadowData);
  3400. scene_state.directional_shadows = memnew_arr(DirectionalShadowData, MAX_DIRECTIONAL_LIGHTS);
  3401. glGenBuffers(1, &scene_state.directional_shadow_buffer);
  3402. glBindBuffer(GL_UNIFORM_BUFFER, scene_state.directional_shadow_buffer);
  3403. GLES3::Utilities::get_singleton()->buffer_allocate_data(GL_UNIFORM_BUFFER, scene_state.directional_shadow_buffer, directional_shadow_buffer_size, nullptr, GL_STREAM_DRAW, "Directional Shadow UBO");
  3404. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  3405. }
  3406. {
  3407. sky_globals.max_directional_lights = 4;
  3408. uint32_t directional_light_buffer_size = sky_globals.max_directional_lights * sizeof(DirectionalLightData);
  3409. sky_globals.directional_lights = memnew_arr(DirectionalLightData, sky_globals.max_directional_lights);
  3410. sky_globals.last_frame_directional_lights = memnew_arr(DirectionalLightData, sky_globals.max_directional_lights);
  3411. sky_globals.last_frame_directional_light_count = sky_globals.max_directional_lights + 1;
  3412. glGenBuffers(1, &sky_globals.directional_light_buffer);
  3413. glBindBuffer(GL_UNIFORM_BUFFER, sky_globals.directional_light_buffer);
  3414. GLES3::Utilities::get_singleton()->buffer_allocate_data(GL_UNIFORM_BUFFER, sky_globals.directional_light_buffer, directional_light_buffer_size, nullptr, GL_STREAM_DRAW, "Sky DirectionalLight UBO");
  3415. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  3416. }
  3417. {
  3418. String global_defines;
  3419. global_defines += "#define MAX_GLOBAL_SHADER_UNIFORMS 256\n"; // TODO: this is arbitrary for now
  3420. global_defines += "\n#define MAX_LIGHT_DATA_STRUCTS " + itos(config->max_renderable_lights) + "\n";
  3421. global_defines += "\n#define MAX_DIRECTIONAL_LIGHT_DATA_STRUCTS " + itos(MAX_DIRECTIONAL_LIGHTS) + "\n";
  3422. global_defines += "\n#define MAX_FORWARD_LIGHTS " + itos(config->max_lights_per_object) + "u\n";
  3423. global_defines += "\n#define MAX_ROUGHNESS_LOD " + itos(sky_globals.roughness_layers - 1) + ".0\n";
  3424. if (config->force_vertex_shading) {
  3425. global_defines += "\n#define USE_VERTEX_LIGHTING\n";
  3426. }
  3427. material_storage->shaders.scene_shader.initialize(global_defines);
  3428. scene_globals.shader_default_version = material_storage->shaders.scene_shader.version_create();
  3429. material_storage->shaders.scene_shader.version_bind_shader(scene_globals.shader_default_version, SceneShaderGLES3::MODE_COLOR);
  3430. }
  3431. {
  3432. //default material and shader
  3433. scene_globals.default_shader = material_storage->shader_allocate();
  3434. material_storage->shader_initialize(scene_globals.default_shader);
  3435. material_storage->shader_set_code(scene_globals.default_shader, R"(
  3436. // Default 3D material shader (Compatibility).
  3437. shader_type spatial;
  3438. void vertex() {
  3439. ROUGHNESS = 0.8;
  3440. }
  3441. void fragment() {
  3442. ALBEDO = vec3(0.6);
  3443. ROUGHNESS = 0.8;
  3444. METALLIC = 0.2;
  3445. }
  3446. )");
  3447. scene_globals.default_material = material_storage->material_allocate();
  3448. material_storage->material_initialize(scene_globals.default_material);
  3449. material_storage->material_set_shader(scene_globals.default_material, scene_globals.default_shader);
  3450. default_material_data_ptr = static_cast<GLES3::SceneMaterialData *>(GLES3::MaterialStorage::get_singleton()->material_get_data(scene_globals.default_material, RS::SHADER_SPATIAL));
  3451. }
  3452. {
  3453. // Overdraw material and shader.
  3454. scene_globals.overdraw_shader = material_storage->shader_allocate();
  3455. material_storage->shader_initialize(scene_globals.overdraw_shader);
  3456. material_storage->shader_set_code(scene_globals.overdraw_shader, R"(
  3457. // 3D editor Overdraw debug draw mode shader (Compatibility).
  3458. shader_type spatial;
  3459. render_mode blend_add, unshaded, fog_disabled;
  3460. void fragment() {
  3461. ALBEDO = vec3(0.4, 0.8, 0.8);
  3462. ALPHA = 0.2;
  3463. }
  3464. )");
  3465. scene_globals.overdraw_material = material_storage->material_allocate();
  3466. material_storage->material_initialize(scene_globals.overdraw_material);
  3467. material_storage->material_set_shader(scene_globals.overdraw_material, scene_globals.overdraw_shader);
  3468. overdraw_material_data_ptr = static_cast<GLES3::SceneMaterialData *>(GLES3::MaterialStorage::get_singleton()->material_get_data(scene_globals.overdraw_material, RS::SHADER_SPATIAL));
  3469. }
  3470. {
  3471. // Initialize Sky stuff
  3472. sky_globals.roughness_layers = GLOBAL_GET("rendering/reflections/sky_reflections/roughness_layers");
  3473. String global_defines;
  3474. global_defines += "#define MAX_GLOBAL_SHADER_UNIFORMS 256\n"; // TODO: this is arbitrary for now
  3475. global_defines += "\n#define MAX_DIRECTIONAL_LIGHT_DATA_STRUCTS " + itos(sky_globals.max_directional_lights) + "\n";
  3476. material_storage->shaders.sky_shader.initialize(global_defines);
  3477. sky_globals.shader_default_version = material_storage->shaders.sky_shader.version_create();
  3478. }
  3479. {
  3480. sky_globals.default_shader = material_storage->shader_allocate();
  3481. material_storage->shader_initialize(sky_globals.default_shader);
  3482. material_storage->shader_set_code(sky_globals.default_shader, R"(
  3483. // Default sky shader.
  3484. shader_type sky;
  3485. void sky() {
  3486. COLOR = vec3(0.0);
  3487. }
  3488. )");
  3489. sky_globals.default_material = material_storage->material_allocate();
  3490. material_storage->material_initialize(sky_globals.default_material);
  3491. material_storage->material_set_shader(sky_globals.default_material, sky_globals.default_shader);
  3492. }
  3493. {
  3494. sky_globals.fog_shader = material_storage->shader_allocate();
  3495. material_storage->shader_initialize(sky_globals.fog_shader);
  3496. material_storage->shader_set_code(sky_globals.fog_shader, R"(
  3497. // Default clear color sky shader.
  3498. shader_type sky;
  3499. uniform vec4 clear_color;
  3500. void sky() {
  3501. COLOR = clear_color.rgb;
  3502. }
  3503. )");
  3504. sky_globals.fog_material = material_storage->material_allocate();
  3505. material_storage->material_initialize(sky_globals.fog_material);
  3506. material_storage->material_set_shader(sky_globals.fog_material, sky_globals.fog_shader);
  3507. }
  3508. {
  3509. glGenVertexArrays(1, &sky_globals.screen_triangle_array);
  3510. glBindVertexArray(sky_globals.screen_triangle_array);
  3511. glGenBuffers(1, &sky_globals.screen_triangle);
  3512. glBindBuffer(GL_ARRAY_BUFFER, sky_globals.screen_triangle);
  3513. const float qv[6] = {
  3514. -1.0f,
  3515. -1.0f,
  3516. 3.0f,
  3517. -1.0f,
  3518. -1.0f,
  3519. 3.0f,
  3520. };
  3521. GLES3::Utilities::get_singleton()->buffer_allocate_data(GL_ARRAY_BUFFER, sky_globals.screen_triangle, sizeof(float) * 6, qv, GL_STATIC_DRAW, "Screen triangle vertex buffer");
  3522. glVertexAttribPointer(RS::ARRAY_VERTEX, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 2, nullptr);
  3523. glEnableVertexAttribArray(RS::ARRAY_VERTEX);
  3524. glBindVertexArray(0);
  3525. glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind
  3526. }
  3527. #ifdef GL_API_ENABLED
  3528. if (RasterizerGLES3::is_gles_over_gl()) {
  3529. glEnable(_EXT_TEXTURE_CUBE_MAP_SEAMLESS);
  3530. }
  3531. #endif // GL_API_ENABLED
  3532. // MultiMesh may read from color when color is disabled, so make sure that the color defaults to white instead of black;
  3533. glVertexAttrib4f(RS::ARRAY_COLOR, 1.0, 1.0, 1.0, 1.0);
  3534. }
  3535. RasterizerSceneGLES3::~RasterizerSceneGLES3() {
  3536. GLES3::Utilities::get_singleton()->buffer_free_data(scene_state.directional_light_buffer);
  3537. GLES3::Utilities::get_singleton()->buffer_free_data(scene_state.omni_light_buffer);
  3538. GLES3::Utilities::get_singleton()->buffer_free_data(scene_state.spot_light_buffer);
  3539. GLES3::Utilities::get_singleton()->buffer_free_data(scene_state.positional_shadow_buffer);
  3540. GLES3::Utilities::get_singleton()->buffer_free_data(scene_state.directional_shadow_buffer);
  3541. memdelete_arr(scene_state.directional_lights);
  3542. memdelete_arr(scene_state.omni_lights);
  3543. memdelete_arr(scene_state.spot_lights);
  3544. memdelete_arr(scene_state.omni_light_sort);
  3545. memdelete_arr(scene_state.spot_light_sort);
  3546. memdelete_arr(scene_state.positional_shadows);
  3547. memdelete_arr(scene_state.directional_shadows);
  3548. // Scene Shader
  3549. GLES3::MaterialStorage::get_singleton()->shaders.scene_shader.version_free(scene_globals.shader_default_version);
  3550. RSG::material_storage->material_free(scene_globals.default_material);
  3551. RSG::material_storage->shader_free(scene_globals.default_shader);
  3552. // Overdraw Shader
  3553. RSG::material_storage->material_free(scene_globals.overdraw_material);
  3554. RSG::material_storage->shader_free(scene_globals.overdraw_shader);
  3555. // Sky Shader
  3556. GLES3::MaterialStorage::get_singleton()->shaders.sky_shader.version_free(sky_globals.shader_default_version);
  3557. RSG::material_storage->material_free(sky_globals.default_material);
  3558. RSG::material_storage->shader_free(sky_globals.default_shader);
  3559. RSG::material_storage->material_free(sky_globals.fog_material);
  3560. RSG::material_storage->shader_free(sky_globals.fog_shader);
  3561. GLES3::Utilities::get_singleton()->buffer_free_data(sky_globals.screen_triangle);
  3562. glDeleteVertexArrays(1, &sky_globals.screen_triangle_array);
  3563. GLES3::Utilities::get_singleton()->buffer_free_data(sky_globals.directional_light_buffer);
  3564. memdelete_arr(sky_globals.directional_lights);
  3565. memdelete_arr(sky_globals.last_frame_directional_lights);
  3566. // UBOs
  3567. if (scene_state.ubo_buffer != 0) {
  3568. GLES3::Utilities::get_singleton()->buffer_free_data(scene_state.ubo_buffer);
  3569. }
  3570. if (scene_state.multiview_buffer != 0) {
  3571. GLES3::Utilities::get_singleton()->buffer_free_data(scene_state.multiview_buffer);
  3572. }
  3573. if (scene_state.tonemap_buffer != 0) {
  3574. GLES3::Utilities::get_singleton()->buffer_free_data(scene_state.tonemap_buffer);
  3575. }
  3576. singleton = nullptr;
  3577. }
  3578. #endif // GLES3_ENABLED