rasterizer_scene_gles3.cpp 149 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610
  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 "rasterizer_gles3.h"
  33. #include "storage/config.h"
  34. #include "storage/mesh_storage.h"
  35. #include "storage/particles_storage.h"
  36. #include "storage/texture_storage.h"
  37. #include "core/config/project_settings.h"
  38. #include "core/templates/sort_array.h"
  39. #include "servers/rendering/rendering_server_default.h"
  40. #include "servers/rendering/rendering_server_globals.h"
  41. #ifdef GLES3_ENABLED
  42. RasterizerSceneGLES3 *RasterizerSceneGLES3::singleton = nullptr;
  43. RenderGeometryInstance *RasterizerSceneGLES3::geometry_instance_create(RID p_base) {
  44. RS::InstanceType type = RSG::utilities->get_base_type(p_base);
  45. ERR_FAIL_COND_V(!((1 << type) & RS::INSTANCE_GEOMETRY_MASK), nullptr);
  46. GeometryInstanceGLES3 *ginstance = geometry_instance_alloc.alloc();
  47. ginstance->data = memnew(GeometryInstanceGLES3::Data);
  48. ginstance->data->base = p_base;
  49. ginstance->data->base_type = type;
  50. ginstance->data->dependency_tracker.userdata = ginstance;
  51. ginstance->data->dependency_tracker.changed_callback = _geometry_instance_dependency_changed;
  52. ginstance->data->dependency_tracker.deleted_callback = _geometry_instance_dependency_deleted;
  53. ginstance->_mark_dirty();
  54. return ginstance;
  55. }
  56. uint32_t RasterizerSceneGLES3::geometry_instance_get_pair_mask() {
  57. return (1 << RS::INSTANCE_LIGHT);
  58. }
  59. void RasterizerSceneGLES3::GeometryInstanceGLES3::pair_light_instances(const RID *p_light_instances, uint32_t p_light_instance_count) {
  60. GLES3::Config *config = GLES3::Config::get_singleton();
  61. paired_omni_light_count = 0;
  62. paired_spot_light_count = 0;
  63. paired_omni_lights.clear();
  64. paired_spot_lights.clear();
  65. for (uint32_t i = 0; i < p_light_instance_count; i++) {
  66. RS::LightType type = GLES3::LightStorage::get_singleton()->light_instance_get_type(p_light_instances[i]);
  67. switch (type) {
  68. case RS::LIGHT_OMNI: {
  69. if (paired_omni_light_count < (uint32_t)config->max_lights_per_object) {
  70. paired_omni_lights.push_back(p_light_instances[i]);
  71. paired_omni_light_count++;
  72. }
  73. } break;
  74. case RS::LIGHT_SPOT: {
  75. if (paired_spot_light_count < (uint32_t)config->max_lights_per_object) {
  76. paired_spot_lights.push_back(p_light_instances[i]);
  77. paired_spot_light_count++;
  78. }
  79. } break;
  80. default:
  81. break;
  82. }
  83. }
  84. }
  85. void RasterizerSceneGLES3::geometry_instance_free(RenderGeometryInstance *p_geometry_instance) {
  86. GeometryInstanceGLES3 *ginstance = static_cast<GeometryInstanceGLES3 *>(p_geometry_instance);
  87. ERR_FAIL_NULL(ginstance);
  88. GeometryInstanceSurface *surf = ginstance->surface_caches;
  89. while (surf) {
  90. GeometryInstanceSurface *next = surf->next;
  91. geometry_instance_surface_alloc.free(surf);
  92. surf = next;
  93. }
  94. memdelete(ginstance->data);
  95. geometry_instance_alloc.free(ginstance);
  96. }
  97. void RasterizerSceneGLES3::GeometryInstanceGLES3::_mark_dirty() {
  98. if (dirty_list_element.in_list()) {
  99. return;
  100. }
  101. //clear surface caches
  102. GeometryInstanceSurface *surf = surface_caches;
  103. while (surf) {
  104. GeometryInstanceSurface *next = surf->next;
  105. RasterizerSceneGLES3::get_singleton()->geometry_instance_surface_alloc.free(surf);
  106. surf = next;
  107. }
  108. surface_caches = nullptr;
  109. RasterizerSceneGLES3::get_singleton()->geometry_instance_dirty_list.add(&dirty_list_element);
  110. }
  111. void RasterizerSceneGLES3::GeometryInstanceGLES3::set_use_lightmap(RID p_lightmap_instance, const Rect2 &p_lightmap_uv_scale, int p_lightmap_slice_index) {
  112. }
  113. void RasterizerSceneGLES3::GeometryInstanceGLES3::set_lightmap_capture(const Color *p_sh9) {
  114. }
  115. void RasterizerSceneGLES3::_update_dirty_geometry_instances() {
  116. while (geometry_instance_dirty_list.first()) {
  117. _geometry_instance_update(geometry_instance_dirty_list.first()->self());
  118. }
  119. }
  120. void RasterizerSceneGLES3::_geometry_instance_dependency_changed(Dependency::DependencyChangedNotification p_notification, DependencyTracker *p_tracker) {
  121. switch (p_notification) {
  122. case Dependency::DEPENDENCY_CHANGED_MATERIAL:
  123. case Dependency::DEPENDENCY_CHANGED_MESH:
  124. case Dependency::DEPENDENCY_CHANGED_PARTICLES:
  125. case Dependency::DEPENDENCY_CHANGED_MULTIMESH:
  126. case Dependency::DEPENDENCY_CHANGED_SKELETON_DATA: {
  127. static_cast<RenderGeometryInstance *>(p_tracker->userdata)->_mark_dirty();
  128. static_cast<GeometryInstanceGLES3 *>(p_tracker->userdata)->data->dirty_dependencies = true;
  129. } break;
  130. case Dependency::DEPENDENCY_CHANGED_MULTIMESH_VISIBLE_INSTANCES: {
  131. GeometryInstanceGLES3 *ginstance = static_cast<GeometryInstanceGLES3 *>(p_tracker->userdata);
  132. if (ginstance->data->base_type == RS::INSTANCE_MULTIMESH) {
  133. ginstance->instance_count = GLES3::MeshStorage::get_singleton()->multimesh_get_instances_to_draw(ginstance->data->base);
  134. }
  135. } break;
  136. default: {
  137. //rest of notifications of no interest
  138. } break;
  139. }
  140. }
  141. void RasterizerSceneGLES3::_geometry_instance_dependency_deleted(const RID &p_dependency, DependencyTracker *p_tracker) {
  142. static_cast<RenderGeometryInstance *>(p_tracker->userdata)->_mark_dirty();
  143. static_cast<GeometryInstanceGLES3 *>(p_tracker->userdata)->data->dirty_dependencies = true;
  144. }
  145. 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) {
  146. GLES3::MeshStorage *mesh_storage = GLES3::MeshStorage::get_singleton();
  147. 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;
  148. bool has_base_alpha = ((p_material->shader_data->uses_alpha && !p_material->shader_data->uses_alpha_clip) || has_read_screen_alpha);
  149. bool has_blend_alpha = p_material->shader_data->uses_blend_alpha;
  150. bool has_alpha = has_base_alpha || has_blend_alpha;
  151. uint32_t flags = 0;
  152. if (p_material->shader_data->uses_screen_texture) {
  153. flags |= GeometryInstanceSurface::FLAG_USES_SCREEN_TEXTURE;
  154. }
  155. if (p_material->shader_data->uses_depth_texture) {
  156. flags |= GeometryInstanceSurface::FLAG_USES_DEPTH_TEXTURE;
  157. }
  158. if (p_material->shader_data->uses_normal_texture) {
  159. flags |= GeometryInstanceSurface::FLAG_USES_NORMAL_TEXTURE;
  160. }
  161. if (ginstance->data->cast_double_sided_shadows) {
  162. flags |= GeometryInstanceSurface::FLAG_USES_DOUBLE_SIDED_SHADOWS;
  163. }
  164. 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) {
  165. //material is only meant for alpha pass
  166. flags |= GeometryInstanceSurface::FLAG_PASS_ALPHA;
  167. 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)) {
  168. flags |= GeometryInstanceSurface::FLAG_PASS_DEPTH;
  169. flags |= GeometryInstanceSurface::FLAG_PASS_SHADOW;
  170. }
  171. } else {
  172. flags |= GeometryInstanceSurface::FLAG_PASS_OPAQUE;
  173. flags |= GeometryInstanceSurface::FLAG_PASS_DEPTH;
  174. flags |= GeometryInstanceSurface::FLAG_PASS_SHADOW;
  175. }
  176. GLES3::SceneMaterialData *material_shadow = nullptr;
  177. void *surface_shadow = nullptr;
  178. 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) {
  179. flags |= GeometryInstanceSurface::FLAG_USES_SHARED_SHADOW_MATERIAL;
  180. material_shadow = static_cast<GLES3::SceneMaterialData *>(GLES3::MaterialStorage::get_singleton()->material_get_data(scene_globals.default_material, RS::SHADER_SPATIAL));
  181. RID shadow_mesh = mesh_storage->mesh_get_shadow_mesh(p_mesh);
  182. if (shadow_mesh.is_valid()) {
  183. surface_shadow = mesh_storage->mesh_get_surface(shadow_mesh, p_surface);
  184. }
  185. } else {
  186. material_shadow = p_material;
  187. }
  188. GeometryInstanceSurface *sdcache = geometry_instance_surface_alloc.alloc();
  189. sdcache->flags = flags;
  190. sdcache->shader = p_material->shader_data;
  191. sdcache->material = p_material;
  192. sdcache->surface = mesh_storage->mesh_get_surface(p_mesh, p_surface);
  193. sdcache->primitive = mesh_storage->mesh_surface_get_primitive(sdcache->surface);
  194. sdcache->surface_index = p_surface;
  195. if (ginstance->data->dirty_dependencies) {
  196. RSG::utilities->base_update_dependency(p_mesh, &ginstance->data->dependency_tracker);
  197. }
  198. //shadow
  199. sdcache->shader_shadow = material_shadow->shader_data;
  200. sdcache->material_shadow = material_shadow;
  201. sdcache->surface_shadow = surface_shadow ? surface_shadow : sdcache->surface;
  202. sdcache->owner = ginstance;
  203. sdcache->next = ginstance->surface_caches;
  204. ginstance->surface_caches = sdcache;
  205. //sortkey
  206. sdcache->sort.sort_key1 = 0;
  207. sdcache->sort.sort_key2 = 0;
  208. sdcache->sort.surface_index = p_surface;
  209. sdcache->sort.material_id_low = p_material_id & 0x0000FFFF;
  210. sdcache->sort.material_id_hi = p_material_id >> 16;
  211. sdcache->sort.shader_id = p_shader_id;
  212. sdcache->sort.geometry_id = p_mesh.get_local_index();
  213. sdcache->sort.priority = p_material->priority;
  214. GLES3::Mesh::Surface *s = reinterpret_cast<GLES3::Mesh::Surface *>(sdcache->surface);
  215. if (p_material->shader_data->uses_tangent && !(s->format & RS::ARRAY_FORMAT_TANGENT)) {
  216. String shader_path = p_material->shader_data->path.is_empty() ? "" : "(" + p_material->shader_data->path + ")";
  217. String mesh_path = mesh_storage->mesh_get_path(p_mesh).is_empty() ? "" : "(" + mesh_storage->mesh_get_path(p_mesh) + ")";
  218. 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));
  219. }
  220. }
  221. 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) {
  222. GLES3::SceneMaterialData *material_data = p_material_data;
  223. GLES3::MaterialStorage *material_storage = GLES3::MaterialStorage::get_singleton();
  224. _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);
  225. while (material_data->next_pass.is_valid()) {
  226. RID next_pass = material_data->next_pass;
  227. material_data = static_cast<GLES3::SceneMaterialData *>(material_storage->material_get_data(next_pass, RS::SHADER_SPATIAL));
  228. if (!material_data || !material_data->shader_data->valid) {
  229. break;
  230. }
  231. if (ginstance->data->dirty_dependencies) {
  232. material_storage->material_update_dependency(next_pass, &ginstance->data->dependency_tracker);
  233. }
  234. _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);
  235. }
  236. }
  237. void RasterizerSceneGLES3::_geometry_instance_add_surface(GeometryInstanceGLES3 *ginstance, uint32_t p_surface, RID p_material, RID p_mesh) {
  238. GLES3::MaterialStorage *material_storage = GLES3::MaterialStorage::get_singleton();
  239. RID m_src;
  240. m_src = ginstance->data->material_override.is_valid() ? ginstance->data->material_override : p_material;
  241. GLES3::SceneMaterialData *material_data = nullptr;
  242. if (m_src.is_valid()) {
  243. material_data = static_cast<GLES3::SceneMaterialData *>(material_storage->material_get_data(m_src, RS::SHADER_SPATIAL));
  244. if (!material_data || !material_data->shader_data->valid) {
  245. material_data = nullptr;
  246. }
  247. }
  248. if (material_data) {
  249. if (ginstance->data->dirty_dependencies) {
  250. material_storage->material_update_dependency(m_src, &ginstance->data->dependency_tracker);
  251. }
  252. } else {
  253. material_data = static_cast<GLES3::SceneMaterialData *>(material_storage->material_get_data(scene_globals.default_material, RS::SHADER_SPATIAL));
  254. m_src = scene_globals.default_material;
  255. }
  256. ERR_FAIL_NULL(material_data);
  257. _geometry_instance_add_surface_with_material_chain(ginstance, p_surface, material_data, m_src, p_mesh);
  258. if (ginstance->data->material_overlay.is_valid()) {
  259. m_src = ginstance->data->material_overlay;
  260. material_data = static_cast<GLES3::SceneMaterialData *>(material_storage->material_get_data(m_src, RS::SHADER_SPATIAL));
  261. if (material_data && material_data->shader_data->valid) {
  262. if (ginstance->data->dirty_dependencies) {
  263. material_storage->material_update_dependency(m_src, &ginstance->data->dependency_tracker);
  264. }
  265. _geometry_instance_add_surface_with_material_chain(ginstance, p_surface, material_data, m_src, p_mesh);
  266. }
  267. }
  268. }
  269. void RasterizerSceneGLES3::_geometry_instance_update(RenderGeometryInstance *p_geometry_instance) {
  270. GLES3::MeshStorage *mesh_storage = GLES3::MeshStorage::get_singleton();
  271. GLES3::ParticlesStorage *particles_storage = GLES3::ParticlesStorage::get_singleton();
  272. GeometryInstanceGLES3 *ginstance = static_cast<GeometryInstanceGLES3 *>(p_geometry_instance);
  273. if (ginstance->data->dirty_dependencies) {
  274. ginstance->data->dependency_tracker.update_begin();
  275. }
  276. //add geometry for drawing
  277. switch (ginstance->data->base_type) {
  278. case RS::INSTANCE_MESH: {
  279. const RID *materials = nullptr;
  280. uint32_t surface_count;
  281. RID mesh = ginstance->data->base;
  282. materials = mesh_storage->mesh_get_surface_count_and_materials(mesh, surface_count);
  283. if (materials) {
  284. //if no materials, no surfaces.
  285. const RID *inst_materials = ginstance->data->surface_materials.ptr();
  286. uint32_t surf_mat_count = ginstance->data->surface_materials.size();
  287. for (uint32_t j = 0; j < surface_count; j++) {
  288. RID material = (j < surf_mat_count && inst_materials[j].is_valid()) ? inst_materials[j] : materials[j];
  289. _geometry_instance_add_surface(ginstance, j, material, mesh);
  290. }
  291. }
  292. ginstance->instance_count = -1;
  293. } break;
  294. case RS::INSTANCE_MULTIMESH: {
  295. RID mesh = mesh_storage->multimesh_get_mesh(ginstance->data->base);
  296. if (mesh.is_valid()) {
  297. const RID *materials = nullptr;
  298. uint32_t surface_count;
  299. materials = mesh_storage->mesh_get_surface_count_and_materials(mesh, surface_count);
  300. if (materials) {
  301. for (uint32_t j = 0; j < surface_count; j++) {
  302. _geometry_instance_add_surface(ginstance, j, materials[j], mesh);
  303. }
  304. }
  305. ginstance->instance_count = mesh_storage->multimesh_get_instances_to_draw(ginstance->data->base);
  306. }
  307. } break;
  308. case RS::INSTANCE_PARTICLES: {
  309. int draw_passes = particles_storage->particles_get_draw_passes(ginstance->data->base);
  310. for (int j = 0; j < draw_passes; j++) {
  311. RID mesh = particles_storage->particles_get_draw_pass_mesh(ginstance->data->base, j);
  312. if (!mesh.is_valid()) {
  313. continue;
  314. }
  315. const RID *materials = nullptr;
  316. uint32_t surface_count;
  317. materials = mesh_storage->mesh_get_surface_count_and_materials(mesh, surface_count);
  318. if (materials) {
  319. for (uint32_t k = 0; k < surface_count; k++) {
  320. _geometry_instance_add_surface(ginstance, k, materials[k], mesh);
  321. }
  322. }
  323. }
  324. ginstance->instance_count = particles_storage->particles_get_amount(ginstance->data->base);
  325. } break;
  326. default: {
  327. }
  328. }
  329. bool store_transform = true;
  330. ginstance->base_flags = 0;
  331. if (ginstance->data->base_type == RS::INSTANCE_MULTIMESH) {
  332. ginstance->base_flags |= INSTANCE_DATA_FLAG_MULTIMESH;
  333. if (mesh_storage->multimesh_get_transform_format(ginstance->data->base) == RS::MULTIMESH_TRANSFORM_2D) {
  334. ginstance->base_flags |= INSTANCE_DATA_FLAG_MULTIMESH_FORMAT_2D;
  335. }
  336. if (mesh_storage->multimesh_uses_colors(ginstance->data->base)) {
  337. ginstance->base_flags |= INSTANCE_DATA_FLAG_MULTIMESH_HAS_COLOR;
  338. }
  339. if (mesh_storage->multimesh_uses_custom_data(ginstance->data->base)) {
  340. ginstance->base_flags |= INSTANCE_DATA_FLAG_MULTIMESH_HAS_CUSTOM_DATA;
  341. }
  342. } else if (ginstance->data->base_type == RS::INSTANCE_PARTICLES) {
  343. ginstance->base_flags |= INSTANCE_DATA_FLAG_PARTICLES;
  344. ginstance->base_flags |= INSTANCE_DATA_FLAG_MULTIMESH;
  345. ginstance->base_flags |= INSTANCE_DATA_FLAG_MULTIMESH_HAS_COLOR;
  346. ginstance->base_flags |= INSTANCE_DATA_FLAG_MULTIMESH_HAS_CUSTOM_DATA;
  347. if (!particles_storage->particles_is_using_local_coords(ginstance->data->base)) {
  348. store_transform = false;
  349. }
  350. } else if (ginstance->data->base_type == RS::INSTANCE_MESH) {
  351. if (mesh_storage->skeleton_is_valid(ginstance->data->skeleton)) {
  352. if (ginstance->data->dirty_dependencies) {
  353. mesh_storage->skeleton_update_dependency(ginstance->data->skeleton, &ginstance->data->dependency_tracker);
  354. }
  355. }
  356. }
  357. ginstance->store_transform_cache = store_transform;
  358. if (ginstance->data->dirty_dependencies) {
  359. ginstance->data->dependency_tracker.update_end();
  360. ginstance->data->dirty_dependencies = false;
  361. }
  362. ginstance->dirty_list_element.remove_from_list();
  363. }
  364. /* SKY API */
  365. void RasterizerSceneGLES3::_free_sky_data(Sky *p_sky) {
  366. if (p_sky->radiance != 0) {
  367. GLES3::Utilities::get_singleton()->texture_free_data(p_sky->radiance);
  368. p_sky->radiance = 0;
  369. GLES3::Utilities::get_singleton()->texture_free_data(p_sky->raw_radiance);
  370. p_sky->raw_radiance = 0;
  371. glDeleteFramebuffers(1, &p_sky->radiance_framebuffer);
  372. p_sky->radiance_framebuffer = 0;
  373. }
  374. }
  375. RID RasterizerSceneGLES3::sky_allocate() {
  376. return sky_owner.allocate_rid();
  377. }
  378. void RasterizerSceneGLES3::sky_initialize(RID p_rid) {
  379. sky_owner.initialize_rid(p_rid);
  380. }
  381. void RasterizerSceneGLES3::sky_set_radiance_size(RID p_sky, int p_radiance_size) {
  382. Sky *sky = sky_owner.get_or_null(p_sky);
  383. ERR_FAIL_NULL(sky);
  384. ERR_FAIL_COND_MSG(p_radiance_size < 32 || p_radiance_size > 2048, "Sky radiance size must be between 32 and 2048");
  385. if (sky->radiance_size == p_radiance_size) {
  386. return; // No need to update
  387. }
  388. sky->radiance_size = p_radiance_size;
  389. _free_sky_data(sky);
  390. _invalidate_sky(sky);
  391. }
  392. void RasterizerSceneGLES3::sky_set_mode(RID p_sky, RS::SkyMode p_mode) {
  393. Sky *sky = sky_owner.get_or_null(p_sky);
  394. ERR_FAIL_NULL(sky);
  395. if (sky->mode == p_mode) {
  396. return;
  397. }
  398. sky->mode = p_mode;
  399. _invalidate_sky(sky);
  400. }
  401. void RasterizerSceneGLES3::sky_set_material(RID p_sky, RID p_material) {
  402. Sky *sky = sky_owner.get_or_null(p_sky);
  403. ERR_FAIL_NULL(sky);
  404. if (sky->material == p_material) {
  405. return;
  406. }
  407. sky->material = p_material;
  408. _invalidate_sky(sky);
  409. }
  410. float RasterizerSceneGLES3::sky_get_baked_exposure(RID p_sky) const {
  411. Sky *sky = sky_owner.get_or_null(p_sky);
  412. ERR_FAIL_NULL_V(sky, 1.0);
  413. return sky->baked_exposure;
  414. }
  415. void RasterizerSceneGLES3::_invalidate_sky(Sky *p_sky) {
  416. if (!p_sky->dirty) {
  417. p_sky->dirty = true;
  418. p_sky->dirty_list = dirty_sky_list;
  419. dirty_sky_list = p_sky;
  420. }
  421. }
  422. void RasterizerSceneGLES3::_update_dirty_skys() {
  423. Sky *sky = dirty_sky_list;
  424. while (sky) {
  425. if (sky->radiance == 0) {
  426. sky->mipmap_count = Image::get_image_required_mipmaps(sky->radiance_size, sky->radiance_size, Image::FORMAT_RGBA8) - 1;
  427. // Left uninitialized, will attach a texture at render time
  428. glGenFramebuffers(1, &sky->radiance_framebuffer);
  429. GLenum internal_format = GL_RGB10_A2;
  430. glGenTextures(1, &sky->radiance);
  431. glBindTexture(GL_TEXTURE_CUBE_MAP, sky->radiance);
  432. #ifdef GL_API_ENABLED
  433. if (RasterizerGLES3::is_gles_over_gl()) {
  434. GLenum format = GL_RGBA;
  435. GLenum type = GL_UNSIGNED_INT_2_10_10_10_REV;
  436. //TODO, on low-end compare this to allocating each face of each mip individually
  437. // see: https://www.khronos.org/registry/OpenGL-Refpages/es3.0/html/glTexStorage2D.xhtml
  438. for (int i = 0; i < 6; i++) {
  439. glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, internal_format, sky->radiance_size, sky->radiance_size, 0, format, type, nullptr);
  440. }
  441. glGenerateMipmap(GL_TEXTURE_CUBE_MAP);
  442. }
  443. #endif // GL_API_ENABLED
  444. #ifdef GLES_API_ENABLED
  445. if (!RasterizerGLES3::is_gles_over_gl()) {
  446. glTexStorage2D(GL_TEXTURE_CUBE_MAP, sky->mipmap_count, internal_format, sky->radiance_size, sky->radiance_size);
  447. }
  448. #endif // GLES_API_ENABLED
  449. glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
  450. glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  451. glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  452. glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  453. glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_BASE_LEVEL, 0);
  454. glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAX_LEVEL, sky->mipmap_count - 1);
  455. GLES3::Utilities::get_singleton()->texture_allocated_data(sky->radiance, Image::get_image_data_size(sky->radiance_size, sky->radiance_size, Image::FORMAT_RGBA8, true), "Sky radiance map");
  456. glGenTextures(1, &sky->raw_radiance);
  457. glBindTexture(GL_TEXTURE_CUBE_MAP, sky->raw_radiance);
  458. #ifdef GL_API_ENABLED
  459. if (RasterizerGLES3::is_gles_over_gl()) {
  460. GLenum format = GL_RGBA;
  461. GLenum type = GL_UNSIGNED_INT_2_10_10_10_REV;
  462. //TODO, on low-end compare this to allocating each face of each mip individually
  463. // see: https://www.khronos.org/registry/OpenGL-Refpages/es3.0/html/glTexStorage2D.xhtml
  464. for (int i = 0; i < 6; i++) {
  465. glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, internal_format, sky->radiance_size, sky->radiance_size, 0, format, type, nullptr);
  466. }
  467. glGenerateMipmap(GL_TEXTURE_CUBE_MAP);
  468. }
  469. #endif // GL_API_ENABLED
  470. #ifdef GLES_API_ENABLED
  471. if (!RasterizerGLES3::is_gles_over_gl()) {
  472. glTexStorage2D(GL_TEXTURE_CUBE_MAP, sky->mipmap_count, internal_format, sky->radiance_size, sky->radiance_size);
  473. }
  474. #endif // GLES_API_ENABLED
  475. glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
  476. glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  477. glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  478. glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  479. glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_BASE_LEVEL, 0);
  480. glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAX_LEVEL, sky->mipmap_count - 1);
  481. glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
  482. GLES3::Utilities::get_singleton()->texture_allocated_data(sky->raw_radiance, Image::get_image_data_size(sky->radiance_size, sky->radiance_size, Image::FORMAT_RGBA8, true), "Sky raw radiance map");
  483. }
  484. sky->reflection_dirty = true;
  485. sky->processing_layer = 0;
  486. Sky *next = sky->dirty_list;
  487. sky->dirty_list = nullptr;
  488. sky->dirty = false;
  489. sky = next;
  490. }
  491. dirty_sky_list = nullptr;
  492. }
  493. 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) {
  494. GLES3::LightStorage *light_storage = GLES3::LightStorage::get_singleton();
  495. GLES3::MaterialStorage *material_storage = GLES3::MaterialStorage::get_singleton();
  496. ERR_FAIL_COND(p_render_data->environment.is_null());
  497. GLES3::SkyMaterialData *material = nullptr;
  498. Sky *sky = sky_owner.get_or_null(environment_get_sky(p_render_data->environment));
  499. RID sky_material;
  500. GLES3::SkyShaderData *shader_data = nullptr;
  501. if (sky) {
  502. sky_material = sky->material;
  503. if (sky_material.is_valid()) {
  504. material = static_cast<GLES3::SkyMaterialData *>(material_storage->material_get_data(sky_material, RS::SHADER_SKY));
  505. if (!material || !material->shader_data->valid) {
  506. material = nullptr;
  507. }
  508. }
  509. }
  510. if (!material) {
  511. sky_material = sky_globals.default_material;
  512. material = static_cast<GLES3::SkyMaterialData *>(material_storage->material_get_data(sky_material, RS::SHADER_SKY));
  513. }
  514. ERR_FAIL_NULL(material);
  515. shader_data = material->shader_data;
  516. ERR_FAIL_NULL(shader_data);
  517. if (sky) {
  518. if (shader_data->uses_time && time - sky->prev_time > 0.00001) {
  519. sky->prev_time = time;
  520. sky->reflection_dirty = true;
  521. RenderingServerDefault::redraw_request();
  522. }
  523. if (material != sky->prev_material) {
  524. sky->prev_material = material;
  525. sky->reflection_dirty = true;
  526. }
  527. if (material->uniform_set_updated) {
  528. material->uniform_set_updated = false;
  529. sky->reflection_dirty = true;
  530. }
  531. if (!p_transform.origin.is_equal_approx(sky->prev_position) && shader_data->uses_position) {
  532. sky->prev_position = p_transform.origin;
  533. sky->reflection_dirty = true;
  534. }
  535. }
  536. glBindBufferBase(GL_UNIFORM_BUFFER, SKY_DIRECTIONAL_LIGHT_UNIFORM_LOCATION, sky_globals.directional_light_buffer);
  537. if (shader_data->uses_light) {
  538. sky_globals.directional_light_count = 0;
  539. for (int i = 0; i < (int)p_lights.size(); i++) {
  540. GLES3::LightInstance *li = GLES3::LightStorage::get_singleton()->get_light_instance(p_lights[i]);
  541. if (!li) {
  542. continue;
  543. }
  544. RID base = li->light;
  545. ERR_CONTINUE(base.is_null());
  546. RS::LightType type = light_storage->light_get_type(base);
  547. if (type == RS::LIGHT_DIRECTIONAL && light_storage->light_directional_get_sky_mode(base) != RS::LIGHT_DIRECTIONAL_SKY_MODE_LIGHT_ONLY) {
  548. DirectionalLightData &sky_light_data = sky_globals.directional_lights[sky_globals.directional_light_count];
  549. Transform3D light_transform = li->transform;
  550. Vector3 world_direction = light_transform.basis.xform(Vector3(0, 0, 1)).normalized();
  551. sky_light_data.direction[0] = world_direction.x;
  552. sky_light_data.direction[1] = world_direction.y;
  553. sky_light_data.direction[2] = world_direction.z;
  554. float sign = light_storage->light_is_negative(base) ? -1 : 1;
  555. sky_light_data.energy = sign * light_storage->light_get_param(base, RS::LIGHT_PARAM_ENERGY);
  556. if (is_using_physical_light_units()) {
  557. sky_light_data.energy *= light_storage->light_get_param(base, RS::LIGHT_PARAM_INTENSITY);
  558. }
  559. if (p_render_data->camera_attributes.is_valid()) {
  560. sky_light_data.energy *= RSG::camera_attributes->camera_attributes_get_exposure_normalization_factor(p_render_data->camera_attributes);
  561. }
  562. Color linear_col = light_storage->light_get_color(base);
  563. sky_light_data.color[0] = linear_col.r;
  564. sky_light_data.color[1] = linear_col.g;
  565. sky_light_data.color[2] = linear_col.b;
  566. sky_light_data.enabled = true;
  567. float angular_diameter = light_storage->light_get_param(base, RS::LIGHT_PARAM_SIZE);
  568. if (angular_diameter > 0.0) {
  569. angular_diameter = Math::tan(Math::deg_to_rad(angular_diameter));
  570. } else {
  571. angular_diameter = 0.0;
  572. }
  573. sky_light_data.size = angular_diameter;
  574. sky_globals.directional_light_count++;
  575. if (sky_globals.directional_light_count >= sky_globals.max_directional_lights) {
  576. break;
  577. }
  578. }
  579. }
  580. // Check whether the directional_light_buffer changes
  581. bool light_data_dirty = false;
  582. // Light buffer is dirty if we have fewer or more lights
  583. // If we have fewer lights, make sure that old lights are disabled
  584. if (sky_globals.directional_light_count != sky_globals.last_frame_directional_light_count) {
  585. light_data_dirty = true;
  586. for (uint32_t i = sky_globals.directional_light_count; i < sky_globals.max_directional_lights; i++) {
  587. sky_globals.directional_lights[i].enabled = false;
  588. sky_globals.last_frame_directional_lights[i].enabled = false;
  589. }
  590. }
  591. if (!light_data_dirty) {
  592. for (uint32_t i = 0; i < sky_globals.directional_light_count; i++) {
  593. if (sky_globals.directional_lights[i].direction[0] != sky_globals.last_frame_directional_lights[i].direction[0] ||
  594. sky_globals.directional_lights[i].direction[1] != sky_globals.last_frame_directional_lights[i].direction[1] ||
  595. sky_globals.directional_lights[i].direction[2] != sky_globals.last_frame_directional_lights[i].direction[2] ||
  596. sky_globals.directional_lights[i].energy != sky_globals.last_frame_directional_lights[i].energy ||
  597. sky_globals.directional_lights[i].color[0] != sky_globals.last_frame_directional_lights[i].color[0] ||
  598. sky_globals.directional_lights[i].color[1] != sky_globals.last_frame_directional_lights[i].color[1] ||
  599. sky_globals.directional_lights[i].color[2] != sky_globals.last_frame_directional_lights[i].color[2] ||
  600. sky_globals.directional_lights[i].enabled != sky_globals.last_frame_directional_lights[i].enabled ||
  601. sky_globals.directional_lights[i].size != sky_globals.last_frame_directional_lights[i].size) {
  602. light_data_dirty = true;
  603. break;
  604. }
  605. }
  606. }
  607. if (light_data_dirty) {
  608. glBufferData(GL_UNIFORM_BUFFER, sizeof(DirectionalLightData) * sky_globals.max_directional_lights, sky_globals.directional_lights, GL_STREAM_DRAW);
  609. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  610. DirectionalLightData *temp = sky_globals.last_frame_directional_lights;
  611. sky_globals.last_frame_directional_lights = sky_globals.directional_lights;
  612. sky_globals.directional_lights = temp;
  613. sky_globals.last_frame_directional_light_count = sky_globals.directional_light_count;
  614. if (sky) {
  615. sky->reflection_dirty = true;
  616. }
  617. }
  618. }
  619. if (p_render_data->view_count > 1) {
  620. glBindBufferBase(GL_UNIFORM_BUFFER, SKY_MULTIVIEW_UNIFORM_LOCATION, scene_state.multiview_buffer);
  621. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  622. }
  623. if (sky && !sky->radiance) {
  624. _invalidate_sky(sky);
  625. _update_dirty_skys();
  626. }
  627. }
  628. void RasterizerSceneGLES3::_draw_sky(RID p_env, const Projection &p_projection, const Transform3D &p_transform, float p_luminance_multiplier, bool p_use_multiview, bool p_flip_y) {
  629. GLES3::MaterialStorage *material_storage = GLES3::MaterialStorage::get_singleton();
  630. ERR_FAIL_COND(p_env.is_null());
  631. Sky *sky = sky_owner.get_or_null(environment_get_sky(p_env));
  632. ERR_FAIL_NULL(sky);
  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. RS::EnvironmentBG background = environment_get_background(p_env);
  640. if (sky) {
  641. sky_material = sky->material;
  642. if (sky_material.is_valid()) {
  643. material_data = static_cast<GLES3::SkyMaterialData *>(material_storage->material_get_data(sky_material, RS::SHADER_SKY));
  644. if (!material_data || !material_data->shader_data->valid) {
  645. material_data = nullptr;
  646. }
  647. }
  648. if (!material_data) {
  649. sky_material = sky_globals.default_material;
  650. material_data = static_cast<GLES3::SkyMaterialData *>(material_storage->material_get_data(sky_material, RS::SHADER_SKY));
  651. }
  652. } else if (background == RS::ENV_BG_CLEAR_COLOR || background == RS::ENV_BG_COLOR) {
  653. sky_material = sky_globals.fog_material;
  654. material_data = static_cast<GLES3::SkyMaterialData *>(material_storage->material_get_data(sky_material, RS::SHADER_SKY));
  655. }
  656. ERR_FAIL_NULL(material_data);
  657. material_data->bind_uniforms();
  658. GLES3::SkyShaderData *shader_data = material_data->shader_data;
  659. ERR_FAIL_NULL(shader_data);
  660. // Camera
  661. Projection camera;
  662. if (environment_get_sky_custom_fov(p_env)) {
  663. float near_plane = p_projection.get_z_near();
  664. float far_plane = p_projection.get_z_far();
  665. float aspect = p_projection.get_aspect();
  666. camera.set_perspective(environment_get_sky_custom_fov(p_env), aspect, near_plane, far_plane);
  667. } else {
  668. camera = p_projection;
  669. }
  670. Basis sky_transform = environment_get_sky_orientation(p_env);
  671. sky_transform.invert();
  672. sky_transform = sky_transform * p_transform.basis;
  673. bool success = material_storage->shaders.sky_shader.version_bind_shader(shader_data->version, SkyShaderGLES3::MODE_BACKGROUND, spec_constants);
  674. if (!success) {
  675. return;
  676. }
  677. material_storage->shaders.sky_shader.version_set_uniform(SkyShaderGLES3::ORIENTATION, sky_transform, shader_data->version, SkyShaderGLES3::MODE_BACKGROUND, spec_constants);
  678. 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);
  679. material_storage->shaders.sky_shader.version_set_uniform(SkyShaderGLES3::POSITION, p_transform.origin, shader_data->version, SkyShaderGLES3::MODE_BACKGROUND, spec_constants);
  680. material_storage->shaders.sky_shader.version_set_uniform(SkyShaderGLES3::TIME, time, shader_data->version, SkyShaderGLES3::MODE_BACKGROUND, spec_constants);
  681. material_storage->shaders.sky_shader.version_set_uniform(SkyShaderGLES3::LUMINANCE_MULTIPLIER, p_luminance_multiplier, shader_data->version, SkyShaderGLES3::MODE_BACKGROUND, spec_constants);
  682. if (p_use_multiview) {
  683. glBindBufferBase(GL_UNIFORM_BUFFER, SKY_MULTIVIEW_UNIFORM_LOCATION, scene_state.multiview_buffer);
  684. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  685. }
  686. glBindVertexArray(sky_globals.screen_triangle_array);
  687. glDrawArrays(GL_TRIANGLES, 0, 3);
  688. }
  689. void RasterizerSceneGLES3::_update_sky_radiance(RID p_env, const Projection &p_projection, const Transform3D &p_transform, float p_luminance_multiplier) {
  690. GLES3::MaterialStorage *material_storage = GLES3::MaterialStorage::get_singleton();
  691. ERR_FAIL_COND(p_env.is_null());
  692. Sky *sky = sky_owner.get_or_null(environment_get_sky(p_env));
  693. ERR_FAIL_NULL(sky);
  694. GLES3::SkyMaterialData *material_data = nullptr;
  695. RID sky_material;
  696. RS::EnvironmentBG background = environment_get_background(p_env);
  697. if (sky) {
  698. ERR_FAIL_NULL(sky);
  699. sky_material = sky->material;
  700. if (sky_material.is_valid()) {
  701. material_data = static_cast<GLES3::SkyMaterialData *>(material_storage->material_get_data(sky_material, RS::SHADER_SKY));
  702. if (!material_data || !material_data->shader_data->valid) {
  703. material_data = nullptr;
  704. }
  705. }
  706. if (!material_data) {
  707. sky_material = sky_globals.default_material;
  708. material_data = static_cast<GLES3::SkyMaterialData *>(material_storage->material_get_data(sky_material, RS::SHADER_SKY));
  709. }
  710. } else if (background == RS::ENV_BG_CLEAR_COLOR || background == RS::ENV_BG_COLOR) {
  711. sky_material = sky_globals.fog_material;
  712. material_data = static_cast<GLES3::SkyMaterialData *>(material_storage->material_get_data(sky_material, RS::SHADER_SKY));
  713. }
  714. ERR_FAIL_NULL(material_data);
  715. material_data->bind_uniforms();
  716. GLES3::SkyShaderData *shader_data = material_data->shader_data;
  717. ERR_FAIL_NULL(shader_data);
  718. bool update_single_frame = sky->mode == RS::SKY_MODE_REALTIME || sky->mode == RS::SKY_MODE_QUALITY;
  719. RS::SkyMode sky_mode = sky->mode;
  720. if (sky_mode == RS::SKY_MODE_AUTOMATIC) {
  721. if (shader_data->uses_time || shader_data->uses_position) {
  722. update_single_frame = true;
  723. sky_mode = RS::SKY_MODE_REALTIME;
  724. } else if (shader_data->uses_light || shader_data->ubo_size > 0) {
  725. update_single_frame = false;
  726. sky_mode = RS::SKY_MODE_INCREMENTAL;
  727. } else {
  728. update_single_frame = true;
  729. sky_mode = RS::SKY_MODE_QUALITY;
  730. }
  731. }
  732. if (sky->processing_layer == 0 && sky_mode == RS::SKY_MODE_INCREMENTAL) {
  733. // On the first frame after creating sky, rebuild in single frame
  734. update_single_frame = true;
  735. sky_mode = RS::SKY_MODE_QUALITY;
  736. }
  737. int max_processing_layer = sky->mipmap_count;
  738. // Update radiance cubemap
  739. if (sky->reflection_dirty && (sky->processing_layer > max_processing_layer || update_single_frame)) {
  740. static const Vector3 view_normals[6] = {
  741. Vector3(+1, 0, 0),
  742. Vector3(-1, 0, 0),
  743. Vector3(0, +1, 0),
  744. Vector3(0, -1, 0),
  745. Vector3(0, 0, +1),
  746. Vector3(0, 0, -1)
  747. };
  748. static const Vector3 view_up[6] = {
  749. Vector3(0, -1, 0),
  750. Vector3(0, -1, 0),
  751. Vector3(0, 0, +1),
  752. Vector3(0, 0, -1),
  753. Vector3(0, -1, 0),
  754. Vector3(0, -1, 0)
  755. };
  756. Projection cm;
  757. cm.set_perspective(90, 1, 0.01, 10.0);
  758. Projection correction;
  759. correction.columns[1][1] = -1.0;
  760. cm = correction * cm;
  761. bool success = material_storage->shaders.sky_shader.version_bind_shader(shader_data->version, SkyShaderGLES3::MODE_CUBEMAP);
  762. if (!success) {
  763. return;
  764. }
  765. material_storage->shaders.sky_shader.version_set_uniform(SkyShaderGLES3::POSITION, p_transform.origin, shader_data->version, SkyShaderGLES3::MODE_CUBEMAP);
  766. material_storage->shaders.sky_shader.version_set_uniform(SkyShaderGLES3::TIME, time, shader_data->version, SkyShaderGLES3::MODE_CUBEMAP);
  767. 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);
  768. material_storage->shaders.sky_shader.version_set_uniform(SkyShaderGLES3::LUMINANCE_MULTIPLIER, p_luminance_multiplier, shader_data->version, SkyShaderGLES3::MODE_CUBEMAP);
  769. glBindVertexArray(sky_globals.screen_triangle_array);
  770. glViewport(0, 0, sky->radiance_size, sky->radiance_size);
  771. glBindFramebuffer(GL_FRAMEBUFFER, sky->radiance_framebuffer);
  772. glDisable(GL_BLEND);
  773. glDepthMask(GL_FALSE);
  774. glDisable(GL_DEPTH_TEST);
  775. scene_state.current_depth_test = GLES3::SceneShaderData::DEPTH_TEST_DISABLED;
  776. glDisable(GL_SCISSOR_TEST);
  777. glDisable(GL_CULL_FACE);
  778. scene_state.cull_mode = GLES3::SceneShaderData::CULL_DISABLED;
  779. for (int i = 0; i < 6; i++) {
  780. Basis local_view = Basis::looking_at(view_normals[i], view_up[i]);
  781. material_storage->shaders.sky_shader.version_set_uniform(SkyShaderGLES3::ORIENTATION, local_view, shader_data->version, SkyShaderGLES3::MODE_CUBEMAP);
  782. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, sky->raw_radiance, 0);
  783. glDrawArrays(GL_TRIANGLES, 0, 3);
  784. }
  785. if (update_single_frame) {
  786. for (int i = 0; i < max_processing_layer; i++) {
  787. _filter_sky_radiance(sky, i);
  788. }
  789. } else {
  790. _filter_sky_radiance(sky, 0); //Just copy over the first mipmap
  791. }
  792. sky->processing_layer = 1;
  793. sky->baked_exposure = p_luminance_multiplier;
  794. sky->reflection_dirty = false;
  795. } else {
  796. if (sky_mode == RS::SKY_MODE_INCREMENTAL && sky->processing_layer < max_processing_layer) {
  797. glDisable(GL_BLEND);
  798. glDepthMask(GL_FALSE);
  799. glDisable(GL_DEPTH_TEST);
  800. scene_state.current_depth_test = GLES3::SceneShaderData::DEPTH_TEST_DISABLED;
  801. glDisable(GL_SCISSOR_TEST);
  802. glDisable(GL_CULL_FACE);
  803. scene_state.cull_mode = GLES3::SceneShaderData::CULL_DISABLED;
  804. _filter_sky_radiance(sky, sky->processing_layer);
  805. sky->processing_layer++;
  806. }
  807. }
  808. }
  809. // Helper functions for IBL filtering
  810. Vector3 importance_sample_GGX(Vector2 xi, float roughness4) {
  811. // Compute distribution direction
  812. float phi = 2.0 * Math_PI * xi.x;
  813. float cos_theta = sqrt((1.0 - xi.y) / (1.0 + (roughness4 - 1.0) * xi.y));
  814. float sin_theta = sqrt(1.0 - cos_theta * cos_theta);
  815. // Convert to spherical direction
  816. Vector3 half_vector;
  817. half_vector.x = sin_theta * cos(phi);
  818. half_vector.y = sin_theta * sin(phi);
  819. half_vector.z = cos_theta;
  820. return half_vector;
  821. }
  822. float distribution_GGX(float NdotH, float roughness4) {
  823. float NdotH2 = NdotH * NdotH;
  824. float denom = (NdotH2 * (roughness4 - 1.0) + 1.0);
  825. denom = Math_PI * denom * denom;
  826. return roughness4 / denom;
  827. }
  828. float radical_inverse_vdC(uint32_t bits) {
  829. bits = (bits << 16) | (bits >> 16);
  830. bits = ((bits & 0x55555555) << 1) | ((bits & 0xAAAAAAAA) >> 1);
  831. bits = ((bits & 0x33333333) << 2) | ((bits & 0xCCCCCCCC) >> 2);
  832. bits = ((bits & 0x0F0F0F0F) << 4) | ((bits & 0xF0F0F0F0) >> 4);
  833. bits = ((bits & 0x00FF00FF) << 8) | ((bits & 0xFF00FF00) >> 8);
  834. return float(bits) * 2.3283064365386963e-10;
  835. }
  836. Vector2 hammersley(uint32_t i, uint32_t N) {
  837. return Vector2(float(i) / float(N), radical_inverse_vdC(i));
  838. }
  839. void RasterizerSceneGLES3::_filter_sky_radiance(Sky *p_sky, int p_base_layer) {
  840. GLES3::MaterialStorage *material_storage = GLES3::MaterialStorage::get_singleton();
  841. glActiveTexture(GL_TEXTURE0);
  842. glBindTexture(GL_TEXTURE_CUBE_MAP, p_sky->raw_radiance);
  843. glBindFramebuffer(GL_FRAMEBUFFER, p_sky->radiance_framebuffer);
  844. CubemapFilterShaderGLES3::ShaderVariant mode = CubemapFilterShaderGLES3::MODE_DEFAULT;
  845. if (p_base_layer == 0) {
  846. glGenerateMipmap(GL_TEXTURE_CUBE_MAP);
  847. // Copy over base layer without filtering.
  848. mode = CubemapFilterShaderGLES3::MODE_COPY;
  849. }
  850. int size = p_sky->radiance_size >> p_base_layer;
  851. glViewport(0, 0, size, size);
  852. glBindVertexArray(sky_globals.screen_triangle_array);
  853. bool success = material_storage->shaders.cubemap_filter_shader.version_bind_shader(scene_globals.cubemap_filter_shader_version, mode);
  854. if (!success) {
  855. return;
  856. }
  857. if (p_base_layer > 0) {
  858. const uint32_t sample_counts[4] = { 1, sky_globals.ggx_samples / 4, sky_globals.ggx_samples / 2, sky_globals.ggx_samples };
  859. uint32_t sample_count = sample_counts[MIN(3, p_base_layer)];
  860. float roughness = float(p_base_layer) / (p_sky->mipmap_count);
  861. float roughness4 = roughness * roughness;
  862. roughness4 *= roughness4;
  863. float solid_angle_texel = 4.0 * Math_PI / float(6 * size * size);
  864. LocalVector<float> sample_directions;
  865. sample_directions.resize(4 * sample_count);
  866. uint32_t index = 0;
  867. float weight = 0.0;
  868. for (uint32_t i = 0; i < sample_count; i++) {
  869. Vector2 xi = hammersley(i, sample_count);
  870. Vector3 dir = importance_sample_GGX(xi, roughness4);
  871. Vector3 light_vec = (2.0 * dir.z * dir - Vector3(0.0, 0.0, 1.0));
  872. if (light_vec.z < 0.0) {
  873. continue;
  874. }
  875. sample_directions[index * 4] = light_vec.x;
  876. sample_directions[index * 4 + 1] = light_vec.y;
  877. sample_directions[index * 4 + 2] = light_vec.z;
  878. float D = distribution_GGX(dir.z, roughness4);
  879. float pdf = D * dir.z / (4.0 * dir.z) + 0.0001;
  880. float solid_angle_sample = 1.0 / (float(sample_count) * pdf + 0.0001);
  881. float mip_level = MAX(0.5 * log2(solid_angle_sample / solid_angle_texel) + float(MAX(1, p_base_layer - 3)), 1.0);
  882. sample_directions[index * 4 + 3] = mip_level;
  883. weight += light_vec.z;
  884. index++;
  885. }
  886. glUniform4fv(material_storage->shaders.cubemap_filter_shader.version_get_uniform(CubemapFilterShaderGLES3::SAMPLE_DIRECTIONS_MIP, scene_globals.cubemap_filter_shader_version, mode), sample_count, sample_directions.ptr());
  887. material_storage->shaders.cubemap_filter_shader.version_set_uniform(CubemapFilterShaderGLES3::WEIGHT, weight, scene_globals.cubemap_filter_shader_version, mode);
  888. material_storage->shaders.cubemap_filter_shader.version_set_uniform(CubemapFilterShaderGLES3::SAMPLE_COUNT, index, scene_globals.cubemap_filter_shader_version, mode);
  889. }
  890. for (int i = 0; i < 6; i++) {
  891. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, p_sky->radiance, p_base_layer);
  892. #ifdef DEBUG_ENABLED
  893. GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
  894. if (status != GL_FRAMEBUFFER_COMPLETE) {
  895. WARN_PRINT("Could not bind sky radiance face: " + itos(i) + ", status: " + GLES3::TextureStorage::get_singleton()->get_framebuffer_error(status));
  896. }
  897. #endif
  898. material_storage->shaders.cubemap_filter_shader.version_set_uniform(CubemapFilterShaderGLES3::FACE_ID, i, scene_globals.cubemap_filter_shader_version, mode);
  899. glDrawArrays(GL_TRIANGLES, 0, 3);
  900. }
  901. glBindVertexArray(0);
  902. glViewport(0, 0, p_sky->screen_size.x, p_sky->screen_size.y);
  903. glBindFramebuffer(GL_FRAMEBUFFER, 0);
  904. }
  905. Ref<Image> RasterizerSceneGLES3::sky_bake_panorama(RID p_sky, float p_energy, bool p_bake_irradiance, const Size2i &p_size) {
  906. return Ref<Image>();
  907. }
  908. /* ENVIRONMENT API */
  909. void RasterizerSceneGLES3::environment_glow_set_use_bicubic_upscale(bool p_enable) {
  910. glow_bicubic_upscale = p_enable;
  911. }
  912. void RasterizerSceneGLES3::environment_set_ssr_roughness_quality(RS::EnvironmentSSRRoughnessQuality p_quality) {
  913. }
  914. 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) {
  915. }
  916. 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) {
  917. }
  918. void RasterizerSceneGLES3::environment_set_sdfgi_ray_count(RS::EnvironmentSDFGIRayCount p_ray_count) {
  919. }
  920. void RasterizerSceneGLES3::environment_set_sdfgi_frames_to_converge(RS::EnvironmentSDFGIFramesToConverge p_frames) {
  921. }
  922. void RasterizerSceneGLES3::environment_set_sdfgi_frames_to_update_light(RS::EnvironmentSDFGIFramesToUpdateLight p_update) {
  923. }
  924. void RasterizerSceneGLES3::environment_set_volumetric_fog_volume_size(int p_size, int p_depth) {
  925. }
  926. void RasterizerSceneGLES3::environment_set_volumetric_fog_filter_active(bool p_enable) {
  927. }
  928. Ref<Image> RasterizerSceneGLES3::environment_bake_panorama(RID p_env, bool p_bake_irradiance, const Size2i &p_size) {
  929. return Ref<Image>();
  930. }
  931. void RasterizerSceneGLES3::positional_soft_shadow_filter_set_quality(RS::ShadowQuality p_quality) {
  932. scene_state.positional_shadow_quality = p_quality;
  933. }
  934. void RasterizerSceneGLES3::directional_soft_shadow_filter_set_quality(RS::ShadowQuality p_quality) {
  935. scene_state.directional_shadow_quality = p_quality;
  936. }
  937. RID RasterizerSceneGLES3::fog_volume_instance_create(RID p_fog_volume) {
  938. return RID();
  939. }
  940. void RasterizerSceneGLES3::fog_volume_instance_set_transform(RID p_fog_volume_instance, const Transform3D &p_transform) {
  941. }
  942. void RasterizerSceneGLES3::fog_volume_instance_set_active(RID p_fog_volume_instance, bool p_active) {
  943. }
  944. RID RasterizerSceneGLES3::fog_volume_instance_get_volume(RID p_fog_volume_instance) const {
  945. return RID();
  946. }
  947. Vector3 RasterizerSceneGLES3::fog_volume_instance_get_position(RID p_fog_volume_instance) const {
  948. return Vector3();
  949. }
  950. RID RasterizerSceneGLES3::voxel_gi_instance_create(RID p_voxel_gi) {
  951. return RID();
  952. }
  953. void RasterizerSceneGLES3::voxel_gi_instance_set_transform_to_data(RID p_probe, const Transform3D &p_xform) {
  954. }
  955. bool RasterizerSceneGLES3::voxel_gi_needs_update(RID p_probe) const {
  956. return false;
  957. }
  958. 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) {
  959. }
  960. void RasterizerSceneGLES3::voxel_gi_set_quality(RS::VoxelGIQuality) {
  961. }
  962. _FORCE_INLINE_ static uint32_t _indices_to_primitives(RS::PrimitiveType p_primitive, uint32_t p_indices) {
  963. static const uint32_t divisor[RS::PRIMITIVE_MAX] = { 1, 2, 1, 3, 1 };
  964. static const uint32_t subtractor[RS::PRIMITIVE_MAX] = { 0, 0, 1, 0, 1 };
  965. return (p_indices - subtractor[p_primitive]) / divisor[p_primitive];
  966. }
  967. void RasterizerSceneGLES3::_fill_render_list(RenderListType p_render_list, const RenderDataGLES3 *p_render_data, PassMode p_pass_mode, bool p_append) {
  968. GLES3::MeshStorage *mesh_storage = GLES3::MeshStorage::get_singleton();
  969. if (p_render_list == RENDER_LIST_OPAQUE) {
  970. scene_state.used_screen_texture = false;
  971. scene_state.used_normal_texture = false;
  972. scene_state.used_depth_texture = false;
  973. }
  974. Plane near_plane;
  975. if (p_render_data->cam_orthogonal) {
  976. near_plane = Plane(-p_render_data->cam_transform.basis.get_column(Vector3::AXIS_Z), p_render_data->cam_transform.origin);
  977. near_plane.d += p_render_data->cam_projection.get_z_near();
  978. }
  979. float z_max = p_render_data->cam_projection.get_z_far() - p_render_data->cam_projection.get_z_near();
  980. RenderList *rl = &render_list[p_render_list];
  981. // Parse any updates on our geometry, updates surface caches and such
  982. _update_dirty_geometry_instances();
  983. if (!p_append) {
  984. rl->clear();
  985. if (p_render_list == RENDER_LIST_OPAQUE) {
  986. render_list[RENDER_LIST_ALPHA].clear(); //opaque fills alpha too
  987. }
  988. }
  989. //fill list
  990. for (int i = 0; i < (int)p_render_data->instances->size(); i++) {
  991. GeometryInstanceGLES3 *inst = static_cast<GeometryInstanceGLES3 *>((*p_render_data->instances)[i]);
  992. Vector3 center = inst->transform.origin;
  993. if (p_render_data->cam_orthogonal) {
  994. if (inst->use_aabb_center) {
  995. center = inst->transformed_aabb.get_support(-near_plane.normal);
  996. }
  997. inst->depth = near_plane.distance_to(center) - inst->sorting_offset;
  998. } else {
  999. if (inst->use_aabb_center) {
  1000. center = inst->transformed_aabb.position + (inst->transformed_aabb.size * 0.5);
  1001. }
  1002. inst->depth = p_render_data->cam_transform.origin.distance_to(center) - inst->sorting_offset;
  1003. }
  1004. uint32_t depth_layer = CLAMP(int(inst->depth * 16 / z_max), 0, 15);
  1005. uint32_t flags = inst->base_flags; //fill flags if appropriate
  1006. if (inst->non_uniform_scale) {
  1007. flags |= INSTANCE_DATA_FLAGS_NON_UNIFORM_SCALE;
  1008. }
  1009. // Sets the index values for lookup in the shader
  1010. // This has to be done after _setup_lights was called this frame
  1011. if (p_pass_mode == PASS_MODE_COLOR) {
  1012. inst->light_passes.clear();
  1013. inst->spot_light_gl_cache.clear();
  1014. inst->omni_light_gl_cache.clear();
  1015. uint64_t current_frame = RSG::rasterizer->get_frame_number();
  1016. if (inst->paired_omni_light_count) {
  1017. for (uint32_t j = 0; j < inst->paired_omni_light_count; j++) {
  1018. RID light_instance = inst->paired_omni_lights[j];
  1019. if (GLES3::LightStorage::get_singleton()->light_instance_get_render_pass(light_instance) != current_frame) {
  1020. continue;
  1021. }
  1022. RID light = GLES3::LightStorage::get_singleton()->light_instance_get_base_light(light_instance);
  1023. int32_t shadow_id = GLES3::LightStorage::get_singleton()->light_instance_get_shadow_id(light_instance);
  1024. if (GLES3::LightStorage::get_singleton()->light_has_shadow(light) && shadow_id >= 0) {
  1025. GeometryInstanceGLES3::LightPass pass;
  1026. pass.light_id = GLES3::LightStorage::get_singleton()->light_instance_get_gl_id(light_instance);
  1027. pass.shadow_id = shadow_id;
  1028. pass.light_instance_rid = light_instance;
  1029. pass.is_omni = true;
  1030. inst->light_passes.push_back(pass);
  1031. } else {
  1032. // Lights without shadow can all go in base pass.
  1033. inst->omni_light_gl_cache.push_back((uint32_t)GLES3::LightStorage::get_singleton()->light_instance_get_gl_id(light_instance));
  1034. }
  1035. }
  1036. }
  1037. if (inst->paired_spot_light_count) {
  1038. for (uint32_t j = 0; j < inst->paired_spot_light_count; j++) {
  1039. RID light_instance = inst->paired_spot_lights[j];
  1040. if (GLES3::LightStorage::get_singleton()->light_instance_get_render_pass(light_instance) != current_frame) {
  1041. continue;
  1042. }
  1043. RID light = GLES3::LightStorage::get_singleton()->light_instance_get_base_light(light_instance);
  1044. int32_t shadow_id = GLES3::LightStorage::get_singleton()->light_instance_get_shadow_id(light_instance);
  1045. if (GLES3::LightStorage::get_singleton()->light_has_shadow(light) && shadow_id >= 0) {
  1046. GeometryInstanceGLES3::LightPass pass;
  1047. pass.light_id = GLES3::LightStorage::get_singleton()->light_instance_get_gl_id(light_instance);
  1048. pass.shadow_id = shadow_id;
  1049. pass.light_instance_rid = light_instance;
  1050. inst->light_passes.push_back(pass);
  1051. } else {
  1052. // Lights without shadow can all go in base pass.
  1053. inst->spot_light_gl_cache.push_back((uint32_t)GLES3::LightStorage::get_singleton()->light_instance_get_gl_id(light_instance));
  1054. }
  1055. }
  1056. }
  1057. }
  1058. inst->flags_cache = flags;
  1059. GeometryInstanceSurface *surf = inst->surface_caches;
  1060. while (surf) {
  1061. // LOD
  1062. if (p_render_data->screen_mesh_lod_threshold > 0.0 && mesh_storage->mesh_surface_has_lod(surf->surface)) {
  1063. // Get the LOD support points on the mesh AABB.
  1064. Vector3 lod_support_min = inst->transformed_aabb.get_support(p_render_data->cam_transform.basis.get_column(Vector3::AXIS_Z));
  1065. Vector3 lod_support_max = inst->transformed_aabb.get_support(-p_render_data->cam_transform.basis.get_column(Vector3::AXIS_Z));
  1066. // Get the distances to those points on the AABB from the camera origin.
  1067. float distance_min = (float)p_render_data->cam_transform.origin.distance_to(lod_support_min);
  1068. float distance_max = (float)p_render_data->cam_transform.origin.distance_to(lod_support_max);
  1069. float distance = 0.0;
  1070. if (distance_min * distance_max < 0.0) {
  1071. //crossing plane
  1072. distance = 0.0;
  1073. } else if (distance_min >= 0.0) {
  1074. distance = distance_min;
  1075. } else if (distance_max <= 0.0) {
  1076. distance = -distance_max;
  1077. }
  1078. if (p_render_data->cam_orthogonal) {
  1079. distance = 1.0;
  1080. }
  1081. uint32_t indices = 0;
  1082. surf->lod_index = mesh_storage->mesh_surface_get_lod(surf->surface, inst->lod_model_scale * inst->lod_bias, distance * p_render_data->lod_distance_multiplier, p_render_data->screen_mesh_lod_threshold, indices);
  1083. surf->index_count = indices;
  1084. if (p_render_data->render_info) {
  1085. indices = _indices_to_primitives(surf->primitive, indices);
  1086. if (p_render_list == RENDER_LIST_OPAQUE) { //opaque
  1087. p_render_data->render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_VISIBLE][RS::VIEWPORT_RENDER_INFO_PRIMITIVES_IN_FRAME] += indices;
  1088. } else if (p_render_list == RENDER_LIST_SECONDARY) { //shadow
  1089. p_render_data->render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_SHADOW][RS::VIEWPORT_RENDER_INFO_PRIMITIVES_IN_FRAME] += indices;
  1090. }
  1091. }
  1092. } else {
  1093. surf->lod_index = 0;
  1094. if (p_render_data->render_info) {
  1095. uint32_t to_draw = mesh_storage->mesh_surface_get_vertices_drawn_count(surf->surface);
  1096. to_draw = _indices_to_primitives(surf->primitive, to_draw);
  1097. to_draw *= inst->instance_count > 0 ? inst->instance_count : 1;
  1098. if (p_render_list == RENDER_LIST_OPAQUE) { //opaque
  1099. p_render_data->render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_VISIBLE][RS::VIEWPORT_RENDER_INFO_PRIMITIVES_IN_FRAME] += to_draw;
  1100. } else if (p_render_list == RENDER_LIST_SECONDARY) { //shadow
  1101. p_render_data->render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_SHADOW][RS::VIEWPORT_RENDER_INFO_PRIMITIVES_IN_FRAME] += to_draw;
  1102. }
  1103. }
  1104. }
  1105. // ADD Element
  1106. if (p_pass_mode == PASS_MODE_COLOR) {
  1107. #ifdef DEBUG_ENABLED
  1108. bool force_alpha = unlikely(get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_OVERDRAW);
  1109. #else
  1110. bool force_alpha = false;
  1111. #endif
  1112. if (!force_alpha && (surf->flags & GeometryInstanceSurface::FLAG_PASS_OPAQUE)) {
  1113. rl->add_element(surf);
  1114. }
  1115. if (force_alpha || (surf->flags & GeometryInstanceSurface::FLAG_PASS_ALPHA)) {
  1116. render_list[RENDER_LIST_ALPHA].add_element(surf);
  1117. }
  1118. if (surf->flags & GeometryInstanceSurface::FLAG_USES_SCREEN_TEXTURE) {
  1119. scene_state.used_screen_texture = true;
  1120. }
  1121. if (surf->flags & GeometryInstanceSurface::FLAG_USES_NORMAL_TEXTURE) {
  1122. scene_state.used_normal_texture = true;
  1123. }
  1124. if (surf->flags & GeometryInstanceSurface::FLAG_USES_DEPTH_TEXTURE) {
  1125. scene_state.used_depth_texture = true;
  1126. }
  1127. } else if (p_pass_mode == PASS_MODE_SHADOW) {
  1128. if (surf->flags & GeometryInstanceSurface::FLAG_PASS_SHADOW) {
  1129. rl->add_element(surf);
  1130. }
  1131. } else {
  1132. if (surf->flags & (GeometryInstanceSurface::FLAG_PASS_DEPTH | GeometryInstanceSurface::FLAG_PASS_OPAQUE)) {
  1133. rl->add_element(surf);
  1134. }
  1135. }
  1136. surf->sort.depth_layer = depth_layer;
  1137. surf->finished_base_pass = false;
  1138. surf->light_pass_index = 0;
  1139. surf = surf->next;
  1140. }
  1141. }
  1142. }
  1143. // Needs to be called after _setup_lights so that directional_light_count is accurate.
  1144. 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) {
  1145. Projection correction;
  1146. correction.columns[1][1] = p_flip_y ? -1.0 : 1.0;
  1147. Projection projection = correction * p_render_data->cam_projection;
  1148. //store camera into ubo
  1149. GLES3::MaterialStorage::store_camera(projection, scene_state.ubo.projection_matrix);
  1150. GLES3::MaterialStorage::store_camera(projection.inverse(), scene_state.ubo.inv_projection_matrix);
  1151. GLES3::MaterialStorage::store_transform(p_render_data->cam_transform, scene_state.ubo.inv_view_matrix);
  1152. GLES3::MaterialStorage::store_transform(p_render_data->inv_cam_transform, scene_state.ubo.view_matrix);
  1153. scene_state.ubo.camera_visible_layers = p_render_data->camera_visible_layers;
  1154. if (p_render_data->view_count > 1) {
  1155. for (uint32_t v = 0; v < p_render_data->view_count; v++) {
  1156. projection = correction * p_render_data->view_projection[v];
  1157. GLES3::MaterialStorage::store_camera(projection, scene_state.multiview_ubo.projection_matrix_view[v]);
  1158. GLES3::MaterialStorage::store_camera(projection.inverse(), scene_state.multiview_ubo.inv_projection_matrix_view[v]);
  1159. scene_state.multiview_ubo.eye_offset[v][0] = p_render_data->view_eye_offset[v].x;
  1160. scene_state.multiview_ubo.eye_offset[v][1] = p_render_data->view_eye_offset[v].y;
  1161. scene_state.multiview_ubo.eye_offset[v][2] = p_render_data->view_eye_offset[v].z;
  1162. scene_state.multiview_ubo.eye_offset[v][3] = 0.0;
  1163. }
  1164. }
  1165. // Only render the lights without shadows in the base pass.
  1166. scene_state.ubo.directional_light_count = p_render_data->directional_light_count - p_render_data->directional_shadow_count;
  1167. scene_state.ubo.z_far = p_render_data->z_far;
  1168. scene_state.ubo.z_near = p_render_data->z_near;
  1169. scene_state.ubo.viewport_size[0] = p_screen_size.x;
  1170. scene_state.ubo.viewport_size[1] = p_screen_size.y;
  1171. Size2 screen_pixel_size = Vector2(1.0, 1.0) / Size2(p_screen_size);
  1172. scene_state.ubo.screen_pixel_size[0] = screen_pixel_size.x;
  1173. scene_state.ubo.screen_pixel_size[1] = screen_pixel_size.y;
  1174. scene_state.ubo.shadow_bias = p_shadow_bias;
  1175. scene_state.ubo.pancake_shadows = p_pancake_shadows;
  1176. //time global variables
  1177. scene_state.ubo.time = time;
  1178. if (get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_UNSHADED) {
  1179. scene_state.ubo.use_ambient_light = true;
  1180. scene_state.ubo.ambient_light_color_energy[0] = 1;
  1181. scene_state.ubo.ambient_light_color_energy[1] = 1;
  1182. scene_state.ubo.ambient_light_color_energy[2] = 1;
  1183. scene_state.ubo.ambient_light_color_energy[3] = 1.0;
  1184. scene_state.ubo.use_ambient_cubemap = false;
  1185. scene_state.ubo.use_reflection_cubemap = false;
  1186. } else if (is_environment(p_render_data->environment)) {
  1187. RS::EnvironmentBG env_bg = environment_get_background(p_render_data->environment);
  1188. RS::EnvironmentAmbientSource ambient_src = environment_get_ambient_source(p_render_data->environment);
  1189. float bg_energy_multiplier = environment_get_bg_energy_multiplier(p_render_data->environment);
  1190. scene_state.ubo.ambient_light_color_energy[3] = bg_energy_multiplier;
  1191. scene_state.ubo.ambient_color_sky_mix = environment_get_ambient_sky_contribution(p_render_data->environment);
  1192. //ambient
  1193. if (ambient_src == RS::ENV_AMBIENT_SOURCE_BG && (env_bg == RS::ENV_BG_CLEAR_COLOR || env_bg == RS::ENV_BG_COLOR)) {
  1194. Color color = env_bg == RS::ENV_BG_CLEAR_COLOR ? p_default_bg_color : environment_get_bg_color(p_render_data->environment);
  1195. color = color.srgb_to_linear();
  1196. scene_state.ubo.ambient_light_color_energy[0] = color.r * bg_energy_multiplier;
  1197. scene_state.ubo.ambient_light_color_energy[1] = color.g * bg_energy_multiplier;
  1198. scene_state.ubo.ambient_light_color_energy[2] = color.b * bg_energy_multiplier;
  1199. scene_state.ubo.use_ambient_light = true;
  1200. scene_state.ubo.use_ambient_cubemap = false;
  1201. } else {
  1202. float energy = environment_get_ambient_light_energy(p_render_data->environment);
  1203. Color color = environment_get_ambient_light(p_render_data->environment);
  1204. color = color.srgb_to_linear();
  1205. scene_state.ubo.ambient_light_color_energy[0] = color.r * energy;
  1206. scene_state.ubo.ambient_light_color_energy[1] = color.g * energy;
  1207. scene_state.ubo.ambient_light_color_energy[2] = color.b * energy;
  1208. Basis sky_transform = environment_get_sky_orientation(p_render_data->environment);
  1209. sky_transform = sky_transform.inverse() * p_render_data->cam_transform.basis;
  1210. GLES3::MaterialStorage::store_transform_3x3(sky_transform, scene_state.ubo.radiance_inverse_xform);
  1211. 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;
  1212. scene_state.ubo.use_ambient_light = scene_state.ubo.use_ambient_cubemap || ambient_src == RS::ENV_AMBIENT_SOURCE_COLOR;
  1213. }
  1214. //specular
  1215. RS::EnvironmentReflectionSource ref_src = environment_get_reflection_source(p_render_data->environment);
  1216. if ((ref_src == RS::ENV_REFLECTION_SOURCE_BG && env_bg == RS::ENV_BG_SKY) || ref_src == RS::ENV_REFLECTION_SOURCE_SKY) {
  1217. scene_state.ubo.use_reflection_cubemap = true;
  1218. } else {
  1219. scene_state.ubo.use_reflection_cubemap = false;
  1220. }
  1221. scene_state.ubo.fog_enabled = environment_get_fog_enabled(p_render_data->environment);
  1222. scene_state.ubo.fog_density = environment_get_fog_density(p_render_data->environment);
  1223. scene_state.ubo.fog_height = environment_get_fog_height(p_render_data->environment);
  1224. scene_state.ubo.fog_height_density = environment_get_fog_height_density(p_render_data->environment);
  1225. scene_state.ubo.fog_aerial_perspective = environment_get_fog_aerial_perspective(p_render_data->environment);
  1226. Color fog_color = environment_get_fog_light_color(p_render_data->environment).srgb_to_linear();
  1227. float fog_energy = environment_get_fog_light_energy(p_render_data->environment);
  1228. scene_state.ubo.fog_light_color[0] = fog_color.r * fog_energy;
  1229. scene_state.ubo.fog_light_color[1] = fog_color.g * fog_energy;
  1230. scene_state.ubo.fog_light_color[2] = fog_color.b * fog_energy;
  1231. scene_state.ubo.fog_sun_scatter = environment_get_fog_sun_scatter(p_render_data->environment);
  1232. } else {
  1233. }
  1234. if (p_render_data->camera_attributes.is_valid()) {
  1235. scene_state.ubo.emissive_exposure_normalization = RSG::camera_attributes->camera_attributes_get_exposure_normalization_factor(p_render_data->camera_attributes);
  1236. scene_state.ubo.IBL_exposure_normalization = 1.0;
  1237. if (is_environment(p_render_data->environment)) {
  1238. RID sky_rid = environment_get_sky(p_render_data->environment);
  1239. if (sky_rid.is_valid()) {
  1240. 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);
  1241. scene_state.ubo.IBL_exposure_normalization = current_exposure / MAX(0.001, sky_get_baked_exposure(sky_rid));
  1242. }
  1243. }
  1244. } else if (scene_state.ubo.emissive_exposure_normalization > 0.0) {
  1245. // This branch is triggered when using render_material().
  1246. // Emissive is set outside the function, so don't set it.
  1247. // IBL isn't used don't set it.
  1248. } else {
  1249. scene_state.ubo.emissive_exposure_normalization = 1.0;
  1250. scene_state.ubo.IBL_exposure_normalization = 1.0;
  1251. }
  1252. if (scene_state.ubo_buffer == 0) {
  1253. glGenBuffers(1, &scene_state.ubo_buffer);
  1254. glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_DATA_UNIFORM_LOCATION, scene_state.ubo_buffer);
  1255. 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");
  1256. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  1257. } else {
  1258. glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_DATA_UNIFORM_LOCATION, scene_state.ubo_buffer);
  1259. glBufferData(GL_UNIFORM_BUFFER, sizeof(SceneState::UBO), &scene_state.ubo, GL_STREAM_DRAW);
  1260. }
  1261. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  1262. if (p_render_data->view_count > 1) {
  1263. if (scene_state.multiview_buffer == 0) {
  1264. glGenBuffers(1, &scene_state.multiview_buffer);
  1265. glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_MULTIVIEW_UNIFORM_LOCATION, scene_state.multiview_buffer);
  1266. 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");
  1267. } else {
  1268. glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_MULTIVIEW_UNIFORM_LOCATION, scene_state.multiview_buffer);
  1269. glBufferData(GL_UNIFORM_BUFFER, sizeof(SceneState::MultiviewUBO), &scene_state.multiview_ubo, GL_STREAM_DRAW);
  1270. }
  1271. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  1272. }
  1273. }
  1274. // Puts lights into Uniform Buffers. Needs to be called before _fill_list as this caches the index of each light in the Uniform Buffer
  1275. 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) {
  1276. GLES3::LightStorage *light_storage = GLES3::LightStorage::get_singleton();
  1277. GLES3::Config *config = GLES3::Config::get_singleton();
  1278. const Transform3D inverse_transform = p_render_data->inv_cam_transform;
  1279. const PagedArray<RID> &lights = *p_render_data->lights;
  1280. r_directional_light_count = 0;
  1281. r_omni_light_count = 0;
  1282. r_spot_light_count = 0;
  1283. r_directional_shadow_count = 0;
  1284. int num_lights = lights.size();
  1285. for (int i = 0; i < num_lights; i++) {
  1286. GLES3::LightInstance *li = GLES3::LightStorage::get_singleton()->get_light_instance(lights[i]);
  1287. if (!li) {
  1288. continue;
  1289. }
  1290. RID base = li->light;
  1291. ERR_CONTINUE(base.is_null());
  1292. RS::LightType type = light_storage->light_get_type(base);
  1293. switch (type) {
  1294. case RS::LIGHT_DIRECTIONAL: {
  1295. if (r_directional_light_count >= RendererSceneRender::MAX_DIRECTIONAL_LIGHTS || light_storage->light_directional_get_sky_mode(base) == RS::LIGHT_DIRECTIONAL_SKY_MODE_SKY_ONLY) {
  1296. continue;
  1297. }
  1298. // If a DirectionalLight has shadows, we will add it to the end of the array and work in.
  1299. bool has_shadow = light_storage->light_has_shadow(base);
  1300. int index = r_directional_light_count - r_directional_shadow_count;
  1301. if (has_shadow) {
  1302. // Lights with shadow are incremented from the end of the array.
  1303. index = MAX_DIRECTIONAL_LIGHTS - 1 - r_directional_shadow_count;
  1304. }
  1305. DirectionalLightData &light_data = scene_state.directional_lights[index];
  1306. Transform3D light_transform = li->transform;
  1307. Vector3 direction = inverse_transform.basis.xform(light_transform.basis.xform(Vector3(0, 0, 1))).normalized();
  1308. light_data.direction[0] = direction.x;
  1309. light_data.direction[1] = direction.y;
  1310. light_data.direction[2] = direction.z;
  1311. float sign = light_storage->light_is_negative(base) ? -1 : 1;
  1312. light_data.energy = sign * light_storage->light_get_param(base, RS::LIGHT_PARAM_ENERGY);
  1313. if (is_using_physical_light_units()) {
  1314. light_data.energy *= light_storage->light_get_param(base, RS::LIGHT_PARAM_INTENSITY);
  1315. } else {
  1316. light_data.energy *= Math_PI;
  1317. }
  1318. if (p_render_data->camera_attributes.is_valid()) {
  1319. light_data.energy *= RSG::camera_attributes->camera_attributes_get_exposure_normalization_factor(p_render_data->camera_attributes);
  1320. }
  1321. Color linear_col = light_storage->light_get_color(base).srgb_to_linear();
  1322. light_data.color[0] = linear_col.r;
  1323. light_data.color[1] = linear_col.g;
  1324. light_data.color[2] = linear_col.b;
  1325. float size = light_storage->light_get_param(base, RS::LIGHT_PARAM_SIZE);
  1326. light_data.size = 1.0 - Math::cos(Math::deg_to_rad(size)); //angle to cosine offset
  1327. light_data.specular = light_storage->light_get_param(base, RS::LIGHT_PARAM_SPECULAR);
  1328. light_data.shadow_opacity = (p_using_shadows && light_storage->light_has_shadow(base))
  1329. ? light_storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_OPACITY)
  1330. : 0.0;
  1331. if (has_shadow) {
  1332. DirectionalShadowData &shadow_data = scene_state.directional_shadows[MAX_DIRECTIONAL_LIGHTS - 1 - r_directional_shadow_count];
  1333. RS::LightDirectionalShadowMode shadow_mode = light_storage->light_directional_get_shadow_mode(base);
  1334. int limit = shadow_mode == RS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL ? 0 : (shadow_mode == RS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS ? 1 : 3);
  1335. shadow_data.shadow_atlas_pixel_size = 1.0 / light_storage->directional_shadow_get_size();
  1336. shadow_data.blend_splits = uint32_t((shadow_mode != RS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL) && light_storage->light_directional_get_blend_splits(base));
  1337. for (int j = 0; j < 4; j++) {
  1338. Rect2 atlas_rect = li->shadow_transform[j].atlas_rect;
  1339. Projection matrix = li->shadow_transform[j].camera;
  1340. float split = li->shadow_transform[MIN(limit, j)].split;
  1341. Projection bias;
  1342. bias.set_light_bias();
  1343. Projection rectm;
  1344. rectm.set_light_atlas_rect(atlas_rect);
  1345. Transform3D modelview = (inverse_transform * li->shadow_transform[j].transform).inverse();
  1346. shadow_data.direction[0] = light_data.direction[0];
  1347. shadow_data.direction[1] = light_data.direction[1];
  1348. shadow_data.direction[2] = light_data.direction[2];
  1349. Projection shadow_mtx = rectm * bias * matrix * modelview;
  1350. shadow_data.shadow_split_offsets[j] = split;
  1351. 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;
  1352. GLES3::MaterialStorage::store_camera(shadow_mtx, shadow_data.shadow_matrices[j]);
  1353. }
  1354. float fade_start = light_storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_FADE_START);
  1355. shadow_data.fade_from = -shadow_data.shadow_split_offsets[3] * MIN(fade_start, 0.999);
  1356. shadow_data.fade_to = -shadow_data.shadow_split_offsets[3];
  1357. r_directional_shadow_count++;
  1358. }
  1359. r_directional_light_count++;
  1360. } break;
  1361. case RS::LIGHT_OMNI: {
  1362. if (r_omni_light_count >= (uint32_t)config->max_renderable_lights) {
  1363. continue;
  1364. }
  1365. const real_t distance = p_render_data->cam_transform.origin.distance_to(li->transform.origin);
  1366. if (light_storage->light_is_distance_fade_enabled(li->light)) {
  1367. const float fade_begin = light_storage->light_get_distance_fade_begin(li->light);
  1368. const float fade_length = light_storage->light_get_distance_fade_length(li->light);
  1369. if (distance > fade_begin) {
  1370. if (distance > fade_begin + fade_length) {
  1371. // Out of range, don't draw this light to improve performance.
  1372. continue;
  1373. }
  1374. }
  1375. }
  1376. scene_state.omni_light_sort[r_omni_light_count].instance = li;
  1377. scene_state.omni_light_sort[r_omni_light_count].depth = distance;
  1378. r_omni_light_count++;
  1379. } break;
  1380. case RS::LIGHT_SPOT: {
  1381. if (r_spot_light_count >= (uint32_t)config->max_renderable_lights) {
  1382. continue;
  1383. }
  1384. const real_t distance = p_render_data->cam_transform.origin.distance_to(li->transform.origin);
  1385. if (light_storage->light_is_distance_fade_enabled(li->light)) {
  1386. const float fade_begin = light_storage->light_get_distance_fade_begin(li->light);
  1387. const float fade_length = light_storage->light_get_distance_fade_length(li->light);
  1388. if (distance > fade_begin) {
  1389. if (distance > fade_begin + fade_length) {
  1390. // Out of range, don't draw this light to improve performance.
  1391. continue;
  1392. }
  1393. }
  1394. }
  1395. scene_state.spot_light_sort[r_spot_light_count].instance = li;
  1396. scene_state.spot_light_sort[r_spot_light_count].depth = distance;
  1397. r_spot_light_count++;
  1398. } break;
  1399. }
  1400. li->last_pass = RSG::rasterizer->get_frame_number();
  1401. }
  1402. if (r_omni_light_count) {
  1403. SortArray<InstanceSort<GLES3::LightInstance>> sorter;
  1404. sorter.sort(scene_state.omni_light_sort, r_omni_light_count);
  1405. }
  1406. if (r_spot_light_count) {
  1407. SortArray<InstanceSort<GLES3::LightInstance>> sorter;
  1408. sorter.sort(scene_state.spot_light_sort, r_spot_light_count);
  1409. }
  1410. int num_positional_shadows = 0;
  1411. for (uint32_t i = 0; i < (r_omni_light_count + r_spot_light_count); i++) {
  1412. uint32_t index = (i < r_omni_light_count) ? i : i - (r_omni_light_count);
  1413. LightData &light_data = (i < r_omni_light_count) ? scene_state.omni_lights[index] : scene_state.spot_lights[index];
  1414. RS::LightType type = (i < r_omni_light_count) ? RS::LIGHT_OMNI : RS::LIGHT_SPOT;
  1415. GLES3::LightInstance *li = (i < r_omni_light_count) ? scene_state.omni_light_sort[index].instance : scene_state.spot_light_sort[index].instance;
  1416. real_t distance = (i < r_omni_light_count) ? scene_state.omni_light_sort[index].depth : scene_state.spot_light_sort[index].depth;
  1417. RID base = li->light;
  1418. li->gl_id = index;
  1419. Transform3D light_transform = li->transform;
  1420. Vector3 pos = inverse_transform.xform(light_transform.origin);
  1421. light_data.position[0] = pos.x;
  1422. light_data.position[1] = pos.y;
  1423. light_data.position[2] = pos.z;
  1424. float radius = MAX(0.001, light_storage->light_get_param(base, RS::LIGHT_PARAM_RANGE));
  1425. light_data.inv_radius = 1.0 / radius;
  1426. Vector3 direction = inverse_transform.basis.xform(light_transform.basis.xform(Vector3(0, 0, -1))).normalized();
  1427. light_data.direction[0] = direction.x;
  1428. light_data.direction[1] = direction.y;
  1429. light_data.direction[2] = direction.z;
  1430. float size = light_storage->light_get_param(base, RS::LIGHT_PARAM_SIZE);
  1431. light_data.size = size;
  1432. float sign = light_storage->light_is_negative(base) ? -1 : 1;
  1433. Color linear_col = light_storage->light_get_color(base).srgb_to_linear();
  1434. // Reuse fade begin, fade length and distance for shadow LOD determination later.
  1435. float fade_begin = 0.0;
  1436. float fade_shadow = 0.0;
  1437. float fade_length = 0.0;
  1438. float fade = 1.0;
  1439. float shadow_opacity_fade = 1.0;
  1440. if (light_storage->light_is_distance_fade_enabled(base)) {
  1441. fade_begin = light_storage->light_get_distance_fade_begin(base);
  1442. fade_shadow = light_storage->light_get_distance_fade_shadow(base);
  1443. fade_length = light_storage->light_get_distance_fade_length(base);
  1444. if (distance > fade_begin) {
  1445. // Use `smoothstep()` to make opacity changes more gradual and less noticeable to the player.
  1446. fade = Math::smoothstep(0.0f, 1.0f, 1.0f - float(distance - fade_begin) / fade_length);
  1447. }
  1448. if (distance > fade_shadow) {
  1449. shadow_opacity_fade = Math::smoothstep(0.0f, 1.0f, 1.0f - float(distance - fade_shadow) / fade_length);
  1450. }
  1451. }
  1452. float energy = sign * light_storage->light_get_param(base, RS::LIGHT_PARAM_ENERGY) * fade;
  1453. if (is_using_physical_light_units()) {
  1454. energy *= light_storage->light_get_param(base, RS::LIGHT_PARAM_INTENSITY);
  1455. // Convert from Luminous Power to Luminous Intensity
  1456. if (type == RS::LIGHT_OMNI) {
  1457. energy *= 1.0 / (Math_PI * 4.0);
  1458. } else {
  1459. // Spot Lights are not physically accurate, Luminous Intensity should change in relation to the cone angle.
  1460. // We make this assumption to keep them easy to control.
  1461. energy *= 1.0 / Math_PI;
  1462. }
  1463. } else {
  1464. energy *= Math_PI;
  1465. }
  1466. if (p_render_data->camera_attributes.is_valid()) {
  1467. energy *= RSG::camera_attributes->camera_attributes_get_exposure_normalization_factor(p_render_data->camera_attributes);
  1468. }
  1469. light_data.color[0] = linear_col.r * energy;
  1470. light_data.color[1] = linear_col.g * energy;
  1471. light_data.color[2] = linear_col.b * energy;
  1472. light_data.attenuation = light_storage->light_get_param(base, RS::LIGHT_PARAM_ATTENUATION);
  1473. light_data.inv_spot_attenuation = 1.0f / light_storage->light_get_param(base, RS::LIGHT_PARAM_SPOT_ATTENUATION);
  1474. float spot_angle = light_storage->light_get_param(base, RS::LIGHT_PARAM_SPOT_ANGLE);
  1475. light_data.cos_spot_angle = Math::cos(Math::deg_to_rad(spot_angle));
  1476. light_data.specular_amount = light_storage->light_get_param(base, RS::LIGHT_PARAM_SPECULAR) * 2.0;
  1477. // Setup shadows
  1478. const bool needs_shadow =
  1479. p_using_shadows &&
  1480. light_storage->owns_shadow_atlas(p_render_data->shadow_atlas) &&
  1481. light_storage->shadow_atlas_owns_light_instance(p_render_data->shadow_atlas, li->self) &&
  1482. light_storage->light_has_shadow(base);
  1483. bool in_shadow_range = true;
  1484. if (needs_shadow && light_storage->light_is_distance_fade_enabled(base)) {
  1485. if (distance > fade_shadow + fade_length) {
  1486. // Out of range, don't draw shadows to improve performance.
  1487. in_shadow_range = false;
  1488. }
  1489. }
  1490. // Fill in the shadow information.
  1491. if (needs_shadow && in_shadow_range) {
  1492. if (num_positional_shadows >= config->max_renderable_lights) {
  1493. continue;
  1494. }
  1495. ShadowData &shadow_data = scene_state.positional_shadows[num_positional_shadows];
  1496. li->shadow_id = num_positional_shadows;
  1497. num_positional_shadows++;
  1498. light_data.shadow_opacity = light_storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_OPACITY) * shadow_opacity_fade;
  1499. float shadow_texel_size = light_storage->light_instance_get_shadow_texel_size(li->self, p_render_data->shadow_atlas);
  1500. shadow_data.shadow_atlas_pixel_size = shadow_texel_size;
  1501. shadow_data.shadow_normal_bias = light_storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_NORMAL_BIAS) * shadow_texel_size * 10.0;
  1502. shadow_data.light_position[0] = light_data.position[0];
  1503. shadow_data.light_position[1] = light_data.position[1];
  1504. shadow_data.light_position[2] = light_data.position[2];
  1505. if (type == RS::LIGHT_OMNI) {
  1506. Transform3D proj = (inverse_transform * light_transform).inverse();
  1507. GLES3::MaterialStorage::store_transform(proj, shadow_data.shadow_matrix);
  1508. } else if (type == RS::LIGHT_SPOT) {
  1509. Transform3D modelview = (inverse_transform * light_transform).inverse();
  1510. Projection bias;
  1511. bias.set_light_bias();
  1512. Projection cm = li->shadow_transform[0].camera;
  1513. Projection shadow_mtx = bias * cm * modelview;
  1514. GLES3::MaterialStorage::store_camera(shadow_mtx, shadow_data.shadow_matrix);
  1515. }
  1516. }
  1517. }
  1518. // TODO, to avoid stalls, should rotate between 3 buffers based on frame index.
  1519. // TODO, consider mapping the buffer as in 2D
  1520. glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_OMNILIGHT_UNIFORM_LOCATION, scene_state.omni_light_buffer);
  1521. if (r_omni_light_count) {
  1522. glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(LightData) * r_omni_light_count, scene_state.omni_lights);
  1523. }
  1524. glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_SPOTLIGHT_UNIFORM_LOCATION, scene_state.spot_light_buffer);
  1525. if (r_spot_light_count) {
  1526. glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(LightData) * r_spot_light_count, scene_state.spot_lights);
  1527. }
  1528. glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_DIRECTIONAL_LIGHT_UNIFORM_LOCATION, scene_state.directional_light_buffer);
  1529. if (r_directional_light_count) {
  1530. glBufferData(GL_UNIFORM_BUFFER, sizeof(DirectionalLightData) * MAX_DIRECTIONAL_LIGHTS, scene_state.directional_lights, GL_STREAM_DRAW);
  1531. }
  1532. glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_POSITIONAL_SHADOW_UNIFORM_LOCATION, scene_state.positional_shadow_buffer);
  1533. if (num_positional_shadows) {
  1534. glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(ShadowData) * num_positional_shadows, scene_state.positional_shadows);
  1535. }
  1536. glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_DIRECTIONAL_SHADOW_UNIFORM_LOCATION, scene_state.directional_shadow_buffer);
  1537. if (r_directional_shadow_count) {
  1538. glBufferData(GL_UNIFORM_BUFFER, sizeof(DirectionalShadowData) * MAX_DIRECTIONAL_LIGHTS, scene_state.directional_shadows, GL_STREAM_DRAW);
  1539. }
  1540. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  1541. }
  1542. // Render shadows
  1543. void RasterizerSceneGLES3::_render_shadows(const RenderDataGLES3 *p_render_data, const Size2i &p_viewport_size) {
  1544. GLES3::LightStorage *light_storage = GLES3::LightStorage::get_singleton();
  1545. LocalVector<int> cube_shadows;
  1546. LocalVector<int> shadows;
  1547. LocalVector<int> directional_shadows;
  1548. Plane camera_plane(-p_render_data->cam_transform.basis.get_column(Vector3::AXIS_Z), p_render_data->cam_transform.origin);
  1549. float lod_distance_multiplier = p_render_data->cam_projection.get_lod_multiplier();
  1550. // Put lights into buckets for omni (cube shadows), directional, and spot.
  1551. {
  1552. for (int i = 0; i < p_render_data->render_shadow_count; i++) {
  1553. RID li = p_render_data->render_shadows[i].light;
  1554. RID base = light_storage->light_instance_get_base_light(li);
  1555. if (light_storage->light_get_type(base) == RS::LIGHT_DIRECTIONAL) {
  1556. directional_shadows.push_back(i);
  1557. } else if (light_storage->light_get_type(base) == RS::LIGHT_OMNI && light_storage->light_omni_get_shadow_mode(base) == RS::LIGHT_OMNI_SHADOW_CUBE) {
  1558. cube_shadows.push_back(i);
  1559. } else {
  1560. shadows.push_back(i);
  1561. }
  1562. }
  1563. if (directional_shadows.size()) {
  1564. light_storage->update_directional_shadow_atlas();
  1565. }
  1566. }
  1567. bool render_shadows = directional_shadows.size() || shadows.size() || cube_shadows.size();
  1568. if (render_shadows) {
  1569. RENDER_TIMESTAMP("Render Shadows");
  1570. // Render cubemap shadows.
  1571. for (const int &index : cube_shadows) {
  1572. _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, camera_plane, lod_distance_multiplier, p_render_data->screen_mesh_lod_threshold, p_render_data->render_info, p_viewport_size);
  1573. }
  1574. // Render directional shadows.
  1575. for (uint32_t i = 0; i < directional_shadows.size(); i++) {
  1576. _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, camera_plane, lod_distance_multiplier, p_render_data->screen_mesh_lod_threshold, p_render_data->render_info, p_viewport_size);
  1577. }
  1578. // Render positional shadows (Spotlight and Omnilight with dual-paraboloid).
  1579. for (uint32_t i = 0; i < shadows.size(); i++) {
  1580. _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, camera_plane, lod_distance_multiplier, p_render_data->screen_mesh_lod_threshold, p_render_data->render_info, p_viewport_size);
  1581. }
  1582. }
  1583. }
  1584. void RasterizerSceneGLES3::_render_shadow_pass(RID p_light, RID p_shadow_atlas, int p_pass, const PagedArray<RenderGeometryInstance *> &p_instances, const Plane &p_camera_plane, float p_lod_distance_multiplier, float p_screen_mesh_lod_threshold, RenderingMethod::RenderInfo *p_render_info, const Size2i &p_viewport_size) {
  1585. GLES3::LightStorage *light_storage = GLES3::LightStorage::get_singleton();
  1586. ERR_FAIL_COND(!light_storage->owns_light_instance(p_light));
  1587. RID base = light_storage->light_instance_get_base_light(p_light);
  1588. float zfar = 0.0;
  1589. bool use_pancake = false;
  1590. float shadow_bias = 0.0;
  1591. bool reverse_cull = false;
  1592. bool needs_clear = false;
  1593. Projection light_projection;
  1594. Transform3D light_transform;
  1595. GLuint shadow_fb = 0;
  1596. Rect2i atlas_rect;
  1597. if (light_storage->light_get_type(base) == RS::LIGHT_DIRECTIONAL) {
  1598. // Set pssm stuff.
  1599. uint64_t last_scene_shadow_pass = light_storage->light_instance_get_shadow_pass(p_light);
  1600. if (last_scene_shadow_pass != get_scene_pass()) {
  1601. light_storage->light_instance_set_directional_rect(p_light, light_storage->get_directional_shadow_rect());
  1602. light_storage->directional_shadow_increase_current_light();
  1603. light_storage->light_instance_set_shadow_pass(p_light, get_scene_pass());
  1604. }
  1605. atlas_rect = light_storage->light_instance_get_directional_rect(p_light);
  1606. if (light_storage->light_directional_get_shadow_mode(base) == RS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS) {
  1607. atlas_rect.size.width /= 2;
  1608. atlas_rect.size.height /= 2;
  1609. if (p_pass == 1) {
  1610. atlas_rect.position.x += atlas_rect.size.width;
  1611. } else if (p_pass == 2) {
  1612. atlas_rect.position.y += atlas_rect.size.height;
  1613. } else if (p_pass == 3) {
  1614. atlas_rect.position += atlas_rect.size;
  1615. }
  1616. } else if (light_storage->light_directional_get_shadow_mode(base) == RS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS) {
  1617. atlas_rect.size.height /= 2;
  1618. if (p_pass == 0) {
  1619. } else {
  1620. atlas_rect.position.y += atlas_rect.size.height;
  1621. }
  1622. }
  1623. use_pancake = light_storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_PANCAKE_SIZE) > 0;
  1624. light_projection = light_storage->light_instance_get_shadow_camera(p_light, p_pass);
  1625. light_transform = light_storage->light_instance_get_shadow_transform(p_light, p_pass);
  1626. float directional_shadow_size = light_storage->directional_shadow_get_size();
  1627. Rect2 atlas_rect_norm = atlas_rect;
  1628. atlas_rect_norm.position /= directional_shadow_size;
  1629. atlas_rect_norm.size /= directional_shadow_size;
  1630. light_storage->light_instance_set_directional_shadow_atlas_rect(p_light, p_pass, atlas_rect_norm);
  1631. zfar = RSG::light_storage->light_get_param(base, RS::LIGHT_PARAM_RANGE);
  1632. shadow_fb = light_storage->direction_shadow_get_fb();
  1633. reverse_cull = !light_storage->light_get_reverse_cull_face_mode(base);
  1634. float bias_scale = light_storage->light_instance_get_shadow_bias_scale(p_light, p_pass);
  1635. shadow_bias = light_storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_BIAS) / 100.0 * bias_scale;
  1636. } else {
  1637. // Set from shadow atlas.
  1638. ERR_FAIL_COND(!light_storage->owns_shadow_atlas(p_shadow_atlas));
  1639. ERR_FAIL_COND(!light_storage->shadow_atlas_owns_light_instance(p_shadow_atlas, p_light));
  1640. uint32_t key = light_storage->shadow_atlas_get_light_instance_key(p_shadow_atlas, p_light);
  1641. uint32_t quadrant = (key >> GLES3::LightStorage::QUADRANT_SHIFT) & 0x3;
  1642. uint32_t shadow = key & GLES3::LightStorage::SHADOW_INDEX_MASK;
  1643. ERR_FAIL_INDEX((int)shadow, light_storage->shadow_atlas_get_quadrant_shadows_length(p_shadow_atlas, quadrant));
  1644. int shadow_size = light_storage->shadow_atlas_get_quadrant_shadow_size(p_shadow_atlas, quadrant);
  1645. shadow_fb = light_storage->shadow_atlas_get_quadrant_shadow_fb(p_shadow_atlas, quadrant, shadow);
  1646. zfar = light_storage->light_get_param(base, RS::LIGHT_PARAM_RANGE);
  1647. reverse_cull = !light_storage->light_get_reverse_cull_face_mode(base);
  1648. if (light_storage->light_get_type(base) == RS::LIGHT_OMNI) {
  1649. if (light_storage->light_omni_get_shadow_mode(base) == RS::LIGHT_OMNI_SHADOW_CUBE) {
  1650. GLuint shadow_texture = light_storage->shadow_atlas_get_quadrant_shadow_texture(p_shadow_atlas, quadrant, shadow);
  1651. glBindFramebuffer(GL_FRAMEBUFFER, shadow_fb);
  1652. static GLenum cube_map_faces[6] = {
  1653. GL_TEXTURE_CUBE_MAP_POSITIVE_X,
  1654. GL_TEXTURE_CUBE_MAP_NEGATIVE_X,
  1655. // Flipped order for Y to match what the RD renderer expects
  1656. // (and thus what is given to us by the Rendering Server).
  1657. GL_TEXTURE_CUBE_MAP_NEGATIVE_Y,
  1658. GL_TEXTURE_CUBE_MAP_POSITIVE_Y,
  1659. GL_TEXTURE_CUBE_MAP_POSITIVE_Z,
  1660. GL_TEXTURE_CUBE_MAP_NEGATIVE_Z
  1661. };
  1662. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, cube_map_faces[p_pass], shadow_texture, 0);
  1663. light_projection = light_storage->light_instance_get_shadow_camera(p_light, p_pass);
  1664. light_transform = light_storage->light_instance_get_shadow_transform(p_light, p_pass);
  1665. shadow_size = shadow_size / 2;
  1666. } else {
  1667. ERR_FAIL_MSG("Dual paraboloid shadow mode not supported in GL Compatibility renderer. Please use Cubemap shadow mode instead.");
  1668. }
  1669. shadow_bias = light_storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_BIAS);
  1670. } else if (light_storage->light_get_type(base) == RS::LIGHT_SPOT) {
  1671. light_projection = light_storage->light_instance_get_shadow_camera(p_light, 0);
  1672. light_transform = light_storage->light_instance_get_shadow_transform(p_light, 0);
  1673. shadow_bias = light_storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_BIAS) / 10.0;
  1674. // Prebake range into bias so we can scale based on distance easily.
  1675. shadow_bias *= light_storage->light_get_param(base, RS::LIGHT_PARAM_RANGE);
  1676. }
  1677. atlas_rect.size.x = shadow_size;
  1678. atlas_rect.size.y = shadow_size;
  1679. needs_clear = true;
  1680. }
  1681. RenderDataGLES3 render_data;
  1682. render_data.cam_projection = light_projection;
  1683. render_data.cam_transform = light_transform;
  1684. render_data.inv_cam_transform = light_transform.affine_inverse();
  1685. render_data.z_far = zfar; // Only used by OmniLights.
  1686. render_data.z_near = 0.0;
  1687. render_data.lod_distance_multiplier = p_lod_distance_multiplier;
  1688. render_data.instances = &p_instances;
  1689. render_data.render_info = p_render_info;
  1690. _setup_environment(&render_data, true, p_viewport_size, false, Color(), use_pancake, shadow_bias);
  1691. if (get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_DISABLE_LOD) {
  1692. render_data.screen_mesh_lod_threshold = 0.0;
  1693. } else {
  1694. render_data.screen_mesh_lod_threshold = p_screen_mesh_lod_threshold;
  1695. }
  1696. _fill_render_list(RENDER_LIST_SECONDARY, &render_data, PASS_MODE_SHADOW);
  1697. render_list[RENDER_LIST_SECONDARY].sort_by_key();
  1698. glBindFramebuffer(GL_FRAMEBUFFER, shadow_fb);
  1699. glViewport(atlas_rect.position.x, atlas_rect.position.y, atlas_rect.size.x, atlas_rect.size.y);
  1700. GLuint global_buffer = GLES3::MaterialStorage::get_singleton()->global_shader_parameters_get_uniform_buffer();
  1701. glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_GLOBALS_UNIFORM_LOCATION, global_buffer);
  1702. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  1703. glDisable(GL_BLEND);
  1704. glDepthMask(GL_TRUE);
  1705. glEnable(GL_DEPTH_TEST);
  1706. glDepthFunc(GL_LESS);
  1707. glDisable(GL_SCISSOR_TEST);
  1708. glCullFace(GL_BACK);
  1709. glEnable(GL_CULL_FACE);
  1710. scene_state.cull_mode = GLES3::SceneShaderData::CULL_BACK;
  1711. glColorMask(0, 0, 0, 0);
  1712. RasterizerGLES3::clear_depth(1.0);
  1713. if (needs_clear) {
  1714. glClear(GL_DEPTH_BUFFER_BIT);
  1715. }
  1716. uint64_t spec_constant_base_flags = SceneShaderGLES3::DISABLE_LIGHTMAP |
  1717. SceneShaderGLES3::DISABLE_LIGHT_DIRECTIONAL |
  1718. SceneShaderGLES3::DISABLE_LIGHT_OMNI |
  1719. SceneShaderGLES3::DISABLE_LIGHT_SPOT |
  1720. SceneShaderGLES3::DISABLE_FOG |
  1721. SceneShaderGLES3::RENDER_SHADOWS;
  1722. if (light_storage->light_get_type(base) == RS::LIGHT_OMNI) {
  1723. spec_constant_base_flags |= SceneShaderGLES3::RENDER_SHADOWS_LINEAR;
  1724. }
  1725. 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);
  1726. _render_list_template<PASS_MODE_SHADOW>(&render_list_params, &render_data, 0, render_list[RENDER_LIST_SECONDARY].elements.size());
  1727. glColorMask(1, 1, 1, 1);
  1728. glDisable(GL_DEPTH_TEST);
  1729. glDepthMask(GL_FALSE);
  1730. glDisable(GL_CULL_FACE);
  1731. scene_state.cull_mode = GLES3::SceneShaderData::CULL_DISABLED;
  1732. glBindFramebuffer(GL_FRAMEBUFFER, 0);
  1733. }
  1734. 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_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) {
  1735. GLES3::TextureStorage *texture_storage = GLES3::TextureStorage::get_singleton();
  1736. GLES3::Config *config = GLES3::Config::get_singleton();
  1737. RENDER_TIMESTAMP("Setup 3D Scene");
  1738. Ref<RenderSceneBuffersGLES3> rb;
  1739. if (p_render_buffers.is_valid()) {
  1740. rb = p_render_buffers;
  1741. ERR_FAIL_COND(rb.is_null());
  1742. }
  1743. GLES3::RenderTarget *rt = texture_storage->get_render_target(rb->render_target);
  1744. ERR_FAIL_NULL(rt);
  1745. // Assign render data
  1746. // Use the format from rendererRD
  1747. RenderDataGLES3 render_data;
  1748. {
  1749. render_data.render_buffers = rb;
  1750. render_data.transparent_bg = rb.is_valid() ? rt->is_transparent : false;
  1751. // Our first camera is used by default
  1752. render_data.cam_transform = p_camera_data->main_transform;
  1753. render_data.inv_cam_transform = render_data.cam_transform.affine_inverse();
  1754. render_data.cam_projection = p_camera_data->main_projection;
  1755. render_data.cam_orthogonal = p_camera_data->is_orthogonal;
  1756. render_data.camera_visible_layers = p_camera_data->visible_layers;
  1757. render_data.view_count = p_camera_data->view_count;
  1758. for (uint32_t v = 0; v < p_camera_data->view_count; v++) {
  1759. render_data.view_eye_offset[v] = p_camera_data->view_offset[v].origin;
  1760. render_data.view_projection[v] = p_camera_data->view_projection[v];
  1761. }
  1762. render_data.z_near = p_camera_data->main_projection.get_z_near();
  1763. render_data.z_far = p_camera_data->main_projection.get_z_far();
  1764. render_data.instances = &p_instances;
  1765. render_data.lights = &p_lights;
  1766. render_data.reflection_probes = &p_reflection_probes;
  1767. render_data.environment = p_environment;
  1768. render_data.camera_attributes = p_camera_attributes;
  1769. render_data.shadow_atlas = p_shadow_atlas;
  1770. render_data.reflection_probe = p_reflection_probe;
  1771. render_data.reflection_probe_pass = p_reflection_probe_pass;
  1772. // this should be the same for all cameras..
  1773. render_data.lod_distance_multiplier = p_camera_data->main_projection.get_lod_multiplier();
  1774. if (get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_DISABLE_LOD) {
  1775. render_data.screen_mesh_lod_threshold = 0.0;
  1776. } else {
  1777. render_data.screen_mesh_lod_threshold = p_screen_mesh_lod_threshold;
  1778. }
  1779. render_data.render_info = r_render_info;
  1780. render_data.render_shadows = p_render_shadows;
  1781. render_data.render_shadow_count = p_render_shadow_count;
  1782. }
  1783. PagedArray<RID> empty;
  1784. if (get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_UNSHADED) {
  1785. render_data.lights = &empty;
  1786. render_data.reflection_probes = &empty;
  1787. }
  1788. bool reverse_cull = render_data.cam_transform.basis.determinant() < 0;
  1789. ///////////
  1790. // Fill Light lists here
  1791. //////////
  1792. GLuint global_buffer = GLES3::MaterialStorage::get_singleton()->global_shader_parameters_get_uniform_buffer();
  1793. glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_GLOBALS_UNIFORM_LOCATION, global_buffer);
  1794. Color clear_color;
  1795. if (p_render_buffers.is_valid()) {
  1796. clear_color = texture_storage->render_target_get_clear_request_color(rb->render_target);
  1797. } else {
  1798. clear_color = texture_storage->get_default_clear_color();
  1799. }
  1800. bool fb_cleared = false;
  1801. Size2i screen_size;
  1802. screen_size.x = rb->width;
  1803. screen_size.y = rb->height;
  1804. bool use_wireframe = get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_WIREFRAME;
  1805. SceneState::TonemapUBO tonemap_ubo;
  1806. if (render_data.environment.is_valid()) {
  1807. tonemap_ubo.exposure = environment_get_exposure(render_data.environment);
  1808. tonemap_ubo.white = environment_get_white(render_data.environment);
  1809. tonemap_ubo.tonemapper = int32_t(environment_get_tone_mapper(render_data.environment));
  1810. }
  1811. if (scene_state.tonemap_buffer == 0) {
  1812. // Only create if using 3D
  1813. glGenBuffers(1, &scene_state.tonemap_buffer);
  1814. glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_TONEMAP_UNIFORM_LOCATION, scene_state.tonemap_buffer);
  1815. GLES3::Utilities::get_singleton()->buffer_allocate_data(GL_UNIFORM_BUFFER, scene_state.tonemap_buffer, sizeof(SceneState::TonemapUBO), &tonemap_ubo, GL_STREAM_DRAW, "Tonemap UBO");
  1816. } else {
  1817. glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_TONEMAP_UNIFORM_LOCATION, scene_state.tonemap_buffer);
  1818. glBufferData(GL_UNIFORM_BUFFER, sizeof(SceneState::TonemapUBO), &tonemap_ubo, GL_STREAM_DRAW);
  1819. }
  1820. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  1821. scene_state.ubo.emissive_exposure_normalization = -1.0; // Use default exposure normalization.
  1822. bool flip_y = !render_data.reflection_probe.is_valid();
  1823. if (rt->overridden.color.is_valid()) {
  1824. // If we've overridden the render target's color texture, then don't render upside down.
  1825. // We're probably rendering directly to an XR device.
  1826. flip_y = false;
  1827. }
  1828. if (!flip_y) {
  1829. // If we're rendering right-side up, then we need to change the winding order.
  1830. glFrontFace(GL_CW);
  1831. }
  1832. _render_shadows(&render_data, screen_size);
  1833. _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);
  1834. _setup_environment(&render_data, render_data.reflection_probe.is_valid(), screen_size, flip_y, clear_color, false);
  1835. _fill_render_list(RENDER_LIST_OPAQUE, &render_data, PASS_MODE_COLOR);
  1836. render_list[RENDER_LIST_OPAQUE].sort_by_key();
  1837. render_list[RENDER_LIST_ALPHA].sort_by_reverse_depth_and_priority();
  1838. bool draw_sky = false;
  1839. bool draw_sky_fog_only = false;
  1840. bool keep_color = false;
  1841. float sky_energy_multiplier = 1.0;
  1842. if (unlikely(get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_OVERDRAW)) {
  1843. clear_color = Color(0, 0, 0, 1); //in overdraw mode, BG should always be black
  1844. } else if (render_data.environment.is_valid()) {
  1845. RS::EnvironmentBG bg_mode = environment_get_background(render_data.environment);
  1846. float bg_energy_multiplier = environment_get_bg_energy_multiplier(render_data.environment);
  1847. bg_energy_multiplier *= environment_get_bg_intensity(render_data.environment);
  1848. if (render_data.camera_attributes.is_valid()) {
  1849. bg_energy_multiplier *= RSG::camera_attributes->camera_attributes_get_exposure_normalization_factor(render_data.camera_attributes);
  1850. }
  1851. switch (bg_mode) {
  1852. case RS::ENV_BG_CLEAR_COLOR: {
  1853. clear_color.r *= bg_energy_multiplier;
  1854. clear_color.g *= bg_energy_multiplier;
  1855. clear_color.b *= bg_energy_multiplier;
  1856. if (environment_get_fog_enabled(render_data.environment)) {
  1857. draw_sky_fog_only = true;
  1858. GLES3::MaterialStorage::get_singleton()->material_set_param(sky_globals.fog_material, "clear_color", Variant(clear_color));
  1859. }
  1860. } break;
  1861. case RS::ENV_BG_COLOR: {
  1862. clear_color = environment_get_bg_color(render_data.environment);
  1863. clear_color.r *= bg_energy_multiplier;
  1864. clear_color.g *= bg_energy_multiplier;
  1865. clear_color.b *= bg_energy_multiplier;
  1866. if (environment_get_fog_enabled(render_data.environment)) {
  1867. draw_sky_fog_only = true;
  1868. GLES3::MaterialStorage::get_singleton()->material_set_param(sky_globals.fog_material, "clear_color", Variant(clear_color));
  1869. }
  1870. } break;
  1871. case RS::ENV_BG_SKY: {
  1872. draw_sky = true;
  1873. } break;
  1874. case RS::ENV_BG_CANVAS: {
  1875. keep_color = true;
  1876. } break;
  1877. case RS::ENV_BG_KEEP: {
  1878. keep_color = true;
  1879. } break;
  1880. case RS::ENV_BG_CAMERA_FEED: {
  1881. } break;
  1882. default: {
  1883. }
  1884. }
  1885. // setup sky if used for ambient, reflections, or background
  1886. if (draw_sky || draw_sky_fog_only || environment_get_reflection_source(render_data.environment) == RS::ENV_REFLECTION_SOURCE_SKY || environment_get_ambient_source(render_data.environment) == RS::ENV_AMBIENT_SOURCE_SKY) {
  1887. RENDER_TIMESTAMP("Setup Sky");
  1888. Projection projection = render_data.cam_projection;
  1889. if (render_data.reflection_probe.is_valid()) {
  1890. Projection correction;
  1891. correction.columns[1][1] = -1.0;
  1892. projection = correction * render_data.cam_projection;
  1893. }
  1894. sky_energy_multiplier *= bg_energy_multiplier;
  1895. _setup_sky(&render_data, *render_data.lights, projection, render_data.cam_transform, screen_size);
  1896. if (environment_get_sky(render_data.environment).is_valid()) {
  1897. if (environment_get_reflection_source(render_data.environment) == RS::ENV_REFLECTION_SOURCE_SKY || environment_get_ambient_source(render_data.environment) == RS::ENV_AMBIENT_SOURCE_SKY || (environment_get_reflection_source(render_data.environment) == RS::ENV_REFLECTION_SOURCE_BG && environment_get_background(render_data.environment) == RS::ENV_BG_SKY)) {
  1898. _update_sky_radiance(render_data.environment, projection, render_data.cam_transform, sky_energy_multiplier);
  1899. }
  1900. } else {
  1901. // do not try to draw sky if invalid
  1902. draw_sky = false;
  1903. }
  1904. }
  1905. }
  1906. glBindFramebuffer(GL_FRAMEBUFFER, rt->fbo);
  1907. glViewport(0, 0, rb->width, rb->height);
  1908. glCullFace(GL_BACK);
  1909. glEnable(GL_CULL_FACE);
  1910. scene_state.cull_mode = GLES3::SceneShaderData::CULL_BACK;
  1911. // Do depth prepass if it's explicitly enabled
  1912. bool use_depth_prepass = config->use_depth_prepass;
  1913. // Don't do depth prepass we are rendering overdraw
  1914. use_depth_prepass = use_depth_prepass && get_debug_draw_mode() != RS::VIEWPORT_DEBUG_DRAW_OVERDRAW;
  1915. if (use_depth_prepass) {
  1916. RENDER_TIMESTAMP("Depth Prepass");
  1917. //pre z pass
  1918. glDisable(GL_BLEND);
  1919. glDepthMask(GL_TRUE);
  1920. glEnable(GL_DEPTH_TEST);
  1921. glDepthFunc(GL_LEQUAL);
  1922. glDisable(GL_SCISSOR_TEST);
  1923. glColorMask(0, 0, 0, 0);
  1924. RasterizerGLES3::clear_depth(1.0);
  1925. glClear(GL_DEPTH_BUFFER_BIT);
  1926. uint64_t spec_constant = SceneShaderGLES3::DISABLE_FOG | SceneShaderGLES3::DISABLE_LIGHT_DIRECTIONAL |
  1927. SceneShaderGLES3::DISABLE_LIGHTMAP | SceneShaderGLES3::DISABLE_LIGHT_OMNI |
  1928. SceneShaderGLES3::DISABLE_LIGHT_SPOT;
  1929. RenderListParameters render_list_params(render_list[RENDER_LIST_OPAQUE].elements.ptr(), render_list[RENDER_LIST_OPAQUE].elements.size(), reverse_cull, spec_constant, use_wireframe);
  1930. _render_list_template<PASS_MODE_DEPTH>(&render_list_params, &render_data, 0, render_list[RENDER_LIST_OPAQUE].elements.size());
  1931. glColorMask(1, 1, 1, 1);
  1932. fb_cleared = true;
  1933. scene_state.used_depth_prepass = true;
  1934. } else {
  1935. scene_state.used_depth_prepass = false;
  1936. }
  1937. glBlendEquation(GL_FUNC_ADD);
  1938. if (render_data.transparent_bg) {
  1939. glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
  1940. glEnable(GL_BLEND);
  1941. } else {
  1942. glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ZERO, GL_ONE);
  1943. glDisable(GL_BLEND);
  1944. }
  1945. scene_state.current_blend_mode = GLES3::SceneShaderData::BLEND_MODE_MIX;
  1946. glEnable(GL_DEPTH_TEST);
  1947. glDepthFunc(GL_LEQUAL);
  1948. glDepthMask(GL_TRUE);
  1949. scene_state.current_depth_test = GLES3::SceneShaderData::DEPTH_TEST_ENABLED;
  1950. scene_state.current_depth_draw = GLES3::SceneShaderData::DEPTH_DRAW_ALWAYS;
  1951. if (!fb_cleared) {
  1952. RasterizerGLES3::clear_depth(1.0);
  1953. glClear(GL_DEPTH_BUFFER_BIT);
  1954. }
  1955. if (!keep_color) {
  1956. clear_color.a = render_data.transparent_bg ? 0.0f : 1.0f;
  1957. glClearBufferfv(GL_COLOR, 0, clear_color.components);
  1958. }
  1959. RENDER_TIMESTAMP("Render Opaque Pass");
  1960. uint64_t spec_constant_base_flags = 0;
  1961. {
  1962. // Specialization Constants that apply for entire rendering pass.
  1963. if (render_data.directional_light_count == 0) {
  1964. spec_constant_base_flags |= SceneShaderGLES3::DISABLE_LIGHT_DIRECTIONAL;
  1965. }
  1966. if (render_data.environment.is_null() || (render_data.environment.is_valid() && !environment_get_fog_enabled(render_data.environment))) {
  1967. spec_constant_base_flags |= SceneShaderGLES3::DISABLE_FOG;
  1968. }
  1969. }
  1970. // Render Opaque Objects.
  1971. 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);
  1972. _render_list_template<PASS_MODE_COLOR>(&render_list_params, &render_data, 0, render_list[RENDER_LIST_OPAQUE].elements.size());
  1973. glDepthMask(GL_FALSE);
  1974. scene_state.current_depth_draw = GLES3::SceneShaderData::DEPTH_DRAW_DISABLED;
  1975. if (draw_sky) {
  1976. RENDER_TIMESTAMP("Render Sky");
  1977. glEnable(GL_DEPTH_TEST);
  1978. glDisable(GL_BLEND);
  1979. glEnable(GL_CULL_FACE);
  1980. glCullFace(GL_BACK);
  1981. scene_state.current_depth_test = GLES3::SceneShaderData::DEPTH_TEST_ENABLED;
  1982. scene_state.cull_mode = GLES3::SceneShaderData::CULL_BACK;
  1983. _draw_sky(render_data.environment, render_data.cam_projection, render_data.cam_transform, sky_energy_multiplier, p_camera_data->view_count > 1, flip_y);
  1984. }
  1985. if (scene_state.used_screen_texture || scene_state.used_depth_texture) {
  1986. texture_storage->copy_scene_to_backbuffer(rt, scene_state.used_screen_texture, scene_state.used_depth_texture);
  1987. glBindFramebuffer(GL_READ_FRAMEBUFFER, rt->fbo);
  1988. glReadBuffer(GL_COLOR_ATTACHMENT0);
  1989. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, rt->backbuffer_fbo);
  1990. if (scene_state.used_screen_texture) {
  1991. glBlitFramebuffer(0, 0, rt->size.x, rt->size.y,
  1992. 0, 0, rt->size.x, rt->size.y,
  1993. GL_COLOR_BUFFER_BIT, GL_NEAREST);
  1994. glActiveTexture(GL_TEXTURE0 + config->max_texture_image_units - 5);
  1995. glBindTexture(GL_TEXTURE_2D, rt->backbuffer);
  1996. }
  1997. if (scene_state.used_depth_texture) {
  1998. glBlitFramebuffer(0, 0, rt->size.x, rt->size.y,
  1999. 0, 0, rt->size.x, rt->size.y,
  2000. GL_DEPTH_BUFFER_BIT, GL_NEAREST);
  2001. glActiveTexture(GL_TEXTURE0 + config->max_texture_image_units - 6);
  2002. glBindTexture(GL_TEXTURE_2D, rt->backbuffer_depth);
  2003. }
  2004. glBindFramebuffer(GL_FRAMEBUFFER, rt->fbo);
  2005. }
  2006. RENDER_TIMESTAMP("Render 3D Transparent Pass");
  2007. glEnable(GL_BLEND);
  2008. //Render transparent pass
  2009. 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);
  2010. _render_list_template<PASS_MODE_COLOR_TRANSPARENT>(&render_list_params_alpha, &render_data, 0, render_list[RENDER_LIST_ALPHA].elements.size(), true);
  2011. if (!flip_y) {
  2012. // Restore the default winding order.
  2013. glFrontFace(GL_CCW);
  2014. }
  2015. if (rb.is_valid()) {
  2016. _render_buffers_debug_draw(rb, p_shadow_atlas);
  2017. }
  2018. glDisable(GL_BLEND);
  2019. texture_storage->render_target_disable_clear_request(rb->render_target);
  2020. glActiveTexture(GL_TEXTURE0);
  2021. }
  2022. template <PassMode p_pass_mode>
  2023. 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) {
  2024. GLES3::MeshStorage *mesh_storage = GLES3::MeshStorage::get_singleton();
  2025. GLES3::ParticlesStorage *particles_storage = GLES3::ParticlesStorage::get_singleton();
  2026. GLES3::MaterialStorage *material_storage = GLES3::MaterialStorage::get_singleton();
  2027. GLuint prev_vertex_array_gl = 0;
  2028. GLuint prev_index_array_gl = 0;
  2029. GLES3::SceneMaterialData *prev_material_data = nullptr;
  2030. GLES3::SceneShaderData *prev_shader = nullptr;
  2031. GeometryInstanceGLES3 *prev_inst = nullptr;
  2032. SceneShaderGLES3::ShaderVariant prev_variant = SceneShaderGLES3::ShaderVariant::MODE_COLOR;
  2033. SceneShaderGLES3::ShaderVariant shader_variant = SceneShaderGLES3::MODE_COLOR; // Assigned to silence wrong -Wmaybe-initialized
  2034. uint64_t prev_spec_constants = 0;
  2035. // Specializations constants used by all instances in the scene.
  2036. uint64_t base_spec_constants = p_params->spec_constant_base_flags;
  2037. if constexpr (p_pass_mode == PASS_MODE_COLOR || p_pass_mode == PASS_MODE_COLOR_TRANSPARENT) {
  2038. GLES3::TextureStorage *texture_storage = GLES3::TextureStorage::get_singleton();
  2039. GLES3::Config *config = GLES3::Config::get_singleton();
  2040. glActiveTexture(GL_TEXTURE0 + config->max_texture_image_units - 2);
  2041. GLuint texture_to_bind = texture_storage->get_texture(texture_storage->texture_gl_get_default(GLES3::DEFAULT_GL_TEXTURE_CUBEMAP_BLACK))->tex_id;
  2042. if (p_render_data->environment.is_valid()) {
  2043. Sky *sky = sky_owner.get_or_null(environment_get_sky(p_render_data->environment));
  2044. if (sky && sky->radiance != 0) {
  2045. texture_to_bind = sky->radiance;
  2046. base_spec_constants |= SceneShaderGLES3::USE_RADIANCE_MAP;
  2047. }
  2048. glBindTexture(GL_TEXTURE_CUBE_MAP, texture_to_bind);
  2049. }
  2050. } else if constexpr (p_pass_mode == PASS_MODE_DEPTH || p_pass_mode == PASS_MODE_SHADOW) {
  2051. shader_variant = SceneShaderGLES3::MODE_DEPTH;
  2052. }
  2053. if (p_render_data->view_count > 1) {
  2054. base_spec_constants |= SceneShaderGLES3::USE_MULTIVIEW;
  2055. }
  2056. bool should_request_redraw = false;
  2057. if constexpr (p_pass_mode != PASS_MODE_DEPTH) {
  2058. // Don't count elements during depth pre-pass to match the RD renderers.
  2059. if (p_render_data->render_info) {
  2060. 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;
  2061. }
  2062. }
  2063. for (uint32_t i = p_from_element; i < p_to_element; i++) {
  2064. GeometryInstanceSurface *surf = p_params->elements[i];
  2065. GeometryInstanceGLES3 *inst = surf->owner;
  2066. if (p_pass_mode == PASS_MODE_COLOR && !(surf->flags & GeometryInstanceSurface::FLAG_PASS_OPAQUE)) {
  2067. continue; // Objects with "Depth-prepass" transparency are included in both render lists, but should only be rendered in the transparent pass
  2068. }
  2069. if (inst->instance_count == 0) {
  2070. continue;
  2071. }
  2072. GLES3::SceneShaderData *shader;
  2073. GLES3::SceneMaterialData *material_data;
  2074. void *mesh_surface;
  2075. if constexpr (p_pass_mode == PASS_MODE_SHADOW) {
  2076. shader = surf->shader_shadow;
  2077. material_data = surf->material_shadow;
  2078. mesh_surface = surf->surface_shadow;
  2079. } else {
  2080. if (unlikely(get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_OVERDRAW)) {
  2081. material_data = overdraw_material_data_ptr;
  2082. shader = material_data->shader_data;
  2083. } else if (unlikely(get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_LIGHTING)) {
  2084. material_data = default_material_data_ptr;
  2085. shader = material_data->shader_data;
  2086. } else {
  2087. shader = surf->shader;
  2088. material_data = surf->material;
  2089. }
  2090. mesh_surface = surf->surface;
  2091. }
  2092. if (!mesh_surface) {
  2093. continue;
  2094. }
  2095. //request a redraw if one of the shaders uses TIME
  2096. if (shader->uses_time) {
  2097. should_request_redraw = true;
  2098. }
  2099. if constexpr (p_pass_mode == PASS_MODE_COLOR_TRANSPARENT) {
  2100. if (scene_state.current_depth_test != shader->depth_test) {
  2101. if (shader->depth_test == GLES3::SceneShaderData::DEPTH_TEST_DISABLED) {
  2102. glDisable(GL_DEPTH_TEST);
  2103. } else {
  2104. glEnable(GL_DEPTH_TEST);
  2105. }
  2106. scene_state.current_depth_test = shader->depth_test;
  2107. }
  2108. }
  2109. if constexpr (p_pass_mode != PASS_MODE_SHADOW) {
  2110. if (scene_state.current_depth_draw != shader->depth_draw) {
  2111. switch (shader->depth_draw) {
  2112. case GLES3::SceneShaderData::DEPTH_DRAW_OPAQUE: {
  2113. glDepthMask((p_pass_mode == PASS_MODE_COLOR && !GLES3::Config::get_singleton()->use_depth_prepass) ||
  2114. p_pass_mode == PASS_MODE_DEPTH);
  2115. } break;
  2116. case GLES3::SceneShaderData::DEPTH_DRAW_ALWAYS: {
  2117. glDepthMask(GL_TRUE);
  2118. } break;
  2119. case GLES3::SceneShaderData::DEPTH_DRAW_DISABLED: {
  2120. glDepthMask(GL_FALSE);
  2121. } break;
  2122. }
  2123. }
  2124. scene_state.current_depth_draw = shader->depth_draw;
  2125. }
  2126. bool uses_additive_lighting = (inst->light_passes.size() + p_render_data->directional_shadow_count) > 0;
  2127. uses_additive_lighting = uses_additive_lighting && !shader->unshaded;
  2128. // TODOS
  2129. /*
  2130. * 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
  2131. * Disable depth draw
  2132. */
  2133. for (int32_t pass = 0; pass < MAX(1, int32_t(inst->light_passes.size() + p_render_data->directional_shadow_count)); pass++) {
  2134. if constexpr (p_pass_mode == PASS_MODE_DEPTH || p_pass_mode == PASS_MODE_SHADOW) {
  2135. if (pass > 0) {
  2136. // Don't render shadow passes when doing depth or shadow pass.
  2137. break;
  2138. }
  2139. }
  2140. if constexpr (p_pass_mode == PASS_MODE_COLOR || p_pass_mode == PASS_MODE_COLOR_TRANSPARENT) {
  2141. if (!uses_additive_lighting && pass == 1) {
  2142. // Don't render additive passes if not using additive lighting.
  2143. break;
  2144. }
  2145. if (uses_additive_lighting && pass == 1 && !p_render_data->transparent_bg) {
  2146. // Enable blending if in opaque pass and not already enabled.
  2147. glEnable(GL_BLEND);
  2148. }
  2149. if (pass < int32_t(inst->light_passes.size())) {
  2150. RID light_instance_rid = inst->light_passes[pass].light_instance_rid;
  2151. if (!GLES3::LightStorage::get_singleton()->light_instance_has_shadow_atlas(light_instance_rid, p_render_data->shadow_atlas)) {
  2152. // Shadow wasn't able to get a spot on the atlas. So skip it.
  2153. continue;
  2154. }
  2155. }
  2156. }
  2157. if constexpr (p_pass_mode == PASS_MODE_COLOR || p_pass_mode == PASS_MODE_COLOR_TRANSPARENT) {
  2158. GLES3::SceneShaderData::BlendMode desired_blend_mode;
  2159. if (pass > 0) {
  2160. desired_blend_mode = GLES3::SceneShaderData::BLEND_MODE_ADD;
  2161. } else {
  2162. desired_blend_mode = shader->blend_mode;
  2163. }
  2164. if (desired_blend_mode != scene_state.current_blend_mode) {
  2165. switch (desired_blend_mode) {
  2166. case GLES3::SceneShaderData::BLEND_MODE_MIX: {
  2167. glBlendEquation(GL_FUNC_ADD);
  2168. if (p_render_data->transparent_bg) {
  2169. glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
  2170. } else {
  2171. glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ZERO, GL_ONE);
  2172. }
  2173. } break;
  2174. case GLES3::SceneShaderData::BLEND_MODE_ADD: {
  2175. glBlendEquation(GL_FUNC_ADD);
  2176. glBlendFunc(p_pass_mode == PASS_MODE_COLOR_TRANSPARENT ? GL_SRC_ALPHA : GL_ONE, GL_ONE);
  2177. } break;
  2178. case GLES3::SceneShaderData::BLEND_MODE_SUB: {
  2179. glBlendEquation(GL_FUNC_REVERSE_SUBTRACT);
  2180. glBlendFunc(GL_SRC_ALPHA, GL_ONE);
  2181. } break;
  2182. case GLES3::SceneShaderData::BLEND_MODE_MUL: {
  2183. glBlendEquation(GL_FUNC_ADD);
  2184. if (p_render_data->transparent_bg) {
  2185. glBlendFuncSeparate(GL_DST_COLOR, GL_ZERO, GL_DST_ALPHA, GL_ZERO);
  2186. } else {
  2187. glBlendFuncSeparate(GL_DST_COLOR, GL_ZERO, GL_ZERO, GL_ONE);
  2188. }
  2189. } break;
  2190. case GLES3::SceneShaderData::BLEND_MODE_ALPHA_TO_COVERAGE: {
  2191. // Do nothing for now.
  2192. } break;
  2193. }
  2194. scene_state.current_blend_mode = desired_blend_mode;
  2195. }
  2196. }
  2197. // Find cull variant.
  2198. GLES3::SceneShaderData::Cull cull_mode = shader->cull_mode;
  2199. if ((surf->flags & GeometryInstanceSurface::FLAG_USES_DOUBLE_SIDED_SHADOWS)) {
  2200. cull_mode = GLES3::SceneShaderData::CULL_DISABLED;
  2201. } else {
  2202. bool mirror = inst->mirror;
  2203. if (p_params->reverse_cull) {
  2204. mirror = !mirror;
  2205. }
  2206. if (cull_mode == GLES3::SceneShaderData::CULL_FRONT && mirror) {
  2207. cull_mode = GLES3::SceneShaderData::CULL_BACK;
  2208. } else if (cull_mode == GLES3::SceneShaderData::CULL_BACK && mirror) {
  2209. cull_mode = GLES3::SceneShaderData::CULL_FRONT;
  2210. }
  2211. }
  2212. if (scene_state.cull_mode != cull_mode) {
  2213. if (cull_mode == GLES3::SceneShaderData::CULL_DISABLED) {
  2214. glDisable(GL_CULL_FACE);
  2215. } else {
  2216. if (scene_state.cull_mode == GLES3::SceneShaderData::CULL_DISABLED) {
  2217. // Last time was disabled, so enable and set proper face.
  2218. glEnable(GL_CULL_FACE);
  2219. }
  2220. glCullFace(cull_mode == GLES3::SceneShaderData::CULL_FRONT ? GL_FRONT : GL_BACK);
  2221. }
  2222. scene_state.cull_mode = cull_mode;
  2223. }
  2224. RS::PrimitiveType primitive = surf->primitive;
  2225. if (shader->uses_point_size) {
  2226. primitive = RS::PRIMITIVE_POINTS;
  2227. }
  2228. static const GLenum prim[5] = { GL_POINTS, GL_LINES, GL_LINE_STRIP, GL_TRIANGLES, GL_TRIANGLE_STRIP };
  2229. GLenum primitive_gl = prim[int(primitive)];
  2230. GLuint vertex_array_gl = 0;
  2231. GLuint index_array_gl = 0;
  2232. //skeleton and blend shape
  2233. if (surf->owner->mesh_instance.is_valid()) {
  2234. mesh_storage->mesh_instance_surface_get_vertex_arrays_and_format(surf->owner->mesh_instance, surf->surface_index, shader->vertex_input_mask, vertex_array_gl);
  2235. } else {
  2236. mesh_storage->mesh_surface_get_vertex_arrays_and_format(mesh_surface, shader->vertex_input_mask, vertex_array_gl);
  2237. }
  2238. index_array_gl = mesh_storage->mesh_surface_get_index_buffer(mesh_surface, surf->lod_index);
  2239. if (prev_vertex_array_gl != vertex_array_gl) {
  2240. if (vertex_array_gl != 0) {
  2241. glBindVertexArray(vertex_array_gl);
  2242. }
  2243. prev_vertex_array_gl = vertex_array_gl;
  2244. // Invalidate the previous index array
  2245. prev_index_array_gl = 0;
  2246. }
  2247. bool use_wireframe = false;
  2248. if (p_params->force_wireframe) {
  2249. GLuint wireframe_index_array_gl = mesh_storage->mesh_surface_get_index_buffer_wireframe(mesh_surface);
  2250. if (wireframe_index_array_gl) {
  2251. index_array_gl = wireframe_index_array_gl;
  2252. use_wireframe = true;
  2253. }
  2254. }
  2255. bool use_index_buffer = index_array_gl != 0;
  2256. if (prev_index_array_gl != index_array_gl) {
  2257. if (index_array_gl != 0) {
  2258. // Bind index each time so we can use LODs
  2259. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, index_array_gl);
  2260. }
  2261. prev_index_array_gl = index_array_gl;
  2262. }
  2263. Transform3D world_transform;
  2264. if (inst->store_transform_cache) {
  2265. world_transform = inst->transform;
  2266. }
  2267. if (prev_material_data != material_data) {
  2268. material_data->bind_uniforms();
  2269. prev_material_data = material_data;
  2270. }
  2271. SceneShaderGLES3::ShaderVariant instance_variant = shader_variant;
  2272. if (inst->instance_count > 0) {
  2273. // Will need to use instancing to draw (either MultiMesh or Particles).
  2274. instance_variant = SceneShaderGLES3::ShaderVariant(1 + int(instance_variant));
  2275. }
  2276. uint64_t spec_constants = base_spec_constants;
  2277. // Set up spec constants for lighting.
  2278. if constexpr (p_pass_mode == PASS_MODE_COLOR || p_pass_mode == PASS_MODE_COLOR_TRANSPARENT) {
  2279. // Only check during color passes as light shader code is compiled out during depth-only pass anyway.
  2280. if (pass == 0) {
  2281. spec_constants |= SceneShaderGLES3::BASE_PASS;
  2282. if (inst->omni_light_gl_cache.size() == 0) {
  2283. spec_constants |= SceneShaderGLES3::DISABLE_LIGHT_OMNI;
  2284. }
  2285. if (inst->spot_light_gl_cache.size() == 0) {
  2286. spec_constants |= SceneShaderGLES3::DISABLE_LIGHT_SPOT;
  2287. }
  2288. if (p_render_data->directional_light_count == p_render_data->directional_shadow_count) {
  2289. spec_constants |= SceneShaderGLES3::DISABLE_LIGHT_DIRECTIONAL;
  2290. }
  2291. } else {
  2292. // Only base pass uses the radiance map.
  2293. spec_constants &= ~SceneShaderGLES3::USE_RADIANCE_MAP;
  2294. spec_constants |= SceneShaderGLES3::DISABLE_LIGHT_OMNI;
  2295. spec_constants |= SceneShaderGLES3::DISABLE_LIGHT_SPOT;
  2296. spec_constants |= SceneShaderGLES3::DISABLE_LIGHT_DIRECTIONAL;
  2297. }
  2298. if (uses_additive_lighting) {
  2299. spec_constants |= SceneShaderGLES3::USE_ADDITIVE_LIGHTING;
  2300. if (pass < int32_t(inst->light_passes.size())) {
  2301. // Rendering positional lights.
  2302. if (inst->light_passes[pass].is_omni) {
  2303. spec_constants |= SceneShaderGLES3::ADDITIVE_OMNI;
  2304. } else {
  2305. spec_constants |= SceneShaderGLES3::ADDITIVE_SPOT;
  2306. }
  2307. if (scene_state.positional_shadow_quality >= RS::SHADOW_QUALITY_SOFT_HIGH) {
  2308. spec_constants |= SceneShaderGLES3::SHADOW_MODE_PCF_13;
  2309. } else if (scene_state.positional_shadow_quality >= RS::SHADOW_QUALITY_SOFT_LOW) {
  2310. spec_constants |= SceneShaderGLES3::SHADOW_MODE_PCF_5;
  2311. }
  2312. } else {
  2313. // Render directional lights.
  2314. uint32_t shadow_id = MAX_DIRECTIONAL_LIGHTS - 1 - (pass - int32_t(inst->light_passes.size()));
  2315. if (scene_state.directional_shadows[shadow_id].shadow_split_offsets[0] == scene_state.directional_shadows[shadow_id].shadow_split_offsets[1]) {
  2316. // Orthogonal, do nothing.
  2317. } else if (scene_state.directional_shadows[shadow_id].shadow_split_offsets[1] == scene_state.directional_shadows[shadow_id].shadow_split_offsets[2]) {
  2318. spec_constants |= SceneShaderGLES3::LIGHT_USE_PSSM2;
  2319. } else {
  2320. spec_constants |= SceneShaderGLES3::LIGHT_USE_PSSM4;
  2321. }
  2322. if (scene_state.directional_shadows[shadow_id].blend_splits) {
  2323. spec_constants |= SceneShaderGLES3::LIGHT_USE_PSSM_BLEND;
  2324. }
  2325. if (scene_state.directional_shadow_quality >= RS::SHADOW_QUALITY_SOFT_HIGH) {
  2326. spec_constants |= SceneShaderGLES3::SHADOW_MODE_PCF_13;
  2327. } else if (scene_state.directional_shadow_quality >= RS::SHADOW_QUALITY_SOFT_LOW) {
  2328. spec_constants |= SceneShaderGLES3::SHADOW_MODE_PCF_5;
  2329. }
  2330. }
  2331. }
  2332. }
  2333. if (prev_shader != shader || prev_variant != instance_variant || spec_constants != prev_spec_constants) {
  2334. bool success = material_storage->shaders.scene_shader.version_bind_shader(shader->version, instance_variant, spec_constants);
  2335. if (!success) {
  2336. break;
  2337. }
  2338. float opaque_prepass_threshold = 0.0;
  2339. if constexpr (p_pass_mode == PASS_MODE_DEPTH) {
  2340. opaque_prepass_threshold = 0.99;
  2341. } else if constexpr (p_pass_mode == PASS_MODE_SHADOW) {
  2342. opaque_prepass_threshold = 0.1;
  2343. }
  2344. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::OPAQUE_PREPASS_THRESHOLD, opaque_prepass_threshold, shader->version, instance_variant, spec_constants);
  2345. prev_shader = shader;
  2346. prev_variant = instance_variant;
  2347. prev_spec_constants = spec_constants;
  2348. }
  2349. // Pass in lighting uniforms.
  2350. if constexpr (p_pass_mode == PASS_MODE_COLOR || p_pass_mode == PASS_MODE_COLOR_TRANSPARENT) {
  2351. GLES3::Config *config = GLES3::Config::get_singleton();
  2352. // Pass light and shadow index and bind shadow texture.
  2353. if (uses_additive_lighting) {
  2354. if (pass < int32_t(inst->light_passes.size())) {
  2355. int32_t shadow_id = inst->light_passes[pass].shadow_id;
  2356. if (shadow_id >= 0) {
  2357. uint32_t light_id = inst->light_passes[pass].light_id;
  2358. bool is_omni = inst->light_passes[pass].is_omni;
  2359. SceneShaderGLES3::Uniforms uniform_name = is_omni ? SceneShaderGLES3::OMNI_LIGHT_INDEX : SceneShaderGLES3::SPOT_LIGHT_INDEX;
  2360. material_storage->shaders.scene_shader.version_set_uniform(uniform_name, uint32_t(light_id), shader->version, instance_variant, spec_constants);
  2361. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::POSITIONAL_SHADOW_INDEX, uint32_t(shadow_id), shader->version, instance_variant, spec_constants);
  2362. glActiveTexture(GL_TEXTURE0 + config->max_texture_image_units - 3);
  2363. RID light_instance_rid = inst->light_passes[pass].light_instance_rid;
  2364. GLuint tex = GLES3::LightStorage::get_singleton()->light_instance_get_shadow_texture(light_instance_rid, p_render_data->shadow_atlas);
  2365. if (is_omni) {
  2366. glBindTexture(GL_TEXTURE_CUBE_MAP, tex);
  2367. } else {
  2368. glBindTexture(GL_TEXTURE_2D, tex);
  2369. }
  2370. }
  2371. } else {
  2372. uint32_t shadow_id = MAX_DIRECTIONAL_LIGHTS - 1 - (pass - int32_t(inst->light_passes.size()));
  2373. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::DIRECTIONAL_SHADOW_INDEX, shadow_id, shader->version, instance_variant, spec_constants);
  2374. GLuint tex = GLES3::LightStorage::get_singleton()->directional_shadow_get_texture();
  2375. glActiveTexture(GL_TEXTURE0 + config->max_texture_image_units - 3);
  2376. glBindTexture(GL_TEXTURE_2D, tex);
  2377. }
  2378. }
  2379. // Pass light count and array of light indices for base pass.
  2380. if ((prev_inst != inst || prev_shader != shader || prev_variant != instance_variant) && pass == 0) {
  2381. // Rebind the light indices.
  2382. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::OMNI_LIGHT_COUNT, inst->omni_light_gl_cache.size(), shader->version, instance_variant, spec_constants);
  2383. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::SPOT_LIGHT_COUNT, inst->spot_light_gl_cache.size(), shader->version, instance_variant, spec_constants);
  2384. if (inst->omni_light_gl_cache.size()) {
  2385. 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());
  2386. }
  2387. if (inst->spot_light_gl_cache.size()) {
  2388. 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());
  2389. }
  2390. prev_inst = inst;
  2391. }
  2392. }
  2393. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::WORLD_TRANSFORM, world_transform, shader->version, instance_variant, spec_constants);
  2394. {
  2395. GLES3::Mesh::Surface *s = reinterpret_cast<GLES3::Mesh::Surface *>(surf->surface);
  2396. if (s->format & RS::ARRAY_FLAG_COMPRESS_ATTRIBUTES) {
  2397. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::COMPRESSED_AABB_POSITION, s->aabb.position, shader->version, instance_variant, spec_constants);
  2398. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::COMPRESSED_AABB_SIZE, s->aabb.size, shader->version, instance_variant, spec_constants);
  2399. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::UV_SCALE, s->uv_scale, shader->version, instance_variant, spec_constants);
  2400. } else {
  2401. 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);
  2402. 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);
  2403. 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);
  2404. }
  2405. }
  2406. material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::MODEL_FLAGS, inst->flags_cache, shader->version, instance_variant, spec_constants);
  2407. // Can be index count or vertex count
  2408. uint32_t count = 0;
  2409. if (surf->lod_index > 0) {
  2410. count = surf->index_count;
  2411. } else {
  2412. count = mesh_storage->mesh_surface_get_vertices_drawn_count(mesh_surface);
  2413. }
  2414. if (use_wireframe) {
  2415. // In this case we are using index count, and we need double the indices for the wireframe mesh.
  2416. count = count * 2;
  2417. }
  2418. if constexpr (p_pass_mode != PASS_MODE_DEPTH) {
  2419. // Don't count draw calls during depth pre-pass to match the RD renderers.
  2420. if (p_render_data->render_info) {
  2421. p_render_data->render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_VISIBLE][RS::VIEWPORT_RENDER_INFO_DRAW_CALLS_IN_FRAME]++;
  2422. }
  2423. }
  2424. if (inst->instance_count > 0) {
  2425. // Using MultiMesh or Particles.
  2426. // Bind instance buffers.
  2427. GLuint instance_buffer = 0;
  2428. uint32_t stride = 0;
  2429. if (inst->flags_cache & INSTANCE_DATA_FLAG_PARTICLES) {
  2430. instance_buffer = particles_storage->particles_get_gl_buffer(inst->data->base);
  2431. stride = 16; // 12 bytes for instance transform and 4 bytes for packed color and custom.
  2432. } else {
  2433. instance_buffer = mesh_storage->multimesh_get_gl_buffer(inst->data->base);
  2434. stride = mesh_storage->multimesh_get_stride(inst->data->base);
  2435. }
  2436. if (instance_buffer == 0) {
  2437. // Instance buffer not initialized yet. Skip rendering for now.
  2438. break;
  2439. }
  2440. glBindBuffer(GL_ARRAY_BUFFER, instance_buffer);
  2441. glEnableVertexAttribArray(12);
  2442. glVertexAttribPointer(12, 4, GL_FLOAT, GL_FALSE, stride * sizeof(float), CAST_INT_TO_UCHAR_PTR(0));
  2443. glVertexAttribDivisor(12, 1);
  2444. glEnableVertexAttribArray(13);
  2445. glVertexAttribPointer(13, 4, GL_FLOAT, GL_FALSE, stride * sizeof(float), CAST_INT_TO_UCHAR_PTR(sizeof(float) * 4));
  2446. glVertexAttribDivisor(13, 1);
  2447. if (!(inst->flags_cache & INSTANCE_DATA_FLAG_MULTIMESH_FORMAT_2D)) {
  2448. glEnableVertexAttribArray(14);
  2449. glVertexAttribPointer(14, 4, GL_FLOAT, GL_FALSE, stride * sizeof(float), CAST_INT_TO_UCHAR_PTR(sizeof(float) * 8));
  2450. glVertexAttribDivisor(14, 1);
  2451. }
  2452. if ((inst->flags_cache & INSTANCE_DATA_FLAG_MULTIMESH_HAS_COLOR) || (inst->flags_cache & INSTANCE_DATA_FLAG_MULTIMESH_HAS_CUSTOM_DATA)) {
  2453. uint32_t color_custom_offset = inst->flags_cache & INSTANCE_DATA_FLAG_MULTIMESH_FORMAT_2D ? 8 : 12;
  2454. glEnableVertexAttribArray(15);
  2455. glVertexAttribIPointer(15, 4, GL_UNSIGNED_INT, stride * sizeof(float), CAST_INT_TO_UCHAR_PTR(color_custom_offset * sizeof(float)));
  2456. glVertexAttribDivisor(15, 1);
  2457. } else {
  2458. // Set all default instance color and custom data values to 1.0 or 0.0 using a compressed format.
  2459. uint16_t zero = Math::make_half_float(0.0f);
  2460. uint16_t one = Math::make_half_float(1.0f);
  2461. GLuint default_color = (uint32_t(one) << 16) | one;
  2462. GLuint default_custom = (uint32_t(zero) << 16) | zero;
  2463. glVertexAttribI4ui(15, default_color, default_color, default_custom, default_custom);
  2464. }
  2465. if (use_wireframe) {
  2466. glDrawElementsInstanced(GL_LINES, count, GL_UNSIGNED_INT, 0, inst->instance_count);
  2467. } else {
  2468. if (use_index_buffer) {
  2469. glDrawElementsInstanced(primitive_gl, count, mesh_storage->mesh_surface_get_index_type(mesh_surface), 0, inst->instance_count);
  2470. } else {
  2471. glDrawArraysInstanced(primitive_gl, 0, count, inst->instance_count);
  2472. }
  2473. }
  2474. } else {
  2475. // Using regular Mesh.
  2476. if (use_wireframe) {
  2477. glDrawElements(GL_LINES, count, GL_UNSIGNED_INT, 0);
  2478. } else {
  2479. if (use_index_buffer) {
  2480. glDrawElements(primitive_gl, count, mesh_storage->mesh_surface_get_index_type(mesh_surface), 0);
  2481. } else {
  2482. glDrawArrays(primitive_gl, 0, count);
  2483. }
  2484. }
  2485. }
  2486. if (inst->instance_count > 0) {
  2487. glDisableVertexAttribArray(12);
  2488. glDisableVertexAttribArray(13);
  2489. glDisableVertexAttribArray(14);
  2490. glDisableVertexAttribArray(15);
  2491. }
  2492. }
  2493. if constexpr (p_pass_mode == PASS_MODE_COLOR) {
  2494. if (uses_additive_lighting && !p_render_data->transparent_bg) {
  2495. // Disable additive blending if enabled for additive lights.
  2496. glDisable(GL_BLEND);
  2497. }
  2498. }
  2499. }
  2500. // Make the actual redraw request
  2501. if (should_request_redraw) {
  2502. RenderingServerDefault::redraw_request();
  2503. }
  2504. }
  2505. 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) {
  2506. }
  2507. void RasterizerSceneGLES3::render_particle_collider_heightfield(RID p_collider, const Transform3D &p_transform, const PagedArray<RenderGeometryInstance *> &p_instances) {
  2508. GLES3::ParticlesStorage *particles_storage = GLES3::ParticlesStorage::get_singleton();
  2509. ERR_FAIL_COND(!particles_storage->particles_collision_is_heightfield(p_collider));
  2510. Vector3 extents = particles_storage->particles_collision_get_extents(p_collider) * p_transform.basis.get_scale();
  2511. Projection cm;
  2512. cm.set_orthogonal(-extents.x, extents.x, -extents.z, extents.z, 0, extents.y * 2.0);
  2513. Vector3 cam_pos = p_transform.origin;
  2514. cam_pos.y += extents.y;
  2515. Transform3D cam_xform;
  2516. 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());
  2517. GLuint fb = particles_storage->particles_collision_get_heightfield_framebuffer(p_collider);
  2518. Size2i fb_size = particles_storage->particles_collision_get_heightfield_size(p_collider);
  2519. RENDER_TIMESTAMP("Setup GPUParticlesCollisionHeightField3D");
  2520. RenderDataGLES3 render_data;
  2521. render_data.cam_projection = cm;
  2522. render_data.cam_transform = cam_xform;
  2523. render_data.view_projection[0] = cm;
  2524. render_data.inv_cam_transform = render_data.cam_transform.affine_inverse();
  2525. render_data.cam_orthogonal = true;
  2526. render_data.z_near = 0.0;
  2527. render_data.z_far = cm.get_z_far();
  2528. render_data.instances = &p_instances;
  2529. _setup_environment(&render_data, true, Vector2(fb_size), true, Color(), false);
  2530. PassMode pass_mode = PASS_MODE_SHADOW;
  2531. _fill_render_list(RENDER_LIST_SECONDARY, &render_data, pass_mode);
  2532. render_list[RENDER_LIST_SECONDARY].sort_by_key();
  2533. RENDER_TIMESTAMP("Render Collider Heightfield");
  2534. glBindFramebuffer(GL_FRAMEBUFFER, fb);
  2535. glViewport(0, 0, fb_size.width, fb_size.height);
  2536. GLuint global_buffer = GLES3::MaterialStorage::get_singleton()->global_shader_parameters_get_uniform_buffer();
  2537. glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_GLOBALS_UNIFORM_LOCATION, global_buffer);
  2538. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  2539. glDisable(GL_BLEND);
  2540. glDepthMask(GL_TRUE);
  2541. glEnable(GL_DEPTH_TEST);
  2542. glDepthFunc(GL_LESS);
  2543. glDisable(GL_SCISSOR_TEST);
  2544. glCullFace(GL_BACK);
  2545. glEnable(GL_CULL_FACE);
  2546. scene_state.cull_mode = GLES3::SceneShaderData::CULL_BACK;
  2547. glColorMask(0, 0, 0, 0);
  2548. RasterizerGLES3::clear_depth(1.0);
  2549. glClear(GL_DEPTH_BUFFER_BIT);
  2550. RenderListParameters render_list_params(render_list[RENDER_LIST_SECONDARY].elements.ptr(), render_list[RENDER_LIST_SECONDARY].elements.size(), false, 31, false);
  2551. _render_list_template<PASS_MODE_SHADOW>(&render_list_params, &render_data, 0, render_list[RENDER_LIST_SECONDARY].elements.size());
  2552. glColorMask(1, 1, 1, 1);
  2553. glBindFramebuffer(GL_FRAMEBUFFER, 0);
  2554. }
  2555. void RasterizerSceneGLES3::set_time(double p_time, double p_step) {
  2556. time = p_time;
  2557. time_step = p_step;
  2558. }
  2559. void RasterizerSceneGLES3::set_debug_draw_mode(RS::ViewportDebugDraw p_debug_draw) {
  2560. debug_draw = p_debug_draw;
  2561. }
  2562. Ref<RenderSceneBuffers> RasterizerSceneGLES3::render_buffers_create() {
  2563. Ref<RenderSceneBuffersGLES3> rb;
  2564. rb.instantiate();
  2565. return rb;
  2566. }
  2567. void RasterizerSceneGLES3::_render_buffers_debug_draw(Ref<RenderSceneBuffersGLES3> p_render_buffers, RID p_shadow_atlas) {
  2568. GLES3::TextureStorage *texture_storage = GLES3::TextureStorage::get_singleton();
  2569. GLES3::LightStorage *light_storage = GLES3::LightStorage::get_singleton();
  2570. GLES3::CopyEffects *copy_effects = GLES3::CopyEffects::get_singleton();
  2571. ERR_FAIL_COND(p_render_buffers.is_null());
  2572. RID render_target = p_render_buffers->render_target;
  2573. GLES3::RenderTarget *rt = texture_storage->get_render_target(render_target);
  2574. ERR_FAIL_NULL(rt);
  2575. if (debug_draw == RS::VIEWPORT_DEBUG_DRAW_SHADOW_ATLAS) {
  2576. if (p_shadow_atlas.is_valid()) {
  2577. // Get or create debug textures to display shadow maps as an atlas.
  2578. GLuint shadow_atlas_texture = light_storage->shadow_atlas_get_debug_texture(p_shadow_atlas);
  2579. GLuint shadow_atlas_fb = light_storage->shadow_atlas_get_debug_fb(p_shadow_atlas);
  2580. uint32_t shadow_atlas_size = light_storage->shadow_atlas_get_size(p_shadow_atlas);
  2581. uint32_t quadrant_size = shadow_atlas_size >> 1;
  2582. glBindFramebuffer(GL_FRAMEBUFFER, shadow_atlas_fb);
  2583. glViewport(0, 0, shadow_atlas_size, shadow_atlas_size);
  2584. glActiveTexture(GL_TEXTURE0);
  2585. glDepthMask(GL_TRUE);
  2586. glDepthFunc(GL_ALWAYS);
  2587. glDisable(GL_CULL_FACE);
  2588. scene_state.cull_mode = GLES3::SceneShaderData::CULL_DISABLED;
  2589. // Loop through quadrants and copy shadows over.
  2590. for (int quadrant = 0; quadrant < 4; quadrant++) {
  2591. uint32_t subdivision = light_storage->shadow_atlas_get_quadrant_subdivision(p_shadow_atlas, quadrant);
  2592. if (subdivision == 0) {
  2593. continue;
  2594. }
  2595. Rect2i atlas_rect;
  2596. Rect2 atlas_uv_rect;
  2597. uint32_t shadow_size = (quadrant_size / subdivision);
  2598. float size = float(shadow_size) / float(shadow_atlas_size);
  2599. uint32_t length = light_storage->shadow_atlas_get_quadrant_shadows_allocated(p_shadow_atlas, quadrant);
  2600. for (uint32_t shadow_idx = 0; shadow_idx < length; shadow_idx++) {
  2601. bool is_omni = light_storage->shadow_atlas_get_quadrant_shadow_is_omni(p_shadow_atlas, quadrant, shadow_idx);
  2602. // Calculate shadow's position in the debug atlas.
  2603. atlas_rect.position.x = (quadrant & 1) * quadrant_size;
  2604. atlas_rect.position.y = (quadrant >> 1) * quadrant_size;
  2605. atlas_rect.position.x += (shadow_idx % subdivision) * shadow_size;
  2606. atlas_rect.position.y += (shadow_idx / subdivision) * shadow_size;
  2607. atlas_uv_rect.position = Vector2(atlas_rect.position) / float(shadow_atlas_size);
  2608. atlas_uv_rect.size = Vector2(size, size);
  2609. GLuint shadow_tex = light_storage->shadow_atlas_get_quadrant_shadow_texture(p_shadow_atlas, quadrant, shadow_idx);
  2610. // Copy from shadowmap to debug atlas.
  2611. if (is_omni) {
  2612. glBindTexture(GL_TEXTURE_CUBE_MAP, shadow_tex);
  2613. glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_COMPARE_MODE, GL_NONE);
  2614. copy_effects->copy_cube_to_rect(atlas_uv_rect);
  2615. glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
  2616. glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_COMPARE_FUNC, GL_LESS);
  2617. } else {
  2618. glBindTexture(GL_TEXTURE_2D, shadow_tex);
  2619. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE);
  2620. copy_effects->copy_to_rect(atlas_uv_rect);
  2621. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
  2622. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LESS);
  2623. }
  2624. }
  2625. }
  2626. glBindFramebuffer(GL_FRAMEBUFFER, rt->fbo);
  2627. glViewport(0, 0, rt->size.width, rt->size.height);
  2628. glBindTexture(GL_TEXTURE_2D, shadow_atlas_texture);
  2629. copy_effects->copy_to_rect(Rect2(Vector2(), Vector2(0.5, 0.5)));
  2630. glBindTexture(GL_TEXTURE_2D, 0);
  2631. glBindFramebuffer(GL_FRAMEBUFFER, 0);
  2632. }
  2633. }
  2634. if (debug_draw == RS::VIEWPORT_DEBUG_DRAW_DIRECTIONAL_SHADOW_ATLAS) {
  2635. if (light_storage->directional_shadow_get_texture() != 0) {
  2636. GLuint shadow_atlas_texture = light_storage->directional_shadow_get_texture();
  2637. glActiveTexture(GL_TEXTURE0);
  2638. glBindTexture(GL_TEXTURE_2D, shadow_atlas_texture);
  2639. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE);
  2640. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_R, GL_RED);
  2641. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_G, GL_RED);
  2642. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, GL_RED);
  2643. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_A, GL_ONE);
  2644. glDisable(GL_DEPTH_TEST);
  2645. glDepthMask(GL_FALSE);
  2646. copy_effects->copy_to_rect(Rect2(Vector2(), Vector2(0.5, 0.5)));
  2647. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_R, GL_RED);
  2648. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_G, GL_GREEN);
  2649. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, GL_BLUE);
  2650. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_A, GL_ALPHA);
  2651. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
  2652. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LESS);
  2653. glBindTexture(GL_TEXTURE_2D, 0);
  2654. }
  2655. }
  2656. }
  2657. void RasterizerSceneGLES3::gi_set_use_half_resolution(bool p_enable) {
  2658. }
  2659. void RasterizerSceneGLES3::screen_space_roughness_limiter_set_active(bool p_enable, float p_amount, float p_curve) {
  2660. }
  2661. bool RasterizerSceneGLES3::screen_space_roughness_limiter_is_active() const {
  2662. return false;
  2663. }
  2664. void RasterizerSceneGLES3::sub_surface_scattering_set_quality(RS::SubSurfaceScatteringQuality p_quality) {
  2665. }
  2666. void RasterizerSceneGLES3::sub_surface_scattering_set_scale(float p_scale, float p_depth_scale) {
  2667. }
  2668. TypedArray<Image> RasterizerSceneGLES3::bake_render_uv2(RID p_base, const TypedArray<RID> &p_material_overrides, const Size2i &p_image_size) {
  2669. return TypedArray<Image>();
  2670. }
  2671. bool RasterizerSceneGLES3::free(RID p_rid) {
  2672. if (is_environment(p_rid)) {
  2673. environment_free(p_rid);
  2674. } else if (sky_owner.owns(p_rid)) {
  2675. Sky *sky = sky_owner.get_or_null(p_rid);
  2676. ERR_FAIL_NULL_V(sky, false);
  2677. _free_sky_data(sky);
  2678. sky_owner.free(p_rid);
  2679. } else if (GLES3::LightStorage::get_singleton()->owns_light_instance(p_rid)) {
  2680. GLES3::LightStorage::get_singleton()->light_instance_free(p_rid);
  2681. } else if (RSG::camera_attributes->owns_camera_attributes(p_rid)) {
  2682. //not much to delete, just free it
  2683. RSG::camera_attributes->camera_attributes_free(p_rid);
  2684. } else {
  2685. return false;
  2686. }
  2687. return true;
  2688. }
  2689. void RasterizerSceneGLES3::update() {
  2690. _update_dirty_skys();
  2691. }
  2692. void RasterizerSceneGLES3::sdfgi_set_debug_probe_select(const Vector3 &p_position, const Vector3 &p_dir) {
  2693. }
  2694. void RasterizerSceneGLES3::decals_set_filter(RS::DecalFilter p_filter) {
  2695. }
  2696. void RasterizerSceneGLES3::light_projectors_set_filter(RS::LightProjectorFilter p_filter) {
  2697. }
  2698. RasterizerSceneGLES3::RasterizerSceneGLES3() {
  2699. singleton = this;
  2700. GLES3::MaterialStorage *material_storage = GLES3::MaterialStorage::get_singleton();
  2701. GLES3::Config *config = GLES3::Config::get_singleton();
  2702. // Quality settings.
  2703. use_physical_light_units = GLOBAL_GET("rendering/lights_and_shadows/use_physical_light_units");
  2704. positional_soft_shadow_filter_set_quality((RS::ShadowQuality)(int)GLOBAL_GET("rendering/lights_and_shadows/positional_shadow/soft_shadow_filter_quality"));
  2705. directional_soft_shadow_filter_set_quality((RS::ShadowQuality)(int)GLOBAL_GET("rendering/lights_and_shadows/directional_shadow/soft_shadow_filter_quality"));
  2706. {
  2707. // Setup Lights
  2708. config->max_renderable_lights = MIN(config->max_renderable_lights, config->max_uniform_buffer_size / (int)sizeof(RasterizerSceneGLES3::LightData));
  2709. config->max_lights_per_object = MIN(config->max_lights_per_object, config->max_renderable_lights);
  2710. uint32_t light_buffer_size = config->max_renderable_lights * sizeof(LightData);
  2711. scene_state.omni_lights = memnew_arr(LightData, config->max_renderable_lights);
  2712. scene_state.omni_light_sort = memnew_arr(InstanceSort<GLES3::LightInstance>, config->max_renderable_lights);
  2713. glGenBuffers(1, &scene_state.omni_light_buffer);
  2714. glBindBuffer(GL_UNIFORM_BUFFER, scene_state.omni_light_buffer);
  2715. GLES3::Utilities::get_singleton()->buffer_allocate_data(GL_UNIFORM_BUFFER, scene_state.omni_light_buffer, light_buffer_size, nullptr, GL_STREAM_DRAW, "OmniLight UBO");
  2716. scene_state.spot_lights = memnew_arr(LightData, config->max_renderable_lights);
  2717. scene_state.spot_light_sort = memnew_arr(InstanceSort<GLES3::LightInstance>, config->max_renderable_lights);
  2718. glGenBuffers(1, &scene_state.spot_light_buffer);
  2719. glBindBuffer(GL_UNIFORM_BUFFER, scene_state.spot_light_buffer);
  2720. GLES3::Utilities::get_singleton()->buffer_allocate_data(GL_UNIFORM_BUFFER, scene_state.spot_light_buffer, light_buffer_size, nullptr, GL_STREAM_DRAW, "SpotLight UBO");
  2721. uint32_t directional_light_buffer_size = MAX_DIRECTIONAL_LIGHTS * sizeof(DirectionalLightData);
  2722. scene_state.directional_lights = memnew_arr(DirectionalLightData, MAX_DIRECTIONAL_LIGHTS);
  2723. glGenBuffers(1, &scene_state.directional_light_buffer);
  2724. glBindBuffer(GL_UNIFORM_BUFFER, scene_state.directional_light_buffer);
  2725. 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");
  2726. uint32_t shadow_buffer_size = config->max_renderable_lights * sizeof(ShadowData) * 2;
  2727. scene_state.positional_shadows = memnew_arr(ShadowData, config->max_renderable_lights * 2);
  2728. glGenBuffers(1, &scene_state.positional_shadow_buffer);
  2729. glBindBuffer(GL_UNIFORM_BUFFER, scene_state.positional_shadow_buffer);
  2730. 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");
  2731. uint32_t directional_shadow_buffer_size = MAX_DIRECTIONAL_LIGHTS * sizeof(DirectionalShadowData);
  2732. scene_state.directional_shadows = memnew_arr(DirectionalShadowData, MAX_DIRECTIONAL_LIGHTS);
  2733. glGenBuffers(1, &scene_state.directional_shadow_buffer);
  2734. glBindBuffer(GL_UNIFORM_BUFFER, scene_state.directional_shadow_buffer);
  2735. 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");
  2736. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  2737. }
  2738. {
  2739. sky_globals.max_directional_lights = 4;
  2740. uint32_t directional_light_buffer_size = sky_globals.max_directional_lights * sizeof(DirectionalLightData);
  2741. sky_globals.directional_lights = memnew_arr(DirectionalLightData, sky_globals.max_directional_lights);
  2742. sky_globals.last_frame_directional_lights = memnew_arr(DirectionalLightData, sky_globals.max_directional_lights);
  2743. sky_globals.last_frame_directional_light_count = sky_globals.max_directional_lights + 1;
  2744. glGenBuffers(1, &sky_globals.directional_light_buffer);
  2745. glBindBuffer(GL_UNIFORM_BUFFER, sky_globals.directional_light_buffer);
  2746. 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");
  2747. glBindBuffer(GL_UNIFORM_BUFFER, 0);
  2748. }
  2749. {
  2750. String global_defines;
  2751. global_defines += "#define MAX_GLOBAL_SHADER_UNIFORMS 256\n"; // TODO: this is arbitrary for now
  2752. global_defines += "\n#define MAX_LIGHT_DATA_STRUCTS " + itos(config->max_renderable_lights) + "\n";
  2753. global_defines += "\n#define MAX_DIRECTIONAL_LIGHT_DATA_STRUCTS " + itos(MAX_DIRECTIONAL_LIGHTS) + "\n";
  2754. global_defines += "\n#define MAX_FORWARD_LIGHTS " + itos(config->max_lights_per_object) + "u\n";
  2755. material_storage->shaders.scene_shader.initialize(global_defines);
  2756. scene_globals.shader_default_version = material_storage->shaders.scene_shader.version_create();
  2757. material_storage->shaders.scene_shader.version_bind_shader(scene_globals.shader_default_version, SceneShaderGLES3::MODE_COLOR);
  2758. }
  2759. {
  2760. //default material and shader
  2761. scene_globals.default_shader = material_storage->shader_allocate();
  2762. material_storage->shader_initialize(scene_globals.default_shader);
  2763. material_storage->shader_set_code(scene_globals.default_shader, R"(
  2764. // Default 3D material shader (Compatibility).
  2765. shader_type spatial;
  2766. void vertex() {
  2767. ROUGHNESS = 0.8;
  2768. }
  2769. void fragment() {
  2770. ALBEDO = vec3(0.6);
  2771. ROUGHNESS = 0.8;
  2772. METALLIC = 0.2;
  2773. }
  2774. )");
  2775. scene_globals.default_material = material_storage->material_allocate();
  2776. material_storage->material_initialize(scene_globals.default_material);
  2777. material_storage->material_set_shader(scene_globals.default_material, scene_globals.default_shader);
  2778. default_material_data_ptr = static_cast<GLES3::SceneMaterialData *>(GLES3::MaterialStorage::get_singleton()->material_get_data(scene_globals.default_material, RS::SHADER_SPATIAL));
  2779. }
  2780. {
  2781. // Overdraw material and shader.
  2782. scene_globals.overdraw_shader = material_storage->shader_allocate();
  2783. material_storage->shader_initialize(scene_globals.overdraw_shader);
  2784. material_storage->shader_set_code(scene_globals.overdraw_shader, R"(
  2785. // 3D editor Overdraw debug draw mode shader (Compatibility).
  2786. shader_type spatial;
  2787. render_mode blend_add, unshaded, fog_disabled;
  2788. void fragment() {
  2789. ALBEDO = vec3(0.4, 0.8, 0.8);
  2790. ALPHA = 0.2;
  2791. }
  2792. )");
  2793. scene_globals.overdraw_material = material_storage->material_allocate();
  2794. material_storage->material_initialize(scene_globals.overdraw_material);
  2795. material_storage->material_set_shader(scene_globals.overdraw_material, scene_globals.overdraw_shader);
  2796. overdraw_material_data_ptr = static_cast<GLES3::SceneMaterialData *>(GLES3::MaterialStorage::get_singleton()->material_get_data(scene_globals.overdraw_material, RS::SHADER_SPATIAL));
  2797. }
  2798. {
  2799. // Initialize Sky stuff
  2800. sky_globals.roughness_layers = GLOBAL_GET("rendering/reflections/sky_reflections/roughness_layers");
  2801. sky_globals.ggx_samples = GLOBAL_GET("rendering/reflections/sky_reflections/ggx_samples");
  2802. String global_defines;
  2803. global_defines += "#define MAX_GLOBAL_SHADER_UNIFORMS 256\n"; // TODO: this is arbitrary for now
  2804. global_defines += "\n#define MAX_DIRECTIONAL_LIGHT_DATA_STRUCTS " + itos(sky_globals.max_directional_lights) + "\n";
  2805. material_storage->shaders.sky_shader.initialize(global_defines);
  2806. sky_globals.shader_default_version = material_storage->shaders.sky_shader.version_create();
  2807. }
  2808. {
  2809. String global_defines;
  2810. global_defines += "\n#define MAX_SAMPLE_COUNT " + itos(sky_globals.ggx_samples) + "\n";
  2811. material_storage->shaders.cubemap_filter_shader.initialize(global_defines);
  2812. scene_globals.cubemap_filter_shader_version = material_storage->shaders.cubemap_filter_shader.version_create();
  2813. }
  2814. {
  2815. sky_globals.default_shader = material_storage->shader_allocate();
  2816. material_storage->shader_initialize(sky_globals.default_shader);
  2817. material_storage->shader_set_code(sky_globals.default_shader, R"(
  2818. // Default sky shader.
  2819. shader_type sky;
  2820. void sky() {
  2821. COLOR = vec3(0.0);
  2822. }
  2823. )");
  2824. sky_globals.default_material = material_storage->material_allocate();
  2825. material_storage->material_initialize(sky_globals.default_material);
  2826. material_storage->material_set_shader(sky_globals.default_material, sky_globals.default_shader);
  2827. }
  2828. {
  2829. sky_globals.fog_shader = material_storage->shader_allocate();
  2830. material_storage->shader_initialize(sky_globals.fog_shader);
  2831. material_storage->shader_set_code(sky_globals.fog_shader, R"(
  2832. // Default clear color sky shader.
  2833. shader_type sky;
  2834. uniform vec4 clear_color;
  2835. void sky() {
  2836. COLOR = clear_color.rgb;
  2837. }
  2838. )");
  2839. sky_globals.fog_material = material_storage->material_allocate();
  2840. material_storage->material_initialize(sky_globals.fog_material);
  2841. material_storage->material_set_shader(sky_globals.fog_material, sky_globals.fog_shader);
  2842. }
  2843. {
  2844. glGenVertexArrays(1, &sky_globals.screen_triangle_array);
  2845. glBindVertexArray(sky_globals.screen_triangle_array);
  2846. glGenBuffers(1, &sky_globals.screen_triangle);
  2847. glBindBuffer(GL_ARRAY_BUFFER, sky_globals.screen_triangle);
  2848. const float qv[6] = {
  2849. -1.0f,
  2850. -1.0f,
  2851. 3.0f,
  2852. -1.0f,
  2853. -1.0f,
  2854. 3.0f,
  2855. };
  2856. 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");
  2857. glVertexAttribPointer(RS::ARRAY_VERTEX, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 2, nullptr);
  2858. glEnableVertexAttribArray(RS::ARRAY_VERTEX);
  2859. glBindVertexArray(0);
  2860. glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind
  2861. }
  2862. #ifdef GL_API_ENABLED
  2863. if (RasterizerGLES3::is_gles_over_gl()) {
  2864. glEnable(_EXT_TEXTURE_CUBE_MAP_SEAMLESS);
  2865. }
  2866. #endif // GL_API_ENABLED
  2867. // MultiMesh may read from color when color is disabled, so make sure that the color defaults to white instead of black;
  2868. glVertexAttrib4f(RS::ARRAY_COLOR, 1.0, 1.0, 1.0, 1.0);
  2869. }
  2870. RasterizerSceneGLES3::~RasterizerSceneGLES3() {
  2871. GLES3::Utilities::get_singleton()->buffer_free_data(scene_state.directional_light_buffer);
  2872. GLES3::Utilities::get_singleton()->buffer_free_data(scene_state.omni_light_buffer);
  2873. GLES3::Utilities::get_singleton()->buffer_free_data(scene_state.spot_light_buffer);
  2874. GLES3::Utilities::get_singleton()->buffer_free_data(scene_state.positional_shadow_buffer);
  2875. GLES3::Utilities::get_singleton()->buffer_free_data(scene_state.directional_shadow_buffer);
  2876. memdelete_arr(scene_state.directional_lights);
  2877. memdelete_arr(scene_state.omni_lights);
  2878. memdelete_arr(scene_state.spot_lights);
  2879. memdelete_arr(scene_state.omni_light_sort);
  2880. memdelete_arr(scene_state.spot_light_sort);
  2881. memdelete_arr(scene_state.positional_shadows);
  2882. memdelete_arr(scene_state.directional_shadows);
  2883. // Scene Shader
  2884. GLES3::MaterialStorage::get_singleton()->shaders.scene_shader.version_free(scene_globals.shader_default_version);
  2885. GLES3::MaterialStorage::get_singleton()->shaders.cubemap_filter_shader.version_free(scene_globals.cubemap_filter_shader_version);
  2886. RSG::material_storage->material_free(scene_globals.default_material);
  2887. RSG::material_storage->shader_free(scene_globals.default_shader);
  2888. // Overdraw Shader
  2889. RSG::material_storage->material_free(scene_globals.overdraw_material);
  2890. RSG::material_storage->shader_free(scene_globals.overdraw_shader);
  2891. // Sky Shader
  2892. GLES3::MaterialStorage::get_singleton()->shaders.sky_shader.version_free(sky_globals.shader_default_version);
  2893. RSG::material_storage->material_free(sky_globals.default_material);
  2894. RSG::material_storage->shader_free(sky_globals.default_shader);
  2895. RSG::material_storage->material_free(sky_globals.fog_material);
  2896. RSG::material_storage->shader_free(sky_globals.fog_shader);
  2897. GLES3::Utilities::get_singleton()->buffer_free_data(sky_globals.screen_triangle);
  2898. glDeleteVertexArrays(1, &sky_globals.screen_triangle_array);
  2899. glDeleteTextures(1, &sky_globals.radical_inverse_vdc_cache_tex);
  2900. GLES3::Utilities::get_singleton()->buffer_free_data(sky_globals.directional_light_buffer);
  2901. memdelete_arr(sky_globals.directional_lights);
  2902. memdelete_arr(sky_globals.last_frame_directional_lights);
  2903. // UBOs
  2904. if (scene_state.ubo_buffer != 0) {
  2905. GLES3::Utilities::get_singleton()->buffer_free_data(scene_state.ubo_buffer);
  2906. }
  2907. if (scene_state.multiview_buffer != 0) {
  2908. GLES3::Utilities::get_singleton()->buffer_free_data(scene_state.multiview_buffer);
  2909. }
  2910. if (scene_state.tonemap_buffer != 0) {
  2911. GLES3::Utilities::get_singleton()->buffer_free_data(scene_state.tonemap_buffer);
  2912. }
  2913. singleton = nullptr;
  2914. }
  2915. #endif // GLES3_ENABLED