diff options
Diffstat (limited to 'drivers/gles3/rasterizer_scene_gles3.cpp')
-rw-r--r-- | drivers/gles3/rasterizer_scene_gles3.cpp | 2317 |
1 files changed, 1842 insertions, 475 deletions
diff --git a/drivers/gles3/rasterizer_scene_gles3.cpp b/drivers/gles3/rasterizer_scene_gles3.cpp index e6e7dd6f17..efd554eac9 100644 --- a/drivers/gles3/rasterizer_scene_gles3.cpp +++ b/drivers/gles3/rasterizer_scene_gles3.cpp @@ -29,15 +29,19 @@ /**************************************************************************/ #include "rasterizer_scene_gles3.h" -#include "core/config/project_settings.h" -#include "core/templates/sort_array.h" -#include "servers/rendering/rendering_server_default.h" -#include "servers/rendering/rendering_server_globals.h" + +#include "drivers/gles3/effects/copy_effects.h" +#include "rasterizer_gles3.h" #include "storage/config.h" #include "storage/mesh_storage.h" #include "storage/particles_storage.h" #include "storage/texture_storage.h" +#include "core/config/project_settings.h" +#include "core/templates/sort_array.h" +#include "servers/rendering/rendering_server_default.h" +#include "servers/rendering/rendering_server_globals.h" + #ifdef GLES3_ENABLED RasterizerSceneGLES3 *RasterizerSceneGLES3::singleton = nullptr; @@ -67,24 +71,24 @@ uint32_t RasterizerSceneGLES3::geometry_instance_get_pair_mask() { void RasterizerSceneGLES3::GeometryInstanceGLES3::pair_light_instances(const RID *p_light_instances, uint32_t p_light_instance_count) { GLES3::Config *config = GLES3::Config::get_singleton(); - omni_light_count = 0; - spot_light_count = 0; - omni_lights.clear(); - spot_lights.clear(); + paired_omni_light_count = 0; + paired_spot_light_count = 0; + paired_omni_lights.clear(); + paired_spot_lights.clear(); for (uint32_t i = 0; i < p_light_instance_count; i++) { RS::LightType type = GLES3::LightStorage::get_singleton()->light_instance_get_type(p_light_instances[i]); switch (type) { case RS::LIGHT_OMNI: { - if (omni_light_count < (uint32_t)config->max_lights_per_object) { - omni_lights.push_back(p_light_instances[i]); - omni_light_count++; + if (paired_omni_light_count < (uint32_t)config->max_lights_per_object) { + paired_omni_lights.push_back(p_light_instances[i]); + paired_omni_light_count++; } } break; case RS::LIGHT_SPOT: { - if (spot_light_count < (uint32_t)config->max_lights_per_object) { - spot_lights.push_back(p_light_instances[i]); - spot_light_count++; + if (paired_spot_light_count < (uint32_t)config->max_lights_per_object) { + paired_spot_lights.push_back(p_light_instances[i]); + paired_spot_light_count++; } } break; default: @@ -95,7 +99,7 @@ void RasterizerSceneGLES3::GeometryInstanceGLES3::pair_light_instances(const RID void RasterizerSceneGLES3::geometry_instance_free(RenderGeometryInstance *p_geometry_instance) { GeometryInstanceGLES3 *ginstance = static_cast<GeometryInstanceGLES3 *>(p_geometry_instance); - ERR_FAIL_COND(!ginstance); + ERR_FAIL_NULL(ginstance); GeometryInstanceSurface *surf = ginstance->surface_caches; while (surf) { GeometryInstanceSurface *next = surf->next; @@ -126,9 +130,27 @@ void RasterizerSceneGLES3::GeometryInstanceGLES3::_mark_dirty() { } void RasterizerSceneGLES3::GeometryInstanceGLES3::set_use_lightmap(RID p_lightmap_instance, const Rect2 &p_lightmap_uv_scale, int p_lightmap_slice_index) { + lightmap_instance = p_lightmap_instance; + lightmap_uv_scale = p_lightmap_uv_scale; + lightmap_slice_index = p_lightmap_slice_index; + + _mark_dirty(); } void RasterizerSceneGLES3::GeometryInstanceGLES3::set_lightmap_capture(const Color *p_sh9) { + if (p_sh9) { + if (lightmap_sh == nullptr) { + lightmap_sh = memnew(GeometryInstanceLightmapSH); + } + + memcpy(lightmap_sh->sh, p_sh9, sizeof(Color) * 9); + } else { + if (lightmap_sh != nullptr) { + memdelete(lightmap_sh); + lightmap_sh = nullptr; + } + } + _mark_dirty(); } void RasterizerSceneGLES3::_update_dirty_geometry_instances() { @@ -205,7 +227,7 @@ void RasterizerSceneGLES3::_geometry_instance_add_surface_with_material(Geometry GLES3::SceneMaterialData *material_shadow = nullptr; void *surface_shadow = nullptr; - 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) { + 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) { flags |= GeometryInstanceSurface::FLAG_USES_SHARED_SHADOW_MATERIAL; material_shadow = static_cast<GLES3::SceneMaterialData *>(GLES3::MaterialStorage::get_singleton()->material_get_data(scene_globals.default_material, RS::SHADER_SPATIAL)); @@ -255,6 +277,13 @@ void RasterizerSceneGLES3::_geometry_instance_add_surface_with_material(Geometry sdcache->sort.shader_id = p_shader_id; sdcache->sort.geometry_id = p_mesh.get_local_index(); sdcache->sort.priority = p_material->priority; + + GLES3::Mesh::Surface *s = reinterpret_cast<GLES3::Mesh::Surface *>(sdcache->surface); + if (p_material->shader_data->uses_tangent && !(s->format & RS::ARRAY_FORMAT_TANGENT)) { + String shader_path = p_material->shader_data->path.is_empty() ? "" : "(" + p_material->shader_data->path + ")"; + String mesh_path = mesh_storage->mesh_get_path(p_mesh).is_empty() ? "" : "(" + mesh_storage->mesh_get_path(p_mesh) + ")"; + 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)); + } } 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) { @@ -300,7 +329,7 @@ void RasterizerSceneGLES3::_geometry_instance_add_surface(GeometryInstanceGLES3 m_src = scene_globals.default_material; } - ERR_FAIL_COND(!material_data); + ERR_FAIL_NULL(material_data); _geometry_instance_add_surface_with_material_chain(ginstance, p_surface, material_data, m_src, p_mesh); @@ -462,7 +491,7 @@ void RasterizerSceneGLES3::sky_initialize(RID p_rid) { void RasterizerSceneGLES3::sky_set_radiance_size(RID p_sky, int p_radiance_size) { Sky *sky = sky_owner.get_or_null(p_sky); - ERR_FAIL_COND(!sky); + ERR_FAIL_NULL(sky); ERR_FAIL_COND_MSG(p_radiance_size < 32 || p_radiance_size > 2048, "Sky radiance size must be between 32 and 2048"); if (sky->radiance_size == p_radiance_size) { @@ -477,7 +506,7 @@ void RasterizerSceneGLES3::sky_set_radiance_size(RID p_sky, int p_radiance_size) void RasterizerSceneGLES3::sky_set_mode(RID p_sky, RS::SkyMode p_mode) { Sky *sky = sky_owner.get_or_null(p_sky); - ERR_FAIL_COND(!sky); + ERR_FAIL_NULL(sky); if (sky->mode == p_mode) { return; @@ -489,7 +518,7 @@ void RasterizerSceneGLES3::sky_set_mode(RID p_sky, RS::SkyMode p_mode) { void RasterizerSceneGLES3::sky_set_material(RID p_sky, RID p_material) { Sky *sky = sky_owner.get_or_null(p_sky); - ERR_FAIL_COND(!sky); + ERR_FAIL_NULL(sky); if (sky->material == p_material) { return; @@ -501,7 +530,7 @@ void RasterizerSceneGLES3::sky_set_material(RID p_sky, RID p_material) { float RasterizerSceneGLES3::sky_get_baked_exposure(RID p_sky) const { Sky *sky = sky_owner.get_or_null(p_sky); - ERR_FAIL_COND_V(!sky, 1.0); + ERR_FAIL_NULL_V(sky, 1.0); return sky->baked_exposure; } @@ -514,6 +543,38 @@ void RasterizerSceneGLES3::_invalidate_sky(Sky *p_sky) { } } +GLuint _init_radiance_texture(int p_size, int p_mipmaps, String p_name) { + GLuint radiance_id = 0; + + glGenTextures(1, &radiance_id); + glBindTexture(GL_TEXTURE_CUBE_MAP, radiance_id); +#ifdef GL_API_ENABLED + if (RasterizerGLES3::is_gles_over_gl()) { + //TODO, on low-end compare this to allocating each face of each mip individually + // see: https://www.khronos.org/registry/OpenGL-Refpages/es3.0/html/glTexStorage2D.xhtml + for (int i = 0; i < 6; i++) { + glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB10_A2, p_size, p_size, 0, GL_RGBA, GL_UNSIGNED_INT_2_10_10_10_REV, nullptr); + } + + glGenerateMipmap(GL_TEXTURE_CUBE_MAP); + } +#endif // GL_API_ENABLED +#ifdef GLES_API_ENABLED + if (!RasterizerGLES3::is_gles_over_gl()) { + glTexStorage2D(GL_TEXTURE_CUBE_MAP, p_mipmaps, GL_RGB10_A2, p_size, p_size); + } +#endif // GLES_API_ENABLED + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_BASE_LEVEL, 0); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAX_LEVEL, p_mipmaps - 1); + + GLES3::Utilities::get_singleton()->texture_allocated_data(radiance_id, Image::get_image_data_size(p_size, p_size, Image::FORMAT_RGBA8, true), p_name); + return radiance_id; +} + void RasterizerSceneGLES3::_update_dirty_skys() { Sky *sky = dirty_sky_list; @@ -522,57 +583,8 @@ void RasterizerSceneGLES3::_update_dirty_skys() { sky->mipmap_count = Image::get_image_required_mipmaps(sky->radiance_size, sky->radiance_size, Image::FORMAT_RGBA8) - 1; // Left uninitialized, will attach a texture at render time glGenFramebuffers(1, &sky->radiance_framebuffer); - - GLenum internal_format = GL_RGB10_A2; - - glGenTextures(1, &sky->radiance); - glBindTexture(GL_TEXTURE_CUBE_MAP, sky->radiance); - -#ifdef GLES_OVER_GL - GLenum format = GL_RGBA; - GLenum type = GL_UNSIGNED_INT_2_10_10_10_REV; - //TODO, on low-end compare this to allocating each face of each mip individually - // see: https://www.khronos.org/registry/OpenGL-Refpages/es3.0/html/glTexStorage2D.xhtml - for (int i = 0; i < 6; i++) { - glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, internal_format, sky->radiance_size, sky->radiance_size, 0, format, type, nullptr); - } - - glGenerateMipmap(GL_TEXTURE_CUBE_MAP); -#else - glTexStorage2D(GL_TEXTURE_CUBE_MAP, sky->mipmap_count, internal_format, sky->radiance_size, sky->radiance_size); -#endif - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_BASE_LEVEL, 0); - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAX_LEVEL, sky->mipmap_count - 1); - - 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"); - - glGenTextures(1, &sky->raw_radiance); - glBindTexture(GL_TEXTURE_CUBE_MAP, sky->raw_radiance); - -#ifdef GLES_OVER_GL - //TODO, on low-end compare this to allocating each face of each mip individually - // see: https://www.khronos.org/registry/OpenGL-Refpages/es3.0/html/glTexStorage2D.xhtml - for (int i = 0; i < 6; i++) { - glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, internal_format, sky->radiance_size, sky->radiance_size, 0, format, type, nullptr); - } - - glGenerateMipmap(GL_TEXTURE_CUBE_MAP); -#else - glTexStorage2D(GL_TEXTURE_CUBE_MAP, sky->mipmap_count, internal_format, sky->radiance_size, sky->radiance_size); -#endif - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_BASE_LEVEL, 0); - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAX_LEVEL, sky->mipmap_count - 1); - - glBindTexture(GL_TEXTURE_CUBE_MAP, 0); - 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"); + sky->radiance = _init_radiance_texture(sky->radiance_size, sky->mipmap_count, "Sky radiance texture"); + sky->raw_radiance = _init_radiance_texture(sky->radiance_size, sky->mipmap_count, "Sky raw radiance texture"); } sky->reflection_dirty = true; @@ -608,18 +620,20 @@ void RasterizerSceneGLES3::_setup_sky(const RenderDataGLES3 *p_render_data, cons material = nullptr; } } + } - if (!material) { - sky_material = sky_globals.default_material; - material = static_cast<GLES3::SkyMaterialData *>(material_storage->material_get_data(sky_material, RS::SHADER_SKY)); - } + if (!material) { + sky_material = sky_globals.default_material; + material = static_cast<GLES3::SkyMaterialData *>(material_storage->material_get_data(sky_material, RS::SHADER_SKY)); + } - ERR_FAIL_COND(!material); + ERR_FAIL_NULL(material); - shader_data = material->shader_data; + shader_data = material->shader_data; - ERR_FAIL_COND(!shader_data); + ERR_FAIL_NULL(shader_data); + if (sky) { if (shader_data->uses_time && time - sky->prev_time > 0.00001) { sky->prev_time = time; sky->reflection_dirty = true; @@ -640,111 +654,113 @@ void RasterizerSceneGLES3::_setup_sky(const RenderDataGLES3 *p_render_data, cons sky->prev_position = p_transform.origin; sky->reflection_dirty = true; } + } - glBindBufferBase(GL_UNIFORM_BUFFER, SKY_DIRECTIONAL_LIGHT_UNIFORM_LOCATION, sky_globals.directional_light_buffer); - if (shader_data->uses_light) { - sky_globals.directional_light_count = 0; - for (int i = 0; i < (int)p_lights.size(); i++) { - GLES3::LightInstance *li = GLES3::LightStorage::get_singleton()->get_light_instance(p_lights[i]); - if (!li) { - continue; - } - RID base = li->light; + glBindBufferBase(GL_UNIFORM_BUFFER, SKY_DIRECTIONAL_LIGHT_UNIFORM_LOCATION, sky_globals.directional_light_buffer); + if (shader_data->uses_light) { + sky_globals.directional_light_count = 0; + for (int i = 0; i < (int)p_lights.size(); i++) { + GLES3::LightInstance *li = GLES3::LightStorage::get_singleton()->get_light_instance(p_lights[i]); + if (!li) { + continue; + } + RID base = li->light; - ERR_CONTINUE(base.is_null()); + ERR_CONTINUE(base.is_null()); - RS::LightType type = light_storage->light_get_type(base); - if (type == RS::LIGHT_DIRECTIONAL && light_storage->light_directional_get_sky_mode(base) != RS::LIGHT_DIRECTIONAL_SKY_MODE_LIGHT_ONLY) { - DirectionalLightData &sky_light_data = sky_globals.directional_lights[sky_globals.directional_light_count]; - Transform3D light_transform = li->transform; - Vector3 world_direction = light_transform.basis.xform(Vector3(0, 0, 1)).normalized(); + RS::LightType type = light_storage->light_get_type(base); + if (type == RS::LIGHT_DIRECTIONAL && light_storage->light_directional_get_sky_mode(base) != RS::LIGHT_DIRECTIONAL_SKY_MODE_LIGHT_ONLY) { + DirectionalLightData &sky_light_data = sky_globals.directional_lights[sky_globals.directional_light_count]; + Transform3D light_transform = li->transform; + Vector3 world_direction = light_transform.basis.xform(Vector3(0, 0, 1)).normalized(); - sky_light_data.direction[0] = world_direction.x; - sky_light_data.direction[1] = world_direction.y; - sky_light_data.direction[2] = world_direction.z; + sky_light_data.direction[0] = world_direction.x; + sky_light_data.direction[1] = world_direction.y; + sky_light_data.direction[2] = world_direction.z; - float sign = light_storage->light_is_negative(base) ? -1 : 1; - sky_light_data.energy = sign * light_storage->light_get_param(base, RS::LIGHT_PARAM_ENERGY); + float sign = light_storage->light_is_negative(base) ? -1 : 1; + sky_light_data.energy = sign * light_storage->light_get_param(base, RS::LIGHT_PARAM_ENERGY); - if (is_using_physical_light_units()) { - sky_light_data.energy *= light_storage->light_get_param(base, RS::LIGHT_PARAM_INTENSITY); - } + if (is_using_physical_light_units()) { + sky_light_data.energy *= light_storage->light_get_param(base, RS::LIGHT_PARAM_INTENSITY); + } - if (p_render_data->camera_attributes.is_valid()) { - sky_light_data.energy *= RSG::camera_attributes->camera_attributes_get_exposure_normalization_factor(p_render_data->camera_attributes); - } + if (p_render_data->camera_attributes.is_valid()) { + sky_light_data.energy *= RSG::camera_attributes->camera_attributes_get_exposure_normalization_factor(p_render_data->camera_attributes); + } - Color linear_col = light_storage->light_get_color(base); - sky_light_data.color[0] = linear_col.r; - sky_light_data.color[1] = linear_col.g; - sky_light_data.color[2] = linear_col.b; + Color linear_col = light_storage->light_get_color(base); + sky_light_data.color[0] = linear_col.r; + sky_light_data.color[1] = linear_col.g; + sky_light_data.color[2] = linear_col.b; - sky_light_data.enabled = true; + sky_light_data.enabled = true; - float angular_diameter = light_storage->light_get_param(base, RS::LIGHT_PARAM_SIZE); - if (angular_diameter > 0.0) { - angular_diameter = Math::tan(Math::deg_to_rad(angular_diameter)); - } else { - angular_diameter = 0.0; - } - sky_light_data.size = angular_diameter; - sky_globals.directional_light_count++; - if (sky_globals.directional_light_count >= sky_globals.max_directional_lights) { - break; - } + float angular_diameter = light_storage->light_get_param(base, RS::LIGHT_PARAM_SIZE); + if (angular_diameter > 0.0) { + angular_diameter = Math::tan(Math::deg_to_rad(angular_diameter)); + } else { + angular_diameter = 0.0; + } + sky_light_data.size = angular_diameter; + sky_globals.directional_light_count++; + if (sky_globals.directional_light_count >= sky_globals.max_directional_lights) { + break; } } - // Check whether the directional_light_buffer changes - bool light_data_dirty = false; - - // Light buffer is dirty if we have fewer or more lights - // If we have fewer lights, make sure that old lights are disabled - if (sky_globals.directional_light_count != sky_globals.last_frame_directional_light_count) { - light_data_dirty = true; - for (uint32_t i = sky_globals.directional_light_count; i < sky_globals.max_directional_lights; i++) { - sky_globals.directional_lights[i].enabled = false; - sky_globals.last_frame_directional_lights[i].enabled = false; - } - } - - if (!light_data_dirty) { - for (uint32_t i = 0; i < sky_globals.directional_light_count; i++) { - if (sky_globals.directional_lights[i].direction[0] != sky_globals.last_frame_directional_lights[i].direction[0] || - sky_globals.directional_lights[i].direction[1] != sky_globals.last_frame_directional_lights[i].direction[1] || - sky_globals.directional_lights[i].direction[2] != sky_globals.last_frame_directional_lights[i].direction[2] || - sky_globals.directional_lights[i].energy != sky_globals.last_frame_directional_lights[i].energy || - sky_globals.directional_lights[i].color[0] != sky_globals.last_frame_directional_lights[i].color[0] || - sky_globals.directional_lights[i].color[1] != sky_globals.last_frame_directional_lights[i].color[1] || - sky_globals.directional_lights[i].color[2] != sky_globals.last_frame_directional_lights[i].color[2] || - sky_globals.directional_lights[i].enabled != sky_globals.last_frame_directional_lights[i].enabled || - sky_globals.directional_lights[i].size != sky_globals.last_frame_directional_lights[i].size) { - light_data_dirty = true; - break; - } + } + // Check whether the directional_light_buffer changes + bool light_data_dirty = false; + + // Light buffer is dirty if we have fewer or more lights + // If we have fewer lights, make sure that old lights are disabled + if (sky_globals.directional_light_count != sky_globals.last_frame_directional_light_count) { + light_data_dirty = true; + for (uint32_t i = sky_globals.directional_light_count; i < sky_globals.max_directional_lights; i++) { + sky_globals.directional_lights[i].enabled = false; + sky_globals.last_frame_directional_lights[i].enabled = false; + } + } + + if (!light_data_dirty) { + for (uint32_t i = 0; i < sky_globals.directional_light_count; i++) { + if (sky_globals.directional_lights[i].direction[0] != sky_globals.last_frame_directional_lights[i].direction[0] || + sky_globals.directional_lights[i].direction[1] != sky_globals.last_frame_directional_lights[i].direction[1] || + sky_globals.directional_lights[i].direction[2] != sky_globals.last_frame_directional_lights[i].direction[2] || + sky_globals.directional_lights[i].energy != sky_globals.last_frame_directional_lights[i].energy || + sky_globals.directional_lights[i].color[0] != sky_globals.last_frame_directional_lights[i].color[0] || + sky_globals.directional_lights[i].color[1] != sky_globals.last_frame_directional_lights[i].color[1] || + sky_globals.directional_lights[i].color[2] != sky_globals.last_frame_directional_lights[i].color[2] || + sky_globals.directional_lights[i].enabled != sky_globals.last_frame_directional_lights[i].enabled || + sky_globals.directional_lights[i].size != sky_globals.last_frame_directional_lights[i].size) { + light_data_dirty = true; + break; } } + } - if (light_data_dirty) { - glBufferData(GL_UNIFORM_BUFFER, sizeof(DirectionalLightData) * sky_globals.max_directional_lights, sky_globals.directional_lights, GL_STREAM_DRAW); - glBindBuffer(GL_UNIFORM_BUFFER, 0); + if (light_data_dirty) { + glBufferData(GL_UNIFORM_BUFFER, sizeof(DirectionalLightData) * sky_globals.max_directional_lights, sky_globals.directional_lights, GL_STREAM_DRAW); + glBindBuffer(GL_UNIFORM_BUFFER, 0); - DirectionalLightData *temp = sky_globals.last_frame_directional_lights; - sky_globals.last_frame_directional_lights = sky_globals.directional_lights; - sky_globals.directional_lights = temp; - sky_globals.last_frame_directional_light_count = sky_globals.directional_light_count; + DirectionalLightData *temp = sky_globals.last_frame_directional_lights; + sky_globals.last_frame_directional_lights = sky_globals.directional_lights; + sky_globals.directional_lights = temp; + sky_globals.last_frame_directional_light_count = sky_globals.directional_light_count; + if (sky) { sky->reflection_dirty = true; } } + } - if (p_render_data->view_count > 1) { - glBindBufferBase(GL_UNIFORM_BUFFER, SKY_MULTIVIEW_UNIFORM_LOCATION, scene_state.multiview_buffer); - glBindBuffer(GL_UNIFORM_BUFFER, 0); - } + if (p_render_data->view_count > 1) { + glBindBufferBase(GL_UNIFORM_BUFFER, SKY_MULTIVIEW_UNIFORM_LOCATION, scene_state.multiview_buffer); + glBindBuffer(GL_UNIFORM_BUFFER, 0); + } - if (!sky->radiance) { - _invalidate_sky(sky); - _update_dirty_skys(); - } + if (sky && !sky->radiance) { + _invalidate_sky(sky); + _update_dirty_skys(); } } @@ -753,7 +769,7 @@ void RasterizerSceneGLES3::_draw_sky(RID p_env, const Projection &p_projection, ERR_FAIL_COND(p_env.is_null()); Sky *sky = sky_owner.get_or_null(environment_get_sky(p_env)); - ERR_FAIL_COND(!sky); + ERR_FAIL_NULL(sky); GLES3::SkyMaterialData *material_data = nullptr; RID sky_material; @@ -784,12 +800,12 @@ void RasterizerSceneGLES3::_draw_sky(RID p_env, const Projection &p_projection, material_data = static_cast<GLES3::SkyMaterialData *>(material_storage->material_get_data(sky_material, RS::SHADER_SKY)); } - ERR_FAIL_COND(!material_data); + ERR_FAIL_NULL(material_data); material_data->bind_uniforms(); GLES3::SkyShaderData *shader_data = material_data->shader_data; - ERR_FAIL_COND(!shader_data); + ERR_FAIL_NULL(shader_data); // Camera Projection camera; @@ -832,7 +848,7 @@ void RasterizerSceneGLES3::_update_sky_radiance(RID p_env, const Projection &p_p ERR_FAIL_COND(p_env.is_null()); Sky *sky = sky_owner.get_or_null(environment_get_sky(p_env)); - ERR_FAIL_COND(!sky); + ERR_FAIL_NULL(sky); GLES3::SkyMaterialData *material_data = nullptr; RID sky_material; @@ -840,7 +856,7 @@ void RasterizerSceneGLES3::_update_sky_radiance(RID p_env, const Projection &p_p RS::EnvironmentBG background = environment_get_background(p_env); if (sky) { - ERR_FAIL_COND(!sky); + ERR_FAIL_NULL(sky); sky_material = sky->material; if (sky_material.is_valid()) { @@ -859,12 +875,12 @@ void RasterizerSceneGLES3::_update_sky_radiance(RID p_env, const Projection &p_p material_data = static_cast<GLES3::SkyMaterialData *>(material_storage->material_get_data(sky_material, RS::SHADER_SKY)); } - ERR_FAIL_COND(!material_data); + ERR_FAIL_NULL(material_data); material_data->bind_uniforms(); GLES3::SkyShaderData *shader_data = material_data->shader_data; - ERR_FAIL_COND(!shader_data); + ERR_FAIL_NULL(shader_data); bool update_single_frame = sky->mode == RS::SKY_MODE_REALTIME || sky->mode == RS::SKY_MODE_QUALITY; RS::SkyMode sky_mode = sky->mode; @@ -930,6 +946,14 @@ void RasterizerSceneGLES3::_update_sky_radiance(RID p_env, const Projection &p_p glViewport(0, 0, sky->radiance_size, sky->radiance_size); glBindFramebuffer(GL_FRAMEBUFFER, sky->radiance_framebuffer); + glDisable(GL_BLEND); + glDepthMask(GL_FALSE); + glDisable(GL_DEPTH_TEST); + scene_state.current_depth_test = GLES3::SceneShaderData::DEPTH_TEST_DISABLED; + glDisable(GL_SCISSOR_TEST); + glDisable(GL_CULL_FACE); + scene_state.cull_mode = GLES3::SceneShaderData::CULL_DISABLED; + for (int i = 0; i < 6; i++) { Basis local_view = Basis::looking_at(view_normals[i], view_up[i]); material_storage->shaders.sky_shader.version_set_uniform(SkyShaderGLES3::ORIENTATION, local_view, shader_data->version, SkyShaderGLES3::MODE_CUBEMAP); @@ -949,6 +973,14 @@ void RasterizerSceneGLES3::_update_sky_radiance(RID p_env, const Projection &p_p sky->reflection_dirty = false; } else { if (sky_mode == RS::SKY_MODE_INCREMENTAL && sky->processing_layer < max_processing_layer) { + glDisable(GL_BLEND); + glDepthMask(GL_FALSE); + glDisable(GL_DEPTH_TEST); + scene_state.current_depth_test = GLES3::SceneShaderData::DEPTH_TEST_DISABLED; + glDisable(GL_SCISSOR_TEST); + glDisable(GL_CULL_FACE); + scene_state.cull_mode = GLES3::SceneShaderData::CULL_DISABLED; + _filter_sky_radiance(sky, sky->processing_layer); sky->processing_layer++; } @@ -1081,7 +1113,80 @@ void RasterizerSceneGLES3::_filter_sky_radiance(Sky *p_sky, int p_base_layer) { } Ref<Image> RasterizerSceneGLES3::sky_bake_panorama(RID p_sky, float p_energy, bool p_bake_irradiance, const Size2i &p_size) { - return Ref<Image>(); + Sky *sky = sky_owner.get_or_null(p_sky); + ERR_FAIL_NULL_V(sky, Ref<Image>()); + + _update_dirty_skys(); + + if (sky->radiance == 0) { + return Ref<Image>(); + } + + GLES3::CopyEffects *copy_effects = GLES3::CopyEffects::get_singleton(); + GLES3::Config *config = GLES3::Config::get_singleton(); + + GLuint rad_tex = 0; + glGenTextures(1, &rad_tex); + glBindTexture(GL_TEXTURE_2D, rad_tex); + if (config->float_texture_supported) { + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, p_size.width, p_size.height, 0, GL_RGBA, GL_FLOAT, nullptr); + GLES3::Utilities::get_singleton()->texture_allocated_data(rad_tex, p_size.width * p_size.height * 16, "Temp sky panorama"); + } else { + // Fallback to RGBA8 on devices that don't support rendering to floating point textures. This will look bad, but we have no choice. + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, p_size.width, p_size.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); + GLES3::Utilities::get_singleton()->texture_allocated_data(rad_tex, p_size.width * p_size.height * 4, "Temp sky panorama"); + } + + GLuint rad_fbo = 0; + glGenFramebuffers(1, &rad_fbo); + glBindFramebuffer(GL_FRAMEBUFFER, rad_fbo); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, rad_tex, 0); + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_CUBE_MAP, sky->radiance); + glViewport(0, 0, p_size.width, p_size.height); + + glClearColor(0.0, 0.0, 0.0, 1.0); + glClear(GL_COLOR_BUFFER_BIT); + + copy_effects->copy_cube_to_panorama(p_bake_irradiance ? float(sky->mipmap_count) : 0.0); + + glBindFramebuffer(GL_FRAMEBUFFER, 0); + glDeleteFramebuffers(1, &rad_fbo); + // Create a dummy texture so we can use texture_2d_get. + RID tex_rid = GLES3::TextureStorage::get_singleton()->texture_allocate(); + GLES3::Texture texture; + texture.width = p_size.width; + texture.height = p_size.height; + texture.alloc_width = p_size.width; + texture.alloc_height = p_size.height; + texture.format = Image::FORMAT_RGBAF; + texture.real_format = Image::FORMAT_RGBAF; + texture.gl_format_cache = GL_RGBA; + texture.gl_type_cache = GL_FLOAT; + texture.type = GLES3::Texture::TYPE_2D; + texture.target = GL_TEXTURE_2D; + texture.active = true; + texture.tex_id = rad_tex; + texture.is_render_target = true; + + GLES3::TextureStorage::get_singleton()->texture_2d_initialize_from_texture(tex_rid, texture); + Ref<Image> img = GLES3::TextureStorage::get_singleton()->texture_2d_get(tex_rid); + GLES3::Utilities::get_singleton()->texture_free_data(rad_tex); + + texture.is_render_target = false; + texture.tex_id = 0; + GLES3::TextureStorage::get_singleton()->texture_free(tex_rid); + + for (int i = 0; i < p_size.width; i++) { + for (int j = 0; j < p_size.height; j++) { + Color c = img->get_pixel(i, j); + c.r *= p_energy; + c.g *= p_energy; + c.b *= p_energy; + img->set_pixel(i, j, c); + } + } + return img; } /* ENVIRONMENT API */ @@ -1115,13 +1220,73 @@ void RasterizerSceneGLES3::environment_set_volumetric_fog_filter_active(bool p_e } Ref<Image> RasterizerSceneGLES3::environment_bake_panorama(RID p_env, bool p_bake_irradiance, const Size2i &p_size) { - return Ref<Image>(); + ERR_FAIL_COND_V(p_env.is_null(), Ref<Image>()); + + RS::EnvironmentBG environment_background = environment_get_background(p_env); + + if (environment_background == RS::ENV_BG_CAMERA_FEED || environment_background == RS::ENV_BG_CANVAS || environment_background == RS::ENV_BG_KEEP) { + return Ref<Image>(); // Nothing to bake. + } + + RS::EnvironmentAmbientSource ambient_source = environment_get_ambient_source(p_env); + + bool use_ambient_light = false; + bool use_cube_map = false; + if (ambient_source == RS::ENV_AMBIENT_SOURCE_BG && (environment_background == RS::ENV_BG_CLEAR_COLOR || environment_background == RS::ENV_BG_COLOR)) { + use_ambient_light = true; + } else { + use_cube_map = (ambient_source == RS::ENV_AMBIENT_SOURCE_BG && environment_background == RS::ENV_BG_SKY) || ambient_source == RS::ENV_AMBIENT_SOURCE_SKY; + use_ambient_light = use_cube_map || ambient_source == RS::ENV_AMBIENT_SOURCE_COLOR; + } + + use_cube_map = use_cube_map || (environment_background == RS::ENV_BG_SKY && environment_get_sky(p_env).is_valid()); + + Color ambient_color; + float ambient_color_sky_mix = 0.0; + if (use_ambient_light) { + ambient_color_sky_mix = environment_get_ambient_sky_contribution(p_env); + const float ambient_energy = environment_get_ambient_light_energy(p_env); + ambient_color = environment_get_ambient_light(p_env); + ambient_color = ambient_color.srgb_to_linear(); + ambient_color.r *= ambient_energy; + ambient_color.g *= ambient_energy; + ambient_color.b *= ambient_energy; + } + + if (use_cube_map) { + Ref<Image> panorama = sky_bake_panorama(environment_get_sky(p_env), environment_get_bg_energy_multiplier(p_env), p_bake_irradiance, p_size); + if (use_ambient_light) { + for (int x = 0; x < p_size.width; x++) { + for (int y = 0; y < p_size.height; y++) { + panorama->set_pixel(x, y, ambient_color.lerp(panorama->get_pixel(x, y), ambient_color_sky_mix)); + } + } + } + return panorama; + } else { + const float bg_energy_multiplier = environment_get_bg_energy_multiplier(p_env); + Color panorama_color = ((environment_background == RS::ENV_BG_CLEAR_COLOR) ? RSG::texture_storage->get_default_clear_color() : environment_get_bg_color(p_env)); + panorama_color = panorama_color.srgb_to_linear(); + panorama_color.r *= bg_energy_multiplier; + panorama_color.g *= bg_energy_multiplier; + panorama_color.b *= bg_energy_multiplier; + + if (use_ambient_light) { + panorama_color = ambient_color.lerp(panorama_color, ambient_color_sky_mix); + } + + Ref<Image> panorama = Image::create_empty(p_size.width, p_size.height, false, Image::FORMAT_RGBAF); + panorama->fill(panorama_color); + return panorama; + } } void RasterizerSceneGLES3::positional_soft_shadow_filter_set_quality(RS::ShadowQuality p_quality) { + scene_state.positional_shadow_quality = p_quality; } void RasterizerSceneGLES3::directional_soft_shadow_filter_set_quality(RS::ShadowQuality p_quality) { + scene_state.directional_shadow_quality = p_quality; } RID RasterizerSceneGLES3::fog_volume_instance_create(RID p_fog_volume) { @@ -1219,18 +1384,61 @@ void RasterizerSceneGLES3::_fill_render_list(RenderListType p_render_list, const // Sets the index values for lookup in the shader // This has to be done after _setup_lights was called this frame - // TODO, check shadow status of lights here, if using shadows, skip here and add below + if (p_pass_mode == PASS_MODE_COLOR) { - if (inst->omni_light_count) { - inst->omni_light_gl_cache.resize(inst->omni_light_count); - for (uint32_t j = 0; j < inst->omni_light_count; j++) { - inst->omni_light_gl_cache[j] = GLES3::LightStorage::get_singleton()->light_instance_get_gl_id(inst->omni_lights[j]); + inst->light_passes.clear(); + inst->spot_light_gl_cache.clear(); + inst->omni_light_gl_cache.clear(); + uint64_t current_frame = RSG::rasterizer->get_frame_number(); + + if (inst->paired_omni_light_count) { + for (uint32_t j = 0; j < inst->paired_omni_light_count; j++) { + RID light_instance = inst->paired_omni_lights[j]; + if (GLES3::LightStorage::get_singleton()->light_instance_get_render_pass(light_instance) != current_frame) { + continue; + } + RID light = GLES3::LightStorage::get_singleton()->light_instance_get_base_light(light_instance); + int32_t shadow_id = GLES3::LightStorage::get_singleton()->light_instance_get_shadow_id(light_instance); + + if (GLES3::LightStorage::get_singleton()->light_has_shadow(light) && shadow_id >= 0) { + // Skip static lights when a lightmap is used. + if (!inst->lightmap_instance.is_valid() || GLES3::LightStorage::get_singleton()->light_get_bake_mode(light) != RenderingServer::LIGHT_BAKE_STATIC) { + GeometryInstanceGLES3::LightPass pass; + pass.light_id = GLES3::LightStorage::get_singleton()->light_instance_get_gl_id(light_instance); + pass.shadow_id = shadow_id; + pass.light_instance_rid = light_instance; + pass.is_omni = true; + inst->light_passes.push_back(pass); + } + } else { + // Lights without shadow can all go in base pass. + inst->omni_light_gl_cache.push_back((uint32_t)GLES3::LightStorage::get_singleton()->light_instance_get_gl_id(light_instance)); + } } } - if (inst->spot_light_count) { - inst->spot_light_gl_cache.resize(inst->spot_light_count); - for (uint32_t j = 0; j < inst->spot_light_count; j++) { - inst->spot_light_gl_cache[j] = GLES3::LightStorage::get_singleton()->light_instance_get_gl_id(inst->spot_lights[j]); + + if (inst->paired_spot_light_count) { + for (uint32_t j = 0; j < inst->paired_spot_light_count; j++) { + RID light_instance = inst->paired_spot_lights[j]; + if (GLES3::LightStorage::get_singleton()->light_instance_get_render_pass(light_instance) != current_frame) { + continue; + } + RID light = GLES3::LightStorage::get_singleton()->light_instance_get_base_light(light_instance); + int32_t shadow_id = GLES3::LightStorage::get_singleton()->light_instance_get_shadow_id(light_instance); + + if (GLES3::LightStorage::get_singleton()->light_has_shadow(light) && shadow_id >= 0) { + // Skip static lights when a lightmap is used. + if (!inst->lightmap_instance.is_valid() || GLES3::LightStorage::get_singleton()->light_get_bake_mode(light) != RenderingServer::LIGHT_BAKE_STATIC) { + GeometryInstanceGLES3::LightPass pass; + pass.light_id = GLES3::LightStorage::get_singleton()->light_instance_get_gl_id(light_instance); + pass.shadow_id = shadow_id; + pass.light_instance_rid = light_instance; + inst->light_passes.push_back(pass); + } + } else { + // Lights without shadow can all go in base pass. + inst->spot_light_gl_cache.push_back((uint32_t)GLES3::LightStorage::get_singleton()->light_instance_get_gl_id(light_instance)); + } } } } @@ -1318,10 +1526,6 @@ void RasterizerSceneGLES3::_fill_render_list(RenderListType p_render_list, const scene_state.used_depth_texture = true; } - /* - Add elements here if there are shadows - */ - } else if (p_pass_mode == PASS_MODE_SHADOW) { if (surf->flags & GeometryInstanceSurface::FLAG_PASS_SHADOW) { rl->add_element(surf); @@ -1333,6 +1537,8 @@ void RasterizerSceneGLES3::_fill_render_list(RenderListType p_render_list, const } surf->sort.depth_layer = depth_layer; + surf->finished_base_pass = false; + surf->light_pass_index = 0; surf = surf->next; } @@ -1340,7 +1546,7 @@ void RasterizerSceneGLES3::_fill_render_list(RenderListType p_render_list, const } // Needs to be called after _setup_lights so that directional_light_count is accurate. -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) { +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) { Projection correction; correction.columns[1][1] = p_flip_y ? -1.0 : 1.0; Projection projection = correction * p_render_data->cam_projection; @@ -1349,6 +1555,7 @@ void RasterizerSceneGLES3::_setup_environment(const RenderDataGLES3 *p_render_da GLES3::MaterialStorage::store_camera(projection.inverse(), scene_state.ubo.inv_projection_matrix); GLES3::MaterialStorage::store_transform(p_render_data->cam_transform, scene_state.ubo.inv_view_matrix); GLES3::MaterialStorage::store_transform(p_render_data->inv_cam_transform, scene_state.ubo.view_matrix); + GLES3::MaterialStorage::store_transform(p_render_data->main_cam_transform, scene_state.ubo.main_cam_inv_view_matrix); scene_state.ubo.camera_visible_layers = p_render_data->camera_visible_layers; if (p_render_data->view_count > 1) { @@ -1364,7 +1571,8 @@ void RasterizerSceneGLES3::_setup_environment(const RenderDataGLES3 *p_render_da } } - scene_state.ubo.directional_light_count = p_render_data->directional_light_count; + // Only render the lights without shadows in the base pass. + scene_state.ubo.directional_light_count = p_render_data->directional_light_count - p_render_data->directional_shadow_count; scene_state.ubo.z_far = p_render_data->z_far; scene_state.ubo.z_near = p_render_data->z_near; @@ -1376,10 +1584,21 @@ void RasterizerSceneGLES3::_setup_environment(const RenderDataGLES3 *p_render_da scene_state.ubo.screen_pixel_size[0] = screen_pixel_size.x; scene_state.ubo.screen_pixel_size[1] = screen_pixel_size.y; + scene_state.ubo.shadow_bias = p_shadow_bias; + scene_state.ubo.pancake_shadows = p_pancake_shadows; + //time global variables scene_state.ubo.time = time; - if (is_environment(p_render_data->environment)) { + if (get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_UNSHADED) { + scene_state.ubo.use_ambient_light = true; + scene_state.ubo.ambient_light_color_energy[0] = 1; + scene_state.ubo.ambient_light_color_energy[1] = 1; + scene_state.ubo.ambient_light_color_energy[2] = 1; + scene_state.ubo.ambient_light_color_energy[3] = 1.0; + scene_state.ubo.use_ambient_cubemap = false; + scene_state.ubo.use_reflection_cubemap = false; + } else if (is_environment(p_render_data->environment)) { RS::EnvironmentBG env_bg = environment_get_background(p_render_data->environment); RS::EnvironmentAmbientSource ambient_src = environment_get_ambient_source(p_render_data->environment); @@ -1423,8 +1642,12 @@ void RasterizerSceneGLES3::_setup_environment(const RenderDataGLES3 *p_render_da } scene_state.ubo.fog_enabled = environment_get_fog_enabled(p_render_data->environment); + scene_state.ubo.fog_mode = environment_get_fog_mode(p_render_data->environment); scene_state.ubo.fog_density = environment_get_fog_density(p_render_data->environment); scene_state.ubo.fog_height = environment_get_fog_height(p_render_data->environment); + scene_state.ubo.fog_depth_curve = environment_get_fog_depth_curve(p_render_data->environment); + scene_state.ubo.fog_depth_end = environment_get_fog_depth_end(p_render_data->environment) > 0.0 ? environment_get_fog_depth_end(p_render_data->environment) : scene_state.ubo.z_far; + scene_state.ubo.fog_depth_begin = MIN(environment_get_fog_depth_begin(p_render_data->environment), scene_state.ubo.fog_depth_end - 0.001); scene_state.ubo.fog_height_density = environment_get_fog_height_density(p_render_data->environment); scene_state.ubo.fog_aerial_perspective = environment_get_fog_aerial_perspective(p_render_data->environment); @@ -1486,7 +1709,7 @@ void RasterizerSceneGLES3::_setup_environment(const RenderDataGLES3 *p_render_da } // Puts lights into Uniform Buffers. Needs to be called before _fill_list as this caches the index of each light in the Uniform Buffer -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) { +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) { GLES3::LightStorage *light_storage = GLES3::LightStorage::get_singleton(); GLES3::Config *config = GLES3::Config::get_singleton(); @@ -1497,6 +1720,7 @@ void RasterizerSceneGLES3::_setup_lights(const RenderDataGLES3 *p_render_data, b r_directional_light_count = 0; r_omni_light_count = 0; r_spot_light_count = 0; + r_directional_shadow_count = 0; int num_lights = lights.size(); @@ -1516,7 +1740,16 @@ void RasterizerSceneGLES3::_setup_lights(const RenderDataGLES3 *p_render_data, b continue; } - DirectionalLightData &light_data = scene_state.directional_lights[r_directional_light_count]; + // If a DirectionalLight has shadows, we will add it to the end of the array and work in. + bool has_shadow = light_storage->light_has_shadow(base); + + int index = r_directional_light_count - r_directional_shadow_count; + + if (has_shadow) { + // Lights with shadow are incremented from the end of the array. + index = MAX_DIRECTIONAL_LIGHTS - 1 - r_directional_shadow_count; + } + DirectionalLightData &light_data = scene_state.directional_lights[index]; Transform3D light_transform = li->transform; @@ -1526,6 +1759,8 @@ void RasterizerSceneGLES3::_setup_lights(const RenderDataGLES3 *p_render_data, b light_data.direction[1] = direction.y; light_data.direction[2] = direction.z; + light_data.bake_mode = light_storage->light_get_bake_mode(base); + float sign = light_storage->light_is_negative(base) ? -1 : 1; light_data.energy = sign * light_storage->light_get_param(base, RS::LIGHT_PARAM_ENERGY); @@ -1550,6 +1785,48 @@ void RasterizerSceneGLES3::_setup_lights(const RenderDataGLES3 *p_render_data, b light_data.specular = light_storage->light_get_param(base, RS::LIGHT_PARAM_SPECULAR); + light_data.shadow_opacity = (p_using_shadows && light_storage->light_has_shadow(base)) + ? light_storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_OPACITY) + : 0.0; + + if (has_shadow) { + DirectionalShadowData &shadow_data = scene_state.directional_shadows[MAX_DIRECTIONAL_LIGHTS - 1 - r_directional_shadow_count]; + + RS::LightDirectionalShadowMode shadow_mode = light_storage->light_directional_get_shadow_mode(base); + + int limit = shadow_mode == RS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL ? 0 : (shadow_mode == RS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS ? 1 : 3); + + shadow_data.shadow_atlas_pixel_size = 1.0 / light_storage->directional_shadow_get_size(); + + shadow_data.blend_splits = uint32_t((shadow_mode != RS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL) && light_storage->light_directional_get_blend_splits(base)); + for (int j = 0; j < 4; j++) { + Rect2 atlas_rect = li->shadow_transform[j].atlas_rect; + Projection matrix = li->shadow_transform[j].camera; + float split = li->shadow_transform[MIN(limit, j)].split; + + Projection bias; + bias.set_light_bias(); + Projection rectm; + rectm.set_light_atlas_rect(atlas_rect); + + Transform3D modelview = (inverse_transform * li->shadow_transform[j].transform).inverse(); + + shadow_data.direction[0] = light_data.direction[0]; + shadow_data.direction[1] = light_data.direction[1]; + shadow_data.direction[2] = light_data.direction[2]; + + Projection shadow_mtx = rectm * bias * matrix * modelview; + shadow_data.shadow_split_offsets[j] = split; + 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; + GLES3::MaterialStorage::store_camera(shadow_mtx, shadow_data.shadow_matrices[j]); + } + float fade_start = light_storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_FADE_START); + shadow_data.fade_from = -shadow_data.shadow_split_offsets[3] * MIN(fade_start, 0.999); + shadow_data.fade_to = -shadow_data.shadow_split_offsets[3]; + + r_directional_shadow_count++; + } + r_directional_light_count++; } break; case RS::LIGHT_OMNI: { @@ -1599,6 +1876,8 @@ void RasterizerSceneGLES3::_setup_lights(const RenderDataGLES3 *p_render_data, b r_spot_light_count++; } break; } + + li->last_pass = RSG::rasterizer->get_frame_number(); } if (r_omni_light_count) { @@ -1611,6 +1890,8 @@ void RasterizerSceneGLES3::_setup_lights(const RenderDataGLES3 *p_render_data, b sorter.sort(scene_state.spot_light_sort, r_spot_light_count); } + int num_positional_shadows = 0; + for (uint32_t i = 0; i < (r_omni_light_count + r_spot_light_count); i++) { uint32_t index = (i < r_omni_light_count) ? i : i - (r_omni_light_count); LightData &light_data = (i < r_omni_light_count) ? scene_state.omni_lights[index] : scene_state.spot_lights[index]; @@ -1628,6 +1909,8 @@ void RasterizerSceneGLES3::_setup_lights(const RenderDataGLES3 *p_render_data, b light_data.position[1] = pos.y; light_data.position[2] = pos.z; + light_data.bake_mode = light_storage->light_get_bake_mode(base); + float radius = MAX(0.001, light_storage->light_get_param(base, RS::LIGHT_PARAM_RANGE)); light_data.inv_radius = 1.0 / radius; @@ -1646,17 +1929,24 @@ void RasterizerSceneGLES3::_setup_lights(const RenderDataGLES3 *p_render_data, b // Reuse fade begin, fade length and distance for shadow LOD determination later. float fade_begin = 0.0; + float fade_shadow = 0.0; float fade_length = 0.0; float fade = 1.0; - if (light_storage->light_is_distance_fade_enabled(li->light)) { - fade_begin = light_storage->light_get_distance_fade_begin(li->light); - fade_length = light_storage->light_get_distance_fade_length(li->light); + float shadow_opacity_fade = 1.0; + + if (light_storage->light_is_distance_fade_enabled(base)) { + fade_begin = light_storage->light_get_distance_fade_begin(base); + fade_shadow = light_storage->light_get_distance_fade_shadow(base); + fade_length = light_storage->light_get_distance_fade_length(base); if (distance > fade_begin) { // Use `smoothstep()` to make opacity changes more gradual and less noticeable to the player. fade = Math::smoothstep(0.0f, 1.0f, 1.0f - float(distance - fade_begin) / fade_length); } + if (distance > fade_shadow) { + shadow_opacity_fade = Math::smoothstep(0.0f, 1.0f, 1.0f - float(distance - fade_shadow) / fade_length); + } } float energy = sign * light_storage->light_get_param(base, RS::LIGHT_PARAM_ENERGY) * fade; @@ -1693,7 +1983,55 @@ void RasterizerSceneGLES3::_setup_lights(const RenderDataGLES3 *p_render_data, b light_data.specular_amount = light_storage->light_get_param(base, RS::LIGHT_PARAM_SPECULAR) * 2.0; - light_data.shadow_opacity = 0.0; + // Setup shadows + const bool needs_shadow = + p_using_shadows && + light_storage->owns_shadow_atlas(p_render_data->shadow_atlas) && + light_storage->shadow_atlas_owns_light_instance(p_render_data->shadow_atlas, li->self) && + light_storage->light_has_shadow(base); + + bool in_shadow_range = true; + if (needs_shadow && light_storage->light_is_distance_fade_enabled(base)) { + if (distance > fade_shadow + fade_length) { + // Out of range, don't draw shadows to improve performance. + in_shadow_range = false; + } + } + + // Fill in the shadow information. + if (needs_shadow && in_shadow_range) { + if (num_positional_shadows >= config->max_renderable_lights) { + continue; + } + ShadowData &shadow_data = scene_state.positional_shadows[num_positional_shadows]; + li->shadow_id = num_positional_shadows; + num_positional_shadows++; + + light_data.shadow_opacity = light_storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_OPACITY) * shadow_opacity_fade; + + float shadow_texel_size = light_storage->light_instance_get_shadow_texel_size(li->self, p_render_data->shadow_atlas); + shadow_data.shadow_atlas_pixel_size = shadow_texel_size; + shadow_data.shadow_normal_bias = light_storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_NORMAL_BIAS) * shadow_texel_size * 10.0; + + shadow_data.light_position[0] = light_data.position[0]; + shadow_data.light_position[1] = light_data.position[1]; + shadow_data.light_position[2] = light_data.position[2]; + + if (type == RS::LIGHT_OMNI) { + Transform3D proj = (inverse_transform * light_transform).inverse(); + + GLES3::MaterialStorage::store_transform(proj, shadow_data.shadow_matrix); + + } else if (type == RS::LIGHT_SPOT) { + Transform3D modelview = (inverse_transform * light_transform).inverse(); + Projection bias; + bias.set_light_bias(); + + Projection cm = li->shadow_transform[0].camera; + Projection shadow_mtx = bias * cm * modelview; + GLES3::MaterialStorage::store_camera(shadow_mtx, shadow_data.shadow_matrix); + } + } } // TODO, to avoid stalls, should rotate between 3 buffers based on frame index. @@ -1710,9 +2048,266 @@ void RasterizerSceneGLES3::_setup_lights(const RenderDataGLES3 *p_render_data, b glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_DIRECTIONAL_LIGHT_UNIFORM_LOCATION, scene_state.directional_light_buffer); if (r_directional_light_count) { - glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(DirectionalLightData) * r_directional_light_count, scene_state.directional_lights); + glBufferData(GL_UNIFORM_BUFFER, sizeof(DirectionalLightData) * MAX_DIRECTIONAL_LIGHTS, scene_state.directional_lights, GL_STREAM_DRAW); + } + + glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_POSITIONAL_SHADOW_UNIFORM_LOCATION, scene_state.positional_shadow_buffer); + if (num_positional_shadows) { + glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(ShadowData) * num_positional_shadows, scene_state.positional_shadows); + } + + glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_DIRECTIONAL_SHADOW_UNIFORM_LOCATION, scene_state.directional_shadow_buffer); + if (r_directional_shadow_count) { + glBufferData(GL_UNIFORM_BUFFER, sizeof(DirectionalShadowData) * MAX_DIRECTIONAL_LIGHTS, scene_state.directional_shadows, GL_STREAM_DRAW); + } + glBindBuffer(GL_UNIFORM_BUFFER, 0); +} + +// Render shadows +void RasterizerSceneGLES3::_render_shadows(const RenderDataGLES3 *p_render_data, const Size2i &p_viewport_size) { + GLES3::LightStorage *light_storage = GLES3::LightStorage::get_singleton(); + + LocalVector<int> cube_shadows; + LocalVector<int> shadows; + LocalVector<int> directional_shadows; + + Plane camera_plane(-p_render_data->cam_transform.basis.get_column(Vector3::AXIS_Z), p_render_data->cam_transform.origin); + float lod_distance_multiplier = p_render_data->cam_projection.get_lod_multiplier(); + + // Put lights into buckets for omni (cube shadows), directional, and spot. + { + for (int i = 0; i < p_render_data->render_shadow_count; i++) { + RID li = p_render_data->render_shadows[i].light; + RID base = light_storage->light_instance_get_base_light(li); + + if (light_storage->light_get_type(base) == RS::LIGHT_DIRECTIONAL) { + directional_shadows.push_back(i); + } else if (light_storage->light_get_type(base) == RS::LIGHT_OMNI && light_storage->light_omni_get_shadow_mode(base) == RS::LIGHT_OMNI_SHADOW_CUBE) { + cube_shadows.push_back(i); + } else { + shadows.push_back(i); + } + } + if (directional_shadows.size()) { + light_storage->update_directional_shadow_atlas(); + } + } + + bool render_shadows = directional_shadows.size() || shadows.size() || cube_shadows.size(); + + if (render_shadows) { + RENDER_TIMESTAMP("Render Shadows"); + + // Render cubemap shadows. + for (const int &index : cube_shadows) { + _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, p_render_data->cam_transform); + } + // Render directional shadows. + for (uint32_t i = 0; i < directional_shadows.size(); i++) { + _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, p_render_data->cam_transform); + } + // Render positional shadows (Spotlight and Omnilight with dual-paraboloid). + for (uint32_t i = 0; i < shadows.size(); i++) { + _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, p_render_data->cam_transform); + } + } +} + +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, const Transform3D &p_main_cam_transform) { + GLES3::LightStorage *light_storage = GLES3::LightStorage::get_singleton(); + + ERR_FAIL_COND(!light_storage->owns_light_instance(p_light)); + + RID base = light_storage->light_instance_get_base_light(p_light); + + float zfar = 0.0; + bool use_pancake = false; + float shadow_bias = 0.0; + bool reverse_cull = false; + bool needs_clear = false; + + Projection light_projection; + Transform3D light_transform; + GLuint shadow_fb = 0; + Rect2i atlas_rect; + + if (light_storage->light_get_type(base) == RS::LIGHT_DIRECTIONAL) { + // Set pssm stuff. + uint64_t last_scene_shadow_pass = light_storage->light_instance_get_shadow_pass(p_light); + if (last_scene_shadow_pass != get_scene_pass()) { + light_storage->light_instance_set_directional_rect(p_light, light_storage->get_directional_shadow_rect()); + light_storage->directional_shadow_increase_current_light(); + light_storage->light_instance_set_shadow_pass(p_light, get_scene_pass()); + } + + atlas_rect = light_storage->light_instance_get_directional_rect(p_light); + + if (light_storage->light_directional_get_shadow_mode(base) == RS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS) { + atlas_rect.size.width /= 2; + atlas_rect.size.height /= 2; + + if (p_pass == 1) { + atlas_rect.position.x += atlas_rect.size.width; + } else if (p_pass == 2) { + atlas_rect.position.y += atlas_rect.size.height; + } else if (p_pass == 3) { + atlas_rect.position += atlas_rect.size; + } + } else if (light_storage->light_directional_get_shadow_mode(base) == RS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS) { + atlas_rect.size.height /= 2; + + if (p_pass == 0) { + } else { + atlas_rect.position.y += atlas_rect.size.height; + } + } + + use_pancake = light_storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_PANCAKE_SIZE) > 0; + light_projection = light_storage->light_instance_get_shadow_camera(p_light, p_pass); + light_transform = light_storage->light_instance_get_shadow_transform(p_light, p_pass); + + float directional_shadow_size = light_storage->directional_shadow_get_size(); + Rect2 atlas_rect_norm = atlas_rect; + atlas_rect_norm.position /= directional_shadow_size; + atlas_rect_norm.size /= directional_shadow_size; + light_storage->light_instance_set_directional_shadow_atlas_rect(p_light, p_pass, atlas_rect_norm); + + zfar = RSG::light_storage->light_get_param(base, RS::LIGHT_PARAM_RANGE); + shadow_fb = light_storage->direction_shadow_get_fb(); + reverse_cull = !light_storage->light_get_reverse_cull_face_mode(base); + + float bias_scale = light_storage->light_instance_get_shadow_bias_scale(p_light, p_pass); + shadow_bias = light_storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_BIAS) / 100.0 * bias_scale; + + } else { + // Set from shadow atlas. + + ERR_FAIL_COND(!light_storage->owns_shadow_atlas(p_shadow_atlas)); + ERR_FAIL_COND(!light_storage->shadow_atlas_owns_light_instance(p_shadow_atlas, p_light)); + + uint32_t key = light_storage->shadow_atlas_get_light_instance_key(p_shadow_atlas, p_light); + + uint32_t quadrant = (key >> GLES3::LightStorage::QUADRANT_SHIFT) & 0x3; + uint32_t shadow = key & GLES3::LightStorage::SHADOW_INDEX_MASK; + + ERR_FAIL_INDEX((int)shadow, light_storage->shadow_atlas_get_quadrant_shadows_length(p_shadow_atlas, quadrant)); + + int shadow_size = light_storage->shadow_atlas_get_quadrant_shadow_size(p_shadow_atlas, quadrant); + + shadow_fb = light_storage->shadow_atlas_get_quadrant_shadow_fb(p_shadow_atlas, quadrant, shadow); + + zfar = light_storage->light_get_param(base, RS::LIGHT_PARAM_RANGE); + reverse_cull = !light_storage->light_get_reverse_cull_face_mode(base); + + if (light_storage->light_get_type(base) == RS::LIGHT_OMNI) { + if (light_storage->light_omni_get_shadow_mode(base) == RS::LIGHT_OMNI_SHADOW_CUBE) { + GLuint shadow_texture = light_storage->shadow_atlas_get_quadrant_shadow_texture(p_shadow_atlas, quadrant, shadow); + glBindFramebuffer(GL_FRAMEBUFFER, shadow_fb); + + static GLenum cube_map_faces[6] = { + GL_TEXTURE_CUBE_MAP_POSITIVE_X, + GL_TEXTURE_CUBE_MAP_NEGATIVE_X, + // Flipped order for Y to match what the RD renderer expects + // (and thus what is given to us by the Rendering Server). + GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, + GL_TEXTURE_CUBE_MAP_POSITIVE_Y, + GL_TEXTURE_CUBE_MAP_POSITIVE_Z, + GL_TEXTURE_CUBE_MAP_NEGATIVE_Z + }; + + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, cube_map_faces[p_pass], shadow_texture, 0); + + light_projection = light_storage->light_instance_get_shadow_camera(p_light, p_pass); + light_transform = light_storage->light_instance_get_shadow_transform(p_light, p_pass); + shadow_size = shadow_size / 2; + } else { + ERR_FAIL_MSG("Dual paraboloid shadow mode not supported in GL Compatibility renderer. Please use Cubemap shadow mode instead."); + } + + shadow_bias = light_storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_BIAS); + + } else if (light_storage->light_get_type(base) == RS::LIGHT_SPOT) { + light_projection = light_storage->light_instance_get_shadow_camera(p_light, 0); + light_transform = light_storage->light_instance_get_shadow_transform(p_light, 0); + + shadow_bias = light_storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_BIAS) / 10.0; + // Prebake range into bias so we can scale based on distance easily. + shadow_bias *= light_storage->light_get_param(base, RS::LIGHT_PARAM_RANGE); + } + atlas_rect.size.x = shadow_size; + atlas_rect.size.y = shadow_size; + + needs_clear = true; + } + + RenderDataGLES3 render_data; + render_data.cam_projection = light_projection; + render_data.cam_transform = light_transform; + render_data.inv_cam_transform = light_transform.affine_inverse(); + render_data.z_far = zfar; // Only used by OmniLights. + render_data.z_near = 0.0; + render_data.lod_distance_multiplier = p_lod_distance_multiplier; + render_data.main_cam_transform = p_main_cam_transform; + + render_data.instances = &p_instances; + render_data.render_info = p_render_info; + + _setup_environment(&render_data, true, p_viewport_size, false, Color(), use_pancake, shadow_bias); + + if (get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_DISABLE_LOD) { + render_data.screen_mesh_lod_threshold = 0.0; + } else { + render_data.screen_mesh_lod_threshold = p_screen_mesh_lod_threshold; } + + _fill_render_list(RENDER_LIST_SECONDARY, &render_data, PASS_MODE_SHADOW); + render_list[RENDER_LIST_SECONDARY].sort_by_key(); + + glBindFramebuffer(GL_FRAMEBUFFER, shadow_fb); + glViewport(atlas_rect.position.x, atlas_rect.position.y, atlas_rect.size.x, atlas_rect.size.y); + + GLuint global_buffer = GLES3::MaterialStorage::get_singleton()->global_shader_parameters_get_uniform_buffer(); + + glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_GLOBALS_UNIFORM_LOCATION, global_buffer); glBindBuffer(GL_UNIFORM_BUFFER, 0); + + glDisable(GL_BLEND); + glDepthMask(GL_TRUE); + glEnable(GL_DEPTH_TEST); + glDepthFunc(GL_LESS); + glDisable(GL_SCISSOR_TEST); + glCullFace(GL_BACK); + glEnable(GL_CULL_FACE); + scene_state.cull_mode = GLES3::SceneShaderData::CULL_BACK; + + glColorMask(0, 0, 0, 0); + glDrawBuffers(0, nullptr); + RasterizerGLES3::clear_depth(1.0); + if (needs_clear) { + glClear(GL_DEPTH_BUFFER_BIT); + } + + uint64_t spec_constant_base_flags = SceneShaderGLES3::DISABLE_LIGHTMAP | + SceneShaderGLES3::DISABLE_LIGHT_DIRECTIONAL | + SceneShaderGLES3::DISABLE_LIGHT_OMNI | + SceneShaderGLES3::DISABLE_LIGHT_SPOT | + SceneShaderGLES3::DISABLE_FOG | + SceneShaderGLES3::RENDER_SHADOWS; + + if (light_storage->light_get_type(base) == RS::LIGHT_OMNI) { + spec_constant_base_flags |= SceneShaderGLES3::RENDER_SHADOWS_LINEAR; + } + + 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); + + _render_list_template<PASS_MODE_SHADOW>(&render_list_params, &render_data, 0, render_list[RENDER_LIST_SECONDARY].elements.size()); + + glColorMask(1, 1, 1, 1); + glDisable(GL_DEPTH_TEST); + glDepthMask(GL_FALSE); + glDisable(GL_CULL_FACE); + scene_state.cull_mode = GLES3::SceneShaderData::CULL_DISABLED; + glBindFramebuffer(GL_FRAMEBUFFER, 0); } 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) { @@ -1727,20 +2322,21 @@ void RasterizerSceneGLES3::render_scene(const Ref<RenderSceneBuffers> &p_render_ } GLES3::RenderTarget *rt = texture_storage->get_render_target(rb->render_target); - ERR_FAIL_COND(!rt); + ERR_FAIL_NULL(rt); // Assign render data // Use the format from rendererRD RenderDataGLES3 render_data; { render_data.render_buffers = rb; - render_data.transparent_bg = rb.is_valid() ? rb->is_transparent : false; + render_data.transparent_bg = rb.is_valid() ? rt->is_transparent : false; // Our first camera is used by default render_data.cam_transform = p_camera_data->main_transform; render_data.inv_cam_transform = render_data.cam_transform.affine_inverse(); render_data.cam_projection = p_camera_data->main_projection; render_data.cam_orthogonal = p_camera_data->is_orthogonal; render_data.camera_visible_layers = p_camera_data->visible_layers; + render_data.main_cam_transform = p_camera_data->main_transform; render_data.view_count = p_camera_data->view_count; for (uint32_t v = 0; v < p_camera_data->view_count; v++) { @@ -1756,6 +2352,7 @@ void RasterizerSceneGLES3::render_scene(const Ref<RenderSceneBuffers> &p_render_ render_data.reflection_probes = &p_reflection_probes; render_data.environment = p_environment; render_data.camera_attributes = p_camera_attributes; + render_data.shadow_atlas = p_shadow_atlas; render_data.reflection_probe = p_reflection_probe; render_data.reflection_probe_pass = p_reflection_probe_pass; @@ -1768,6 +2365,8 @@ void RasterizerSceneGLES3::render_scene(const Ref<RenderSceneBuffers> &p_render_ render_data.screen_mesh_lod_threshold = p_screen_mesh_lod_threshold; } render_data.render_info = r_render_info; + render_data.render_shadows = p_render_shadows; + render_data.render_shadow_count = p_render_shadow_count; } PagedArray<RID> empty; @@ -1795,9 +2394,7 @@ void RasterizerSceneGLES3::render_scene(const Ref<RenderSceneBuffers> &p_render_ bool fb_cleared = false; - Size2i screen_size; - screen_size.x = rb->width; - screen_size.y = rb->height; + Size2i screen_size = rb->internal_size; bool use_wireframe = get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_WIREFRAME; @@ -1833,8 +2430,9 @@ void RasterizerSceneGLES3::render_scene(const Ref<RenderSceneBuffers> &p_render_ // If we're rendering right-side up, then we need to change the winding order. glFrontFace(GL_CW); } + _render_shadows(&render_data, screen_size); - _setup_lights(&render_data, false, render_data.directional_light_count, render_data.omni_light_count, render_data.spot_light_count); + _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); _setup_environment(&render_data, render_data.reflection_probe.is_valid(), screen_size, flip_y, clear_color, false); _fill_render_list(RENDER_LIST_OPAQUE, &render_data, PASS_MODE_COLOR); @@ -1846,7 +2444,7 @@ void RasterizerSceneGLES3::render_scene(const Ref<RenderSceneBuffers> &p_render_ bool keep_color = false; float sky_energy_multiplier = 1.0; - if (get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_OVERDRAW) { + if (unlikely(get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_OVERDRAW)) { clear_color = Color(0, 0, 0, 1); //in overdraw mode, BG should always be black } else if (render_data.environment.is_valid()) { RS::EnvironmentBG bg_mode = environment_get_background(render_data.environment); @@ -1916,8 +2514,10 @@ void RasterizerSceneGLES3::render_scene(const Ref<RenderSceneBuffers> &p_render_ } } - glBindFramebuffer(GL_FRAMEBUFFER, rt->fbo); - glViewport(0, 0, rb->width, rb->height); + GLuint fbo = rb->get_render_fbo(); + + glBindFramebuffer(GL_FRAMEBUFFER, fbo); + glViewport(0, 0, rb->internal_size.x, rb->internal_size.y); glCullFace(GL_BACK); glEnable(GL_CULL_FACE); @@ -1940,8 +2540,10 @@ void RasterizerSceneGLES3::render_scene(const Ref<RenderSceneBuffers> &p_render_ glDisable(GL_SCISSOR_TEST); glColorMask(0, 0, 0, 0); - glClearDepth(1.0f); + RasterizerGLES3::clear_depth(1.0); glClear(GL_DEPTH_BUFFER_BIT); + glDrawBuffers(0, nullptr); + uint64_t spec_constant = SceneShaderGLES3::DISABLE_FOG | SceneShaderGLES3::DISABLE_LIGHT_DIRECTIONAL | SceneShaderGLES3::DISABLE_LIGHTMAP | SceneShaderGLES3::DISABLE_LIGHT_OMNI | SceneShaderGLES3::DISABLE_LIGHT_SPOT; @@ -1974,12 +2576,18 @@ void RasterizerSceneGLES3::render_scene(const Ref<RenderSceneBuffers> &p_render_ scene_state.current_depth_test = GLES3::SceneShaderData::DEPTH_TEST_ENABLED; scene_state.current_depth_draw = GLES3::SceneShaderData::DEPTH_DRAW_ALWAYS; + { + GLuint db = GL_COLOR_ATTACHMENT0; + glDrawBuffers(1, &db); + } + if (!fb_cleared) { - glClearDepth(1.0f); + RasterizerGLES3::clear_depth(1.0); glClear(GL_DEPTH_BUFFER_BIT); } if (!keep_color) { + clear_color.a = render_data.transparent_bg ? 0.0f : 1.0f; glClearBufferfv(GL_COLOR, 0, clear_color.components); } RENDER_TIMESTAMP("Render Opaque Pass"); @@ -1994,6 +2602,10 @@ void RasterizerSceneGLES3::render_scene(const Ref<RenderSceneBuffers> &p_render_ if (render_data.environment.is_null() || (render_data.environment.is_valid() && !environment_get_fog_enabled(render_data.environment))) { spec_constant_base_flags |= SceneShaderGLES3::DISABLE_FOG; } + + if (render_data.environment.is_valid() && environment_get_fog_mode(render_data.environment) == RS::EnvironmentFogMode::ENV_FOG_MODE_DEPTH) { + spec_constant_base_flags |= SceneShaderGLES3::USE_DEPTH_FOG; + } } // Render Opaque Objects. 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); @@ -2017,25 +2629,48 @@ void RasterizerSceneGLES3::render_scene(const Ref<RenderSceneBuffers> &p_render_ } if (scene_state.used_screen_texture || scene_state.used_depth_texture) { - texture_storage->copy_scene_to_backbuffer(rt, scene_state.used_screen_texture, scene_state.used_depth_texture); - glBindFramebuffer(GL_READ_FRAMEBUFFER, rt->fbo); - glReadBuffer(GL_COLOR_ATTACHMENT0); - glBindFramebuffer(GL_DRAW_FRAMEBUFFER, rt->backbuffer_fbo); - if (scene_state.used_screen_texture) { - glBlitFramebuffer(0, 0, rt->size.x, rt->size.y, - 0, 0, rt->size.x, rt->size.y, - GL_COLOR_BUFFER_BIT, GL_NEAREST); - glActiveTexture(GL_TEXTURE0 + config->max_texture_image_units - 5); - glBindTexture(GL_TEXTURE_2D, rt->backbuffer); - } - if (scene_state.used_depth_texture) { - glBlitFramebuffer(0, 0, rt->size.x, rt->size.y, - 0, 0, rt->size.x, rt->size.y, - GL_DEPTH_BUFFER_BIT, GL_NEAREST); - glActiveTexture(GL_TEXTURE0 + config->max_texture_image_units - 6); - glBindTexture(GL_TEXTURE_2D, rt->backbuffer_depth); - } - glBindFramebuffer(GL_FRAMEBUFFER, rt->fbo); + Size2i size; + GLuint backbuffer_fbo = 0; + GLuint backbuffer = 0; + GLuint backbuffer_depth = 0; + + if (rb->get_scaling_3d_mode() == RS::VIEWPORT_SCALING_3D_MODE_OFF) { + texture_storage->check_backbuffer(rt, scene_state.used_screen_texture, scene_state.used_depth_texture); // note, badly names, this just allocates! + + size = rt->size; + backbuffer_fbo = rt->backbuffer_fbo; + backbuffer = rt->backbuffer; + backbuffer_depth = rt->backbuffer_depth; + } else { + rb->check_backbuffer(scene_state.used_screen_texture, scene_state.used_depth_texture); + size = rb->get_internal_size(); + backbuffer_fbo = rb->get_backbuffer_fbo(); + backbuffer = rb->get_backbuffer(); + backbuffer_depth = rb->get_backbuffer_depth(); + } + + if (backbuffer_fbo != 0) { + glBindFramebuffer(GL_READ_FRAMEBUFFER, fbo); + glReadBuffer(GL_COLOR_ATTACHMENT0); + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, backbuffer_fbo); + if (scene_state.used_screen_texture) { + glBlitFramebuffer(0, 0, size.x, size.y, + 0, 0, size.x, size.y, + GL_COLOR_BUFFER_BIT, GL_NEAREST); + glActiveTexture(GL_TEXTURE0 + config->max_texture_image_units - 5); + glBindTexture(GL_TEXTURE_2D, backbuffer); + } + if (scene_state.used_depth_texture) { + glBlitFramebuffer(0, 0, size.x, size.y, + 0, 0, size.x, size.y, + GL_DEPTH_BUFFER_BIT, GL_NEAREST); + glActiveTexture(GL_TEXTURE0 + config->max_texture_image_units - 6); + glBindTexture(GL_TEXTURE_2D, backbuffer_depth); + } + } + + // Bound framebuffer may have changed, so change it back + glBindFramebuffer(GL_FRAMEBUFFER, fbo); } RENDER_TIMESTAMP("Render 3D Transparent Pass"); @@ -2052,10 +2687,108 @@ void RasterizerSceneGLES3::render_scene(const Ref<RenderSceneBuffers> &p_render_ } if (rb.is_valid()) { - _render_buffers_debug_draw(rb, p_shadow_atlas, p_occluder_debug_tex); + _render_buffers_debug_draw(rb, p_shadow_atlas, fbo); } glDisable(GL_BLEND); + + _render_post_processing(&render_data); + texture_storage->render_target_disable_clear_request(rb->render_target); + + glActiveTexture(GL_TEXTURE0); +} + +void RasterizerSceneGLES3::_render_post_processing(const RenderDataGLES3 *p_render_data) { + GLES3::TextureStorage *texture_storage = GLES3::TextureStorage::get_singleton(); + Ref<RenderSceneBuffersGLES3> rb = p_render_data->render_buffers; + ERR_FAIL_COND(rb.is_null()); + + RID render_target = rb->get_render_target(); + Size2i internal_size = rb->get_internal_size(); + Size2i target_size = rb->get_target_size(); + uint32_t view_count = rb->get_view_count(); + + // bool msaa2d_needs_resolve = texture_storage->render_target_get_msaa(render_target) != RS::VIEWPORT_MSAA_DISABLED && !GLES3::Config::get_singleton()->rt_msaa_supported; + bool msaa3d_needs_resolve = rb->get_msaa_needs_resolve(); + GLuint fbo_msaa_3d = rb->get_msaa3d_fbo(); + GLuint fbo_int = rb->get_internal_fbo(); + GLuint fbo_rt = texture_storage->render_target_get_fbo(render_target); // TODO if MSAA 2D is enabled and we're not using rt_msaa, get 2D render target here. + + if (view_count == 1) { + // Resolve if needed. + if (fbo_msaa_3d != 0 && msaa3d_needs_resolve) { + // We can use blit to copy things over + glBindFramebuffer(GL_READ_FRAMEBUFFER, fbo_msaa_3d); + + if (fbo_int != 0) { + // We can't combine resolve and scaling, so resolve into our internal buffer + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo_int); + } else { + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo_rt); + } + glBlitFramebuffer(0, 0, internal_size.x, internal_size.y, 0, 0, internal_size.x, internal_size.y, GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, GL_NEAREST); + } + + if (fbo_int != 0) { + // TODO If we have glow or other post processing, we upscale only depth here, post processing will also do scaling. + glBindFramebuffer(GL_READ_FRAMEBUFFER, fbo_int); + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo_rt); + glBlitFramebuffer(0, 0, internal_size.x, internal_size.y, 0, 0, target_size.x, target_size.y, GL_COLOR_BUFFER_BIT, GL_LINEAR); + glBlitFramebuffer(0, 0, internal_size.x, internal_size.y, 0, 0, target_size.x, target_size.y, GL_DEPTH_BUFFER_BIT, GL_NEAREST); + } + + glBindFramebuffer(GL_FRAMEBUFFER, fbo_rt); + } else if ((fbo_msaa_3d != 0 && msaa3d_needs_resolve) || (fbo_int != 0)) { + // TODO investigate if it's smarter to cache these FBOs + GLuint fbos[2]; // read and write + glGenFramebuffers(2, fbos); + + glBindFramebuffer(GL_READ_FRAMEBUFFER, fbos[0]); + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbos[1]); + + if (fbo_msaa_3d != 0 && msaa3d_needs_resolve) { + GLuint read_color = rb->get_msaa3d_color(); + GLuint read_depth = rb->get_msaa3d_depth(); + GLuint write_color = 0; + GLuint write_depth = 0; + + if (fbo_int != 0) { + write_color = rb->get_internal_color(); + write_depth = rb->get_internal_depth(); + } else { + write_color = texture_storage->render_target_get_color(render_target); + write_depth = texture_storage->render_target_get_depth(render_target); + } + + for (uint32_t v = 0; v < view_count; v++) { + glFramebufferTextureLayer(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, read_color, 0, v); + glFramebufferTextureLayer(GL_READ_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, read_depth, 0, v); + glFramebufferTextureLayer(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, write_color, 0, v); + glFramebufferTextureLayer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, write_depth, 0, v); + glBlitFramebuffer(0, 0, internal_size.x, internal_size.y, 0, 0, internal_size.x, internal_size.y, GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, GL_NEAREST); + } + } + + if (fbo_int != 0) { + GLuint read_color = rb->get_internal_color(); + GLuint read_depth = rb->get_internal_depth(); + GLuint write_color = texture_storage->render_target_get_color(render_target); + GLuint write_depth = texture_storage->render_target_get_depth(render_target); + + for (uint32_t v = 0; v < view_count; v++) { + glFramebufferTextureLayer(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, read_color, 0, v); + glFramebufferTextureLayer(GL_READ_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, read_depth, 0, v); + glFramebufferTextureLayer(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, write_color, 0, v); + glFramebufferTextureLayer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, write_depth, 0, v); + + glBlitFramebuffer(0, 0, internal_size.x, internal_size.y, 0, 0, target_size.x, target_size.y, GL_COLOR_BUFFER_BIT, GL_LINEAR); + glBlitFramebuffer(0, 0, internal_size.x, internal_size.y, 0, 0, target_size.x, target_size.y, GL_DEPTH_BUFFER_BIT, GL_NEAREST); + } + } + + glBindFramebuffer(GL_FRAMEBUFFER, fbo_rt); + glDeleteFramebuffers(2, fbos); + } } template <PassMode p_pass_mode> @@ -2077,23 +2810,6 @@ void RasterizerSceneGLES3::_render_list_template(RenderListParameters *p_params, // Specializations constants used by all instances in the scene. uint64_t base_spec_constants = p_params->spec_constant_base_flags; - if (p_render_data->view_count > 1) { - base_spec_constants |= SceneShaderGLES3::USE_MULTIVIEW; - } - - switch (p_pass_mode) { - case PASS_MODE_COLOR: - case PASS_MODE_COLOR_TRANSPARENT: { - } break; - case PASS_MODE_COLOR_ADDITIVE: { - shader_variant = SceneShaderGLES3::MODE_ADDITIVE; - } break; - case PASS_MODE_SHADOW: - case PASS_MODE_DEPTH: { - shader_variant = SceneShaderGLES3::MODE_DEPTH; - } break; - } - if constexpr (p_pass_mode == PASS_MODE_COLOR || p_pass_mode == PASS_MODE_COLOR_TRANSPARENT) { GLES3::TextureStorage *texture_storage = GLES3::TextureStorage::get_singleton(); GLES3::Config *config = GLES3::Config::get_singleton(); @@ -2107,6 +2823,13 @@ void RasterizerSceneGLES3::_render_list_template(RenderListParameters *p_params, } glBindTexture(GL_TEXTURE_CUBE_MAP, texture_to_bind); } + + } else if constexpr (p_pass_mode == PASS_MODE_DEPTH || p_pass_mode == PASS_MODE_SHADOW) { + shader_variant = SceneShaderGLES3::MODE_DEPTH; + } + + if (p_render_data->view_count > 1) { + base_spec_constants |= SceneShaderGLES3::USE_MULTIVIEW; } bool should_request_redraw = false; @@ -2118,7 +2841,7 @@ void RasterizerSceneGLES3::_render_list_template(RenderListParameters *p_params, } for (uint32_t i = p_from_element; i < p_to_element; i++) { - const GeometryInstanceSurface *surf = p_params->elements[i]; + GeometryInstanceSurface *surf = p_params->elements[i]; GeometryInstanceGLES3 *inst = surf->owner; if (p_pass_mode == PASS_MODE_COLOR && !(surf->flags & GeometryInstanceSurface::FLAG_PASS_OPAQUE)) { @@ -2138,8 +2861,16 @@ void RasterizerSceneGLES3::_render_list_template(RenderListParameters *p_params, material_data = surf->material_shadow; mesh_surface = surf->surface_shadow; } else { - shader = surf->shader; - material_data = surf->material; + if (unlikely(get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_OVERDRAW)) { + material_data = overdraw_material_data_ptr; + shader = material_data->shader_data; + } else if (unlikely(get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_LIGHTING)) { + material_data = default_material_data_ptr; + shader = material_data->shader_data; + } else { + shader = surf->shader; + material_data = surf->material; + } mesh_surface = surf->surface; } @@ -2163,271 +2894,531 @@ void RasterizerSceneGLES3::_render_list_template(RenderListParameters *p_params, } } - if (scene_state.current_depth_draw != shader->depth_draw) { - switch (shader->depth_draw) { - case GLES3::SceneShaderData::DEPTH_DRAW_OPAQUE: { - glDepthMask(p_pass_mode == PASS_MODE_COLOR); - } break; - case GLES3::SceneShaderData::DEPTH_DRAW_ALWAYS: { - glDepthMask(GL_TRUE); - } break; - case GLES3::SceneShaderData::DEPTH_DRAW_DISABLED: { - glDepthMask(GL_FALSE); - } break; + if constexpr (p_pass_mode != PASS_MODE_SHADOW) { + if (scene_state.current_depth_draw != shader->depth_draw) { + switch (shader->depth_draw) { + case GLES3::SceneShaderData::DEPTH_DRAW_OPAQUE: { + glDepthMask((p_pass_mode == PASS_MODE_COLOR && !GLES3::Config::get_singleton()->use_depth_prepass) || + p_pass_mode == PASS_MODE_DEPTH); + } break; + case GLES3::SceneShaderData::DEPTH_DRAW_ALWAYS: { + glDepthMask(GL_TRUE); + } break; + case GLES3::SceneShaderData::DEPTH_DRAW_DISABLED: { + glDepthMask(GL_FALSE); + } break; + } } scene_state.current_depth_draw = shader->depth_draw; } - if constexpr (p_pass_mode == PASS_MODE_COLOR_TRANSPARENT || p_pass_mode == PASS_MODE_COLOR_ADDITIVE) { - GLES3::SceneShaderData::BlendMode desired_blend_mode; - if constexpr (p_pass_mode == PASS_MODE_COLOR_ADDITIVE) { - desired_blend_mode = GLES3::SceneShaderData::BLEND_MODE_ADD; - } else { - desired_blend_mode = shader->blend_mode; + bool uses_additive_lighting = (inst->light_passes.size() + p_render_data->directional_shadow_count) > 0; + uses_additive_lighting = uses_additive_lighting && !shader->unshaded; + + // TODOS + /* + * 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 + * Disable depth draw + */ + + for (int32_t pass = 0; pass < MAX(1, int32_t(inst->light_passes.size() + p_render_data->directional_shadow_count)); pass++) { + if constexpr (p_pass_mode == PASS_MODE_DEPTH || p_pass_mode == PASS_MODE_SHADOW) { + if (pass > 0) { + // Don't render shadow passes when doing depth or shadow pass. + break; + } } - if (desired_blend_mode != scene_state.current_blend_mode) { - switch (desired_blend_mode) { - case GLES3::SceneShaderData::BLEND_MODE_MIX: { - glBlendEquation(GL_FUNC_ADD); - if (p_render_data->transparent_bg) { - glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); - } else { - glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ZERO, GL_ONE); - } + if constexpr (p_pass_mode == PASS_MODE_COLOR || p_pass_mode == PASS_MODE_COLOR_TRANSPARENT) { + if (!uses_additive_lighting && pass == 1) { + // Don't render additive passes if not using additive lighting. + break; + } + if (uses_additive_lighting && pass == 1 && !p_render_data->transparent_bg) { + // Enable blending if in opaque pass and not already enabled. + glEnable(GL_BLEND); + } + if (pass < int32_t(inst->light_passes.size())) { + RID light_instance_rid = inst->light_passes[pass].light_instance_rid; + if (!GLES3::LightStorage::get_singleton()->light_instance_has_shadow_atlas(light_instance_rid, p_render_data->shadow_atlas)) { + // Shadow wasn't able to get a spot on the atlas. So skip it. + continue; + } + } else if (pass > 0) { + uint32_t shadow_id = MAX_DIRECTIONAL_LIGHTS - 1 - (pass - int32_t(inst->light_passes.size())); + if (inst->lightmap_instance.is_valid() && scene_state.directional_lights[shadow_id].bake_mode == RenderingServer::LIGHT_BAKE_STATIC) { + // Skip shadows for static lights on meshes with a lightmap. + continue; + } + } + } - } break; - case GLES3::SceneShaderData::BLEND_MODE_ADD: { - glBlendEquation(GL_FUNC_ADD); - glBlendFunc(p_pass_mode == PASS_MODE_COLOR_TRANSPARENT ? GL_SRC_ALPHA : GL_ONE, GL_ONE); + if constexpr (p_pass_mode == PASS_MODE_COLOR || p_pass_mode == PASS_MODE_COLOR_TRANSPARENT) { + GLES3::SceneShaderData::BlendMode desired_blend_mode; + if (pass > 0) { + desired_blend_mode = GLES3::SceneShaderData::BLEND_MODE_ADD; + } else { + desired_blend_mode = shader->blend_mode; + } - } break; - case GLES3::SceneShaderData::BLEND_MODE_SUB: { - glBlendEquation(GL_FUNC_REVERSE_SUBTRACT); - glBlendFunc(GL_SRC_ALPHA, GL_ONE); + if (desired_blend_mode != scene_state.current_blend_mode) { + switch (desired_blend_mode) { + case GLES3::SceneShaderData::BLEND_MODE_MIX: { + glBlendEquation(GL_FUNC_ADD); + if (p_render_data->transparent_bg) { + glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); + } else { + glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ZERO, GL_ONE); + } + + } break; + case GLES3::SceneShaderData::BLEND_MODE_ADD: { + glBlendEquation(GL_FUNC_ADD); + glBlendFunc(p_pass_mode == PASS_MODE_COLOR_TRANSPARENT ? GL_SRC_ALPHA : GL_ONE, GL_ONE); + + } break; + case GLES3::SceneShaderData::BLEND_MODE_SUB: { + glBlendEquation(GL_FUNC_REVERSE_SUBTRACT); + glBlendFunc(GL_SRC_ALPHA, GL_ONE); + + } break; + case GLES3::SceneShaderData::BLEND_MODE_MUL: { + glBlendEquation(GL_FUNC_ADD); + if (p_render_data->transparent_bg) { + glBlendFuncSeparate(GL_DST_COLOR, GL_ZERO, GL_DST_ALPHA, GL_ZERO); + } else { + glBlendFuncSeparate(GL_DST_COLOR, GL_ZERO, GL_ZERO, GL_ONE); + } + + } break; + case GLES3::SceneShaderData::BLEND_MODE_ALPHA_TO_COVERAGE: { + // Do nothing for now. + } break; + } + scene_state.current_blend_mode = desired_blend_mode; + } + } - } break; - case GLES3::SceneShaderData::BLEND_MODE_MUL: { - glBlendEquation(GL_FUNC_ADD); - if (p_render_data->transparent_bg) { - glBlendFuncSeparate(GL_DST_COLOR, GL_ZERO, GL_DST_ALPHA, GL_ZERO); - } else { - glBlendFuncSeparate(GL_DST_COLOR, GL_ZERO, GL_ZERO, GL_ONE); - } + // Find cull variant. + GLES3::SceneShaderData::Cull cull_mode = shader->cull_mode; - } break; - case GLES3::SceneShaderData::BLEND_MODE_ALPHA_TO_COVERAGE: { - // Do nothing for now. - } break; + if (p_pass_mode == PASS_MODE_MATERIAL || (surf->flags & GeometryInstanceSurface::FLAG_USES_DOUBLE_SIDED_SHADOWS)) { + cull_mode = GLES3::SceneShaderData::CULL_DISABLED; + } else { + bool mirror = inst->mirror; + if (p_params->reverse_cull) { + mirror = !mirror; + } + if (cull_mode == GLES3::SceneShaderData::CULL_FRONT && mirror) { + cull_mode = GLES3::SceneShaderData::CULL_BACK; + } else if (cull_mode == GLES3::SceneShaderData::CULL_BACK && mirror) { + cull_mode = GLES3::SceneShaderData::CULL_FRONT; } - scene_state.current_blend_mode = desired_blend_mode; } - } - //find cull variant - GLES3::SceneShaderData::Cull cull_mode = shader->cull_mode; + if (scene_state.cull_mode != cull_mode) { + if (cull_mode == GLES3::SceneShaderData::CULL_DISABLED) { + glDisable(GL_CULL_FACE); + } else { + if (scene_state.cull_mode == GLES3::SceneShaderData::CULL_DISABLED) { + // Last time was disabled, so enable and set proper face. + glEnable(GL_CULL_FACE); + } + glCullFace(cull_mode == GLES3::SceneShaderData::CULL_FRONT ? GL_FRONT : GL_BACK); + } + scene_state.cull_mode = cull_mode; + } - if ((surf->flags & GeometryInstanceSurface::FLAG_USES_DOUBLE_SIDED_SHADOWS)) { - cull_mode = GLES3::SceneShaderData::CULL_DISABLED; - } else { - bool mirror = inst->mirror; - if (p_params->reverse_cull) { - mirror = !mirror; + RS::PrimitiveType primitive = surf->primitive; + if (shader->uses_point_size) { + primitive = RS::PRIMITIVE_POINTS; } - if (cull_mode == GLES3::SceneShaderData::CULL_FRONT && mirror) { - cull_mode = GLES3::SceneShaderData::CULL_BACK; - } else if (cull_mode == GLES3::SceneShaderData::CULL_BACK && mirror) { - cull_mode = GLES3::SceneShaderData::CULL_FRONT; + static const GLenum prim[5] = { GL_POINTS, GL_LINES, GL_LINE_STRIP, GL_TRIANGLES, GL_TRIANGLE_STRIP }; + GLenum primitive_gl = prim[int(primitive)]; + + GLuint vertex_array_gl = 0; + GLuint index_array_gl = 0; + uint64_t vertex_input_mask = shader->vertex_input_mask; + if (inst->lightmap_instance.is_valid() || p_pass_mode == PASS_MODE_MATERIAL) { + vertex_input_mask |= 1 << RS::ARRAY_TEX_UV2; } - } - if (scene_state.cull_mode != cull_mode) { - if (cull_mode == GLES3::SceneShaderData::CULL_DISABLED) { - glDisable(GL_CULL_FACE); + // Skeleton and blend shapes. + if (surf->owner->mesh_instance.is_valid()) { + mesh_storage->mesh_instance_surface_get_vertex_arrays_and_format(surf->owner->mesh_instance, surf->surface_index, vertex_input_mask, vertex_array_gl); } else { - if (scene_state.cull_mode == GLES3::SceneShaderData::CULL_DISABLED) { - // Last time was disabled, so enable and set proper face. - glEnable(GL_CULL_FACE); - } - glCullFace(cull_mode == GLES3::SceneShaderData::CULL_FRONT ? GL_FRONT : GL_BACK); + mesh_storage->mesh_surface_get_vertex_arrays_and_format(mesh_surface, vertex_input_mask, vertex_array_gl); } - scene_state.cull_mode = cull_mode; - } - RS::PrimitiveType primitive = surf->primitive; - if (shader->uses_point_size) { - primitive = RS::PRIMITIVE_POINTS; - } - static const GLenum prim[5] = { GL_POINTS, GL_LINES, GL_LINE_STRIP, GL_TRIANGLES, GL_TRIANGLE_STRIP }; - GLenum primitive_gl = prim[int(primitive)]; + index_array_gl = mesh_storage->mesh_surface_get_index_buffer(mesh_surface, surf->lod_index); - GLuint vertex_array_gl = 0; - GLuint index_array_gl = 0; + if (prev_vertex_array_gl != vertex_array_gl) { + if (vertex_array_gl != 0) { + glBindVertexArray(vertex_array_gl); + } + prev_vertex_array_gl = vertex_array_gl; - //skeleton and blend shape - if (surf->owner->mesh_instance.is_valid()) { - mesh_storage->mesh_instance_surface_get_vertex_arrays_and_format(surf->owner->mesh_instance, surf->surface_index, shader->vertex_input_mask, vertex_array_gl); - } else { - mesh_storage->mesh_surface_get_vertex_arrays_and_format(mesh_surface, shader->vertex_input_mask, vertex_array_gl); - } + // Invalidate the previous index array + prev_index_array_gl = 0; + } - index_array_gl = mesh_storage->mesh_surface_get_index_buffer(mesh_surface, surf->lod_index); + bool use_wireframe = false; + if (p_params->force_wireframe) { + GLuint wireframe_index_array_gl = mesh_storage->mesh_surface_get_index_buffer_wireframe(mesh_surface); + if (wireframe_index_array_gl) { + index_array_gl = wireframe_index_array_gl; + use_wireframe = true; + } + } - if (prev_vertex_array_gl != vertex_array_gl) { - if (vertex_array_gl != 0) { - glBindVertexArray(vertex_array_gl); + bool use_index_buffer = index_array_gl != 0; + if (prev_index_array_gl != index_array_gl) { + if (index_array_gl != 0) { + // Bind index each time so we can use LODs + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, index_array_gl); + } + prev_index_array_gl = index_array_gl; } - prev_vertex_array_gl = vertex_array_gl; - // Invalidate the previous index array - prev_index_array_gl = 0; - } + Transform3D world_transform; + if (inst->store_transform_cache) { + world_transform = inst->transform; + } - bool use_index_buffer = index_array_gl != 0; - if (prev_index_array_gl != index_array_gl) { - if (index_array_gl != 0) { - // Bind index each time so we can use LODs - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, index_array_gl); + if (prev_material_data != material_data) { + material_data->bind_uniforms(); + prev_material_data = material_data; } - prev_index_array_gl = index_array_gl; - } - Transform3D world_transform; - if (inst->store_transform_cache) { - world_transform = inst->transform; - } + SceneShaderGLES3::ShaderVariant instance_variant = shader_variant; - if (prev_material_data != material_data) { - material_data->bind_uniforms(); - prev_material_data = material_data; - } + if (inst->instance_count > 0) { + // Will need to use instancing to draw (either MultiMesh or Particles). + instance_variant = SceneShaderGLES3::ShaderVariant(1 + int(instance_variant)); + } - SceneShaderGLES3::ShaderVariant instance_variant = shader_variant; - if (inst->instance_count > 0) { - // Will need to use instancing to draw (either MultiMesh or Particles). - instance_variant = SceneShaderGLES3::ShaderVariant(1 + int(shader_variant)); - } + uint64_t spec_constants = base_spec_constants; - uint64_t spec_constants = base_spec_constants; + // Set up spec constants for lighting. + if constexpr (p_pass_mode == PASS_MODE_COLOR || p_pass_mode == PASS_MODE_COLOR_TRANSPARENT) { + // Only check during color passes as light shader code is compiled out during depth-only pass anyway. - if (inst->omni_light_count == 0) { - spec_constants |= SceneShaderGLES3::DISABLE_LIGHT_OMNI; - } + if (pass == 0) { + spec_constants |= SceneShaderGLES3::BASE_PASS; + if (inst->omni_light_gl_cache.size() == 0) { + spec_constants |= SceneShaderGLES3::DISABLE_LIGHT_OMNI; + } - if (inst->spot_light_count == 0) { - spec_constants |= SceneShaderGLES3::DISABLE_LIGHT_SPOT; - } + if (inst->spot_light_gl_cache.size() == 0) { + spec_constants |= SceneShaderGLES3::DISABLE_LIGHT_SPOT; + } - if (prev_shader != shader || prev_variant != instance_variant || spec_constants != prev_spec_constants) { - bool success = material_storage->shaders.scene_shader.version_bind_shader(shader->version, instance_variant, spec_constants); - if (!success) { - continue; - } + if (p_render_data->directional_light_count == p_render_data->directional_shadow_count) { + spec_constants |= SceneShaderGLES3::DISABLE_LIGHT_DIRECTIONAL; + } - float opaque_prepass_threshold = 0.0; - if constexpr (p_pass_mode == PASS_MODE_DEPTH) { - opaque_prepass_threshold = 0.99; - } else if constexpr (p_pass_mode == PASS_MODE_SHADOW) { - opaque_prepass_threshold = 0.1; - } + if (inst->lightmap_instance.is_valid()) { + spec_constants |= SceneShaderGLES3::USE_LIGHTMAP; - material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::OPAQUE_PREPASS_THRESHOLD, opaque_prepass_threshold, shader->version, instance_variant, spec_constants); + GLES3::LightmapInstance *li = GLES3::LightStorage::get_singleton()->get_lightmap_instance(inst->lightmap_instance); + GLES3::Lightmap *lm = GLES3::LightStorage::get_singleton()->get_lightmap(li->lightmap); - prev_shader = shader; - prev_variant = instance_variant; - prev_spec_constants = spec_constants; - } + if (lm->uses_spherical_harmonics) { + spec_constants |= SceneShaderGLES3::USE_SH_LIGHTMAP; + } + } else if (inst->lightmap_sh) { + spec_constants |= SceneShaderGLES3::USE_LIGHTMAP_CAPTURE; + } else { + spec_constants |= SceneShaderGLES3::DISABLE_LIGHTMAP; + } + } else { + // Only base pass uses the radiance map. + spec_constants &= ~SceneShaderGLES3::USE_RADIANCE_MAP; + spec_constants |= SceneShaderGLES3::DISABLE_LIGHT_OMNI; + spec_constants |= SceneShaderGLES3::DISABLE_LIGHT_SPOT; + spec_constants |= SceneShaderGLES3::DISABLE_LIGHT_DIRECTIONAL; + spec_constants |= SceneShaderGLES3::DISABLE_LIGHTMAP; + } - if (prev_inst != inst || prev_shader != shader || prev_variant != instance_variant) { - // Rebind the light indices. - material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::OMNI_LIGHT_COUNT, inst->omni_light_count, shader->version, instance_variant, spec_constants); - material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::SPOT_LIGHT_COUNT, inst->spot_light_count, shader->version, instance_variant, spec_constants); + if (uses_additive_lighting) { + spec_constants |= SceneShaderGLES3::USE_ADDITIVE_LIGHTING; - if (inst->omni_light_count) { - glUniform1uiv(material_storage->shaders.scene_shader.version_get_uniform(SceneShaderGLES3::OMNI_LIGHT_INDICES, shader->version, instance_variant, spec_constants), inst->omni_light_count, inst->omni_light_gl_cache.ptr()); - } + if (pass < int32_t(inst->light_passes.size())) { + // Rendering positional lights. + if (inst->light_passes[pass].is_omni) { + spec_constants |= SceneShaderGLES3::ADDITIVE_OMNI; + } else { + spec_constants |= SceneShaderGLES3::ADDITIVE_SPOT; + } + + if (scene_state.positional_shadow_quality >= RS::SHADOW_QUALITY_SOFT_HIGH) { + spec_constants |= SceneShaderGLES3::SHADOW_MODE_PCF_13; + } else if (scene_state.positional_shadow_quality >= RS::SHADOW_QUALITY_SOFT_LOW) { + spec_constants |= SceneShaderGLES3::SHADOW_MODE_PCF_5; + } + } else { + // Render directional lights. + + uint32_t shadow_id = MAX_DIRECTIONAL_LIGHTS - 1 - (pass - int32_t(inst->light_passes.size())); + if (pass == 0 && inst->lightmap_instance.is_valid() && scene_state.directional_lights[shadow_id].bake_mode == RenderingServer::LIGHT_BAKE_STATIC) { + // Disable additive lighting with a static light and a lightmap. + spec_constants &= ~SceneShaderGLES3::USE_ADDITIVE_LIGHTING; + } + if (scene_state.directional_shadows[shadow_id].shadow_split_offsets[0] == scene_state.directional_shadows[shadow_id].shadow_split_offsets[1]) { + // Orthogonal, do nothing. + } else if (scene_state.directional_shadows[shadow_id].shadow_split_offsets[1] == scene_state.directional_shadows[shadow_id].shadow_split_offsets[2]) { + spec_constants |= SceneShaderGLES3::LIGHT_USE_PSSM2; + } else { + spec_constants |= SceneShaderGLES3::LIGHT_USE_PSSM4; + } - if (inst->spot_light_count) { - glUniform1uiv(material_storage->shaders.scene_shader.version_get_uniform(SceneShaderGLES3::SPOT_LIGHT_INDICES, shader->version, instance_variant, spec_constants), inst->spot_light_count, inst->spot_light_gl_cache.ptr()); + if (scene_state.directional_shadows[shadow_id].blend_splits) { + spec_constants |= SceneShaderGLES3::LIGHT_USE_PSSM_BLEND; + } + + if (scene_state.directional_shadow_quality >= RS::SHADOW_QUALITY_SOFT_HIGH) { + spec_constants |= SceneShaderGLES3::SHADOW_MODE_PCF_13; + } else if (scene_state.directional_shadow_quality >= RS::SHADOW_QUALITY_SOFT_LOW) { + spec_constants |= SceneShaderGLES3::SHADOW_MODE_PCF_5; + } + } + } } - prev_inst = inst; - } + if (prev_shader != shader || prev_variant != instance_variant || spec_constants != prev_spec_constants) { + bool success = material_storage->shaders.scene_shader.version_bind_shader(shader->version, instance_variant, spec_constants); + if (!success) { + break; + } - material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::WORLD_TRANSFORM, world_transform, shader->version, instance_variant, spec_constants); + float opaque_prepass_threshold = 0.0; + if constexpr (p_pass_mode == PASS_MODE_DEPTH) { + opaque_prepass_threshold = 0.99; + } else if constexpr (p_pass_mode == PASS_MODE_SHADOW) { + opaque_prepass_threshold = 0.1; + } - // Can be index count or vertex count - uint32_t count = 0; - if (surf->lod_index > 0) { - count = surf->index_count; - } else { - count = mesh_storage->mesh_surface_get_vertices_drawn_count(mesh_surface); - } - if constexpr (p_pass_mode != PASS_MODE_DEPTH) { - // Don't count draw calls during depth pre-pass to match the RD renderers. - if (p_render_data->render_info) { - p_render_data->render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_VISIBLE][RS::VIEWPORT_RENDER_INFO_DRAW_CALLS_IN_FRAME]++; + material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::OPAQUE_PREPASS_THRESHOLD, opaque_prepass_threshold, shader->version, instance_variant, spec_constants); + + prev_shader = shader; + prev_variant = instance_variant; + prev_spec_constants = spec_constants; } - } - if (inst->instance_count > 0) { - // Using MultiMesh or Particles. - // Bind instance buffers. + // Pass in lighting uniforms. + if constexpr (p_pass_mode == PASS_MODE_COLOR || p_pass_mode == PASS_MODE_COLOR_TRANSPARENT) { + GLES3::Config *config = GLES3::Config::get_singleton(); + // Pass light and shadow index and bind shadow texture. + if (uses_additive_lighting) { + if (pass < int32_t(inst->light_passes.size())) { + int32_t shadow_id = inst->light_passes[pass].shadow_id; + if (shadow_id >= 0) { + uint32_t light_id = inst->light_passes[pass].light_id; + bool is_omni = inst->light_passes[pass].is_omni; + SceneShaderGLES3::Uniforms uniform_name = is_omni ? SceneShaderGLES3::OMNI_LIGHT_INDEX : SceneShaderGLES3::SPOT_LIGHT_INDEX; + material_storage->shaders.scene_shader.version_set_uniform(uniform_name, uint32_t(light_id), shader->version, instance_variant, spec_constants); + material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::POSITIONAL_SHADOW_INDEX, uint32_t(shadow_id), shader->version, instance_variant, spec_constants); + + glActiveTexture(GL_TEXTURE0 + config->max_texture_image_units - 3); + RID light_instance_rid = inst->light_passes[pass].light_instance_rid; + + GLuint tex = GLES3::LightStorage::get_singleton()->light_instance_get_shadow_texture(light_instance_rid, p_render_data->shadow_atlas); + if (is_omni) { + glBindTexture(GL_TEXTURE_CUBE_MAP, tex); + } else { + glBindTexture(GL_TEXTURE_2D, tex); + } + } + } else { + uint32_t shadow_id = MAX_DIRECTIONAL_LIGHTS - 1 - (pass - int32_t(inst->light_passes.size())); + material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::DIRECTIONAL_SHADOW_INDEX, shadow_id, shader->version, instance_variant, spec_constants); + + GLuint tex = GLES3::LightStorage::get_singleton()->directional_shadow_get_texture(); + glActiveTexture(GL_TEXTURE0 + config->max_texture_image_units - 3); + glBindTexture(GL_TEXTURE_2D, tex); + } + } - GLuint instance_buffer = 0; - uint32_t stride = 0; - if (inst->flags_cache & INSTANCE_DATA_FLAG_PARTICLES) { - instance_buffer = particles_storage->particles_get_gl_buffer(inst->data->base); - stride = 16; // 12 bytes for instance transform and 4 bytes for packed color and custom. - } else { - instance_buffer = mesh_storage->multimesh_get_gl_buffer(inst->data->base); - stride = mesh_storage->multimesh_get_stride(inst->data->base); + // Pass light count and array of light indices for base pass. + if ((prev_inst != inst || prev_shader != shader || prev_variant != instance_variant) && pass == 0) { + // Rebind the light indices. + material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::OMNI_LIGHT_COUNT, inst->omni_light_gl_cache.size(), shader->version, instance_variant, spec_constants); + material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::SPOT_LIGHT_COUNT, inst->spot_light_gl_cache.size(), shader->version, instance_variant, spec_constants); + + if (inst->omni_light_gl_cache.size()) { + 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()); + } + + if (inst->spot_light_gl_cache.size()) { + 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()); + } + + if (inst->lightmap_instance.is_valid()) { + GLES3::LightmapInstance *li = GLES3::LightStorage::get_singleton()->get_lightmap_instance(inst->lightmap_instance); + GLES3::Lightmap *lm = GLES3::LightStorage::get_singleton()->get_lightmap(li->lightmap); + + GLuint tex = GLES3::TextureStorage::get_singleton()->texture_get_texid(lm->light_texture); + glActiveTexture(GL_TEXTURE0 + config->max_texture_image_units - 4); + glBindTexture(GL_TEXTURE_2D_ARRAY, tex); + + material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::LIGHTMAP_SLICE, inst->lightmap_slice_index, shader->version, instance_variant, spec_constants); + + Vector4 uv_scale(inst->lightmap_uv_scale.position.x, inst->lightmap_uv_scale.position.y, inst->lightmap_uv_scale.size.x, inst->lightmap_uv_scale.size.y); + material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::LIGHTMAP_UV_SCALE, uv_scale, shader->version, instance_variant, spec_constants); + + float exposure_normalization = 1.0; + if (p_render_data->camera_attributes.is_valid()) { + float enf = RSG::camera_attributes->camera_attributes_get_exposure_normalization_factor(p_render_data->camera_attributes); + exposure_normalization = enf / lm->baked_exposure; + } + material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::LIGHTMAP_EXPOSURE_NORMALIZATION, exposure_normalization, shader->version, instance_variant, spec_constants); + + if (lm->uses_spherical_harmonics) { + Basis to_lm = li->transform.basis.inverse() * p_render_data->cam_transform.basis; + to_lm = to_lm.inverse().transposed(); + GLfloat matrix[9] = { + (GLfloat)to_lm.rows[0][0], + (GLfloat)to_lm.rows[1][0], + (GLfloat)to_lm.rows[2][0], + (GLfloat)to_lm.rows[0][1], + (GLfloat)to_lm.rows[1][1], + (GLfloat)to_lm.rows[2][1], + (GLfloat)to_lm.rows[0][2], + (GLfloat)to_lm.rows[1][2], + (GLfloat)to_lm.rows[2][2], + }; + glUniformMatrix3fv(material_storage->shaders.scene_shader.version_get_uniform(SceneShaderGLES3::LIGHTMAP_NORMAL_XFORM, shader->version, instance_variant, spec_constants), 1, GL_FALSE, matrix); + } + } else if (inst->lightmap_sh) { + glUniform4fv(material_storage->shaders.scene_shader.version_get_uniform(SceneShaderGLES3::LIGHTMAP_CAPTURES, shader->version, instance_variant, spec_constants), 9, reinterpret_cast<const GLfloat *>(inst->lightmap_sh->sh)); + } + + prev_inst = inst; + } } - if (instance_buffer == 0) { - // Instance buffer not initialized yet. Skip rendering for now. - continue; + material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::WORLD_TRANSFORM, world_transform, shader->version, instance_variant, spec_constants); + { + GLES3::Mesh::Surface *s = reinterpret_cast<GLES3::Mesh::Surface *>(surf->surface); + if (s->format & RS::ARRAY_FLAG_COMPRESS_ATTRIBUTES) { + material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::COMPRESSED_AABB_POSITION, s->aabb.position, shader->version, instance_variant, spec_constants); + material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::COMPRESSED_AABB_SIZE, s->aabb.size, shader->version, instance_variant, spec_constants); + material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::UV_SCALE, s->uv_scale, shader->version, instance_variant, spec_constants); + } else { + 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); + 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); + 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); + } } - glBindBuffer(GL_ARRAY_BUFFER, instance_buffer); + material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::MODEL_FLAGS, inst->flags_cache, shader->version, instance_variant, spec_constants); - glEnableVertexAttribArray(12); - glVertexAttribPointer(12, 4, GL_FLOAT, GL_FALSE, stride * sizeof(float), CAST_INT_TO_UCHAR_PTR(0)); - glVertexAttribDivisor(12, 1); - glEnableVertexAttribArray(13); - glVertexAttribPointer(13, 4, GL_FLOAT, GL_FALSE, stride * sizeof(float), CAST_INT_TO_UCHAR_PTR(sizeof(float) * 4)); - glVertexAttribDivisor(13, 1); - if (!(inst->flags_cache & INSTANCE_DATA_FLAG_MULTIMESH_FORMAT_2D)) { - glEnableVertexAttribArray(14); - glVertexAttribPointer(14, 4, GL_FLOAT, GL_FALSE, stride * sizeof(float), CAST_INT_TO_UCHAR_PTR(sizeof(float) * 8)); - glVertexAttribDivisor(14, 1); + if (p_pass_mode == PASS_MODE_MATERIAL) { + material_storage->shaders.scene_shader.version_set_uniform(SceneShaderGLES3::UV_OFFSET, p_params->uv_offset, shader->version, instance_variant, spec_constants); } - if ((inst->flags_cache & INSTANCE_DATA_FLAG_MULTIMESH_HAS_COLOR) || (inst->flags_cache & INSTANCE_DATA_FLAG_MULTIMESH_HAS_CUSTOM_DATA)) { - uint32_t color_custom_offset = inst->flags_cache & INSTANCE_DATA_FLAG_MULTIMESH_FORMAT_2D ? 8 : 12; - glEnableVertexAttribArray(15); - glVertexAttribIPointer(15, 4, GL_UNSIGNED_INT, stride * sizeof(float), CAST_INT_TO_UCHAR_PTR(color_custom_offset * sizeof(float))); - glVertexAttribDivisor(15, 1); - } - if (use_index_buffer) { - glDrawElementsInstanced(primitive_gl, count, mesh_storage->mesh_surface_get_index_type(mesh_surface), 0, inst->instance_count); + // Can be index count or vertex count + uint32_t count = 0; + if (surf->lod_index > 0) { + count = surf->index_count; } else { - glDrawArraysInstanced(primitive_gl, 0, count, inst->instance_count); + count = mesh_storage->mesh_surface_get_vertices_drawn_count(mesh_surface); } - } else { - // Using regular Mesh. - if (use_index_buffer) { - glDrawElements(primitive_gl, count, mesh_storage->mesh_surface_get_index_type(mesh_surface), 0); + + if (use_wireframe) { + // In this case we are using index count, and we need double the indices for the wireframe mesh. + count = count * 2; + } + + if constexpr (p_pass_mode != PASS_MODE_DEPTH) { + // Don't count draw calls during depth pre-pass to match the RD renderers. + if (p_render_data->render_info) { + p_render_data->render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_VISIBLE][RS::VIEWPORT_RENDER_INFO_DRAW_CALLS_IN_FRAME]++; + } + } + + if (inst->instance_count > 0) { + // Using MultiMesh or Particles. + // Bind instance buffers. + + GLuint instance_buffer = 0; + uint32_t stride = 0; + if (inst->flags_cache & INSTANCE_DATA_FLAG_PARTICLES) { + instance_buffer = particles_storage->particles_get_gl_buffer(inst->data->base); + stride = 16; // 12 bytes for instance transform and 4 bytes for packed color and custom. + } else { + instance_buffer = mesh_storage->multimesh_get_gl_buffer(inst->data->base); + stride = mesh_storage->multimesh_get_stride(inst->data->base); + } + + if (instance_buffer == 0) { + // Instance buffer not initialized yet. Skip rendering for now. + break; + } + + glBindBuffer(GL_ARRAY_BUFFER, instance_buffer); + + glEnableVertexAttribArray(12); + glVertexAttribPointer(12, 4, GL_FLOAT, GL_FALSE, stride * sizeof(float), CAST_INT_TO_UCHAR_PTR(0)); + glVertexAttribDivisor(12, 1); + glEnableVertexAttribArray(13); + glVertexAttribPointer(13, 4, GL_FLOAT, GL_FALSE, stride * sizeof(float), CAST_INT_TO_UCHAR_PTR(sizeof(float) * 4)); + glVertexAttribDivisor(13, 1); + if (!(inst->flags_cache & INSTANCE_DATA_FLAG_MULTIMESH_FORMAT_2D)) { + glEnableVertexAttribArray(14); + glVertexAttribPointer(14, 4, GL_FLOAT, GL_FALSE, stride * sizeof(float), CAST_INT_TO_UCHAR_PTR(sizeof(float) * 8)); + glVertexAttribDivisor(14, 1); + } + + if ((inst->flags_cache & INSTANCE_DATA_FLAG_MULTIMESH_HAS_COLOR) || (inst->flags_cache & INSTANCE_DATA_FLAG_MULTIMESH_HAS_CUSTOM_DATA)) { + uint32_t color_custom_offset = inst->flags_cache & INSTANCE_DATA_FLAG_MULTIMESH_FORMAT_2D ? 8 : 12; + glEnableVertexAttribArray(15); + glVertexAttribIPointer(15, 4, GL_UNSIGNED_INT, stride * sizeof(float), CAST_INT_TO_UCHAR_PTR(color_custom_offset * sizeof(float))); + glVertexAttribDivisor(15, 1); + } else { + // Set all default instance color and custom data values to 1.0 or 0.0 using a compressed format. + uint16_t zero = Math::make_half_float(0.0f); + uint16_t one = Math::make_half_float(1.0f); + GLuint default_color = (uint32_t(one) << 16) | one; + GLuint default_custom = (uint32_t(zero) << 16) | zero; + glVertexAttribI4ui(15, default_color, default_color, default_custom, default_custom); + } + + if (use_wireframe) { + glDrawElementsInstanced(GL_LINES, count, GL_UNSIGNED_INT, 0, inst->instance_count); + } else { + if (use_index_buffer) { + glDrawElementsInstanced(primitive_gl, count, mesh_storage->mesh_surface_get_index_type(mesh_surface), 0, inst->instance_count); + } else { + glDrawArraysInstanced(primitive_gl, 0, count, inst->instance_count); + } + } } else { - glDrawArrays(primitive_gl, 0, count); + // Using regular Mesh. + if (use_wireframe) { + glDrawElements(GL_LINES, count, GL_UNSIGNED_INT, 0); + } else { + if (use_index_buffer) { + glDrawElements(primitive_gl, count, mesh_storage->mesh_surface_get_index_type(mesh_surface), 0); + } else { + glDrawArrays(primitive_gl, 0, count); + } + } + } + + if (inst->instance_count > 0) { + glDisableVertexAttribArray(12); + glDisableVertexAttribArray(13); + glDisableVertexAttribArray(14); + glDisableVertexAttribArray(15); } } - if (inst->instance_count > 0) { - glDisableVertexAttribArray(12); - glDisableVertexAttribArray(13); - glDisableVertexAttribArray(14); - glDisableVertexAttribArray(15); + if constexpr (p_pass_mode == PASS_MODE_COLOR) { + if (uses_additive_lighting && !p_render_data->transparent_bg) { + // Disable additive blending if enabled for additive lights. + glDisable(GL_BLEND); + } } } @@ -2468,6 +3459,7 @@ void RasterizerSceneGLES3::render_particle_collider_heightfield(RID p_collider, render_data.cam_orthogonal = true; render_data.z_near = 0.0; render_data.z_far = cm.get_z_far(); + render_data.main_cam_transform = cam_xform; render_data.instances = &p_instances; @@ -2497,8 +3489,11 @@ void RasterizerSceneGLES3::render_particle_collider_heightfield(RID p_collider, glEnable(GL_CULL_FACE); scene_state.cull_mode = GLES3::SceneShaderData::CULL_BACK; + glDrawBuffers(0, nullptr); + glColorMask(0, 0, 0, 0); - glClearDepth(1.0f); + RasterizerGLES3::clear_depth(1.0); + glClear(GL_DEPTH_BUFFER_BIT); RenderListParameters render_list_params(render_list[RENDER_LIST_SECONDARY].elements.ptr(), render_list[RENDER_LIST_SECONDARY].elements.size(), false, 31, false); @@ -2509,6 +3504,93 @@ void RasterizerSceneGLES3::render_particle_collider_heightfield(RID p_collider, glBindFramebuffer(GL_FRAMEBUFFER, 0); } +void RasterizerSceneGLES3::_render_uv2(const PagedArray<RenderGeometryInstance *> &p_instances, GLuint p_framebuffer, const Rect2i &p_region) { + RENDER_TIMESTAMP("Setup Rendering UV2"); + + RenderDataGLES3 render_data; + render_data.instances = &p_instances; + + scene_state.ubo.emissive_exposure_normalization = -1.0; // Use default exposure normalization. + + _setup_environment(&render_data, true, Vector2(1, 1), true, Color(), false); + + PassMode pass_mode = PASS_MODE_MATERIAL; + + _fill_render_list(RENDER_LIST_SECONDARY, &render_data, pass_mode); + render_list[RENDER_LIST_SECONDARY].sort_by_key(); + + RENDER_TIMESTAMP("Render 3D Material"); + + { + glBindFramebuffer(GL_FRAMEBUFFER, p_framebuffer); + glViewport(p_region.position.x, p_region.position.y, p_region.size.x, p_region.size.y); + + GLuint global_buffer = GLES3::MaterialStorage::get_singleton()->global_shader_parameters_get_uniform_buffer(); + + glBindBufferBase(GL_UNIFORM_BUFFER, SCENE_GLOBALS_UNIFORM_LOCATION, global_buffer); + glBindBuffer(GL_UNIFORM_BUFFER, 0); + + glDisable(GL_BLEND); + glDepthMask(GL_TRUE); + glEnable(GL_DEPTH_TEST); + glDepthFunc(GL_LESS); + glDisable(GL_SCISSOR_TEST); + glCullFace(GL_BACK); + glEnable(GL_CULL_FACE); + scene_state.cull_mode = GLES3::SceneShaderData::CULL_BACK; + + TightLocalVector<GLenum> draw_buffers; + draw_buffers.push_back(GL_COLOR_ATTACHMENT0); + draw_buffers.push_back(GL_COLOR_ATTACHMENT1); + draw_buffers.push_back(GL_COLOR_ATTACHMENT2); + draw_buffers.push_back(GL_COLOR_ATTACHMENT3); + glDrawBuffers(draw_buffers.size(), draw_buffers.ptr()); + + glClearColor(0.0, 0.0, 0.0, 0.0); + RasterizerGLES3::clear_depth(1.0); + glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); + + uint64_t base_spec_constant = 0; + base_spec_constant |= SceneShaderGLES3::RENDER_MATERIAL; + base_spec_constant |= SceneShaderGLES3::DISABLE_FOG; + base_spec_constant |= SceneShaderGLES3::DISABLE_LIGHT_DIRECTIONAL; + base_spec_constant |= SceneShaderGLES3::DISABLE_LIGHT_OMNI; + base_spec_constant |= SceneShaderGLES3::DISABLE_LIGHT_SPOT; + base_spec_constant |= SceneShaderGLES3::DISABLE_LIGHTMAP; + + RenderListParameters render_list_params(render_list[RENDER_LIST_SECONDARY].elements.ptr(), render_list[RENDER_LIST_SECONDARY].elements.size(), false, base_spec_constant, true, Vector2(0, 0)); + + const int uv_offset_count = 9; + static const Vector2 uv_offsets[uv_offset_count] = { + Vector2(-1, 1), + Vector2(1, 1), + Vector2(1, -1), + Vector2(-1, -1), + Vector2(-1, 0), + Vector2(1, 0), + Vector2(0, -1), + Vector2(0, 1), + Vector2(0, 0), + }; + + for (int i = 0; i < uv_offset_count; i++) { + Vector2 ofs = uv_offsets[i]; + ofs.x /= p_region.size.width; + ofs.y /= p_region.size.height; + render_list_params.uv_offset = ofs; + _render_list_template<PASS_MODE_MATERIAL>(&render_list_params, &render_data, 0, render_list[RENDER_LIST_SECONDARY].elements.size()); + } + + render_list_params.uv_offset = Vector2(0, 0); + render_list_params.force_wireframe = false; + _render_list_template<PASS_MODE_MATERIAL>(&render_list_params, &render_data, 0, render_list[RENDER_LIST_SECONDARY].elements.size()); + + GLuint db = GL_COLOR_ATTACHMENT0; + glDrawBuffers(1, &db); + glBindFramebuffer(GL_FRAMEBUFFER, 0); + } +} + void RasterizerSceneGLES3::set_time(double p_time, double p_step) { time = p_time; time_step = p_step; @@ -2524,32 +3606,119 @@ Ref<RenderSceneBuffers> RasterizerSceneGLES3::render_buffers_create() { return rb; } -//clear render buffers -/* +void RasterizerSceneGLES3::_render_buffers_debug_draw(Ref<RenderSceneBuffersGLES3> p_render_buffers, RID p_shadow_atlas, GLuint p_fbo) { + GLES3::TextureStorage *texture_storage = GLES3::TextureStorage::get_singleton(); + GLES3::LightStorage *light_storage = GLES3::LightStorage::get_singleton(); + GLES3::CopyEffects *copy_effects = GLES3::CopyEffects::get_singleton(); + + ERR_FAIL_COND(p_render_buffers.is_null()); + + RID render_target = p_render_buffers->render_target; + GLES3::RenderTarget *rt = texture_storage->get_render_target(render_target); + ERR_FAIL_NULL(rt); + + if (debug_draw == RS::VIEWPORT_DEBUG_DRAW_SHADOW_ATLAS) { + if (p_shadow_atlas.is_valid()) { + // Get or create debug textures to display shadow maps as an atlas. + GLuint shadow_atlas_texture = light_storage->shadow_atlas_get_debug_texture(p_shadow_atlas); + GLuint shadow_atlas_fb = light_storage->shadow_atlas_get_debug_fb(p_shadow_atlas); + + uint32_t shadow_atlas_size = light_storage->shadow_atlas_get_size(p_shadow_atlas); + uint32_t quadrant_size = shadow_atlas_size >> 1; + + glBindFramebuffer(GL_FRAMEBUFFER, shadow_atlas_fb); + glViewport(0, 0, shadow_atlas_size, shadow_atlas_size); + glActiveTexture(GL_TEXTURE0); + glDepthMask(GL_TRUE); + glDepthFunc(GL_ALWAYS); + glDisable(GL_CULL_FACE); + scene_state.cull_mode = GLES3::SceneShaderData::CULL_DISABLED; + + // Loop through quadrants and copy shadows over. + for (int quadrant = 0; quadrant < 4; quadrant++) { + uint32_t subdivision = light_storage->shadow_atlas_get_quadrant_subdivision(p_shadow_atlas, quadrant); + if (subdivision == 0) { + continue; + } + + Rect2i atlas_rect; + Rect2 atlas_uv_rect; + uint32_t shadow_size = (quadrant_size / subdivision); + float size = float(shadow_size) / float(shadow_atlas_size); - if (rt->copy_screen_effect.color) { - glDeleteFramebuffers(1, &rt->copy_screen_effect.fbo); - rt->copy_screen_effect.fbo = 0; + uint32_t length = light_storage->shadow_atlas_get_quadrant_shadows_allocated(p_shadow_atlas, quadrant); + for (uint32_t shadow_idx = 0; shadow_idx < length; shadow_idx++) { + bool is_omni = light_storage->shadow_atlas_get_quadrant_shadow_is_omni(p_shadow_atlas, quadrant, shadow_idx); - glDeleteTextures(1, &rt->copy_screen_effect.color); - rt->copy_screen_effect.color = 0; - } + // Calculate shadow's position in the debug atlas. + atlas_rect.position.x = (quadrant & 1) * quadrant_size; + atlas_rect.position.y = (quadrant >> 1) * quadrant_size; - if (rt->multisample_active) { - glDeleteFramebuffers(1, &rt->multisample_fbo); - rt->multisample_fbo = 0; + atlas_rect.position.x += (shadow_idx % subdivision) * shadow_size; + atlas_rect.position.y += (shadow_idx / subdivision) * shadow_size; - glDeleteRenderbuffers(1, &rt->multisample_depth); - rt->multisample_depth = 0; + atlas_uv_rect.position = Vector2(atlas_rect.position) / float(shadow_atlas_size); - glDeleteRenderbuffers(1, &rt->multisample_color); + atlas_uv_rect.size = Vector2(size, size); - rt->multisample_color = 0; - } -*/ + GLuint shadow_tex = light_storage->shadow_atlas_get_quadrant_shadow_texture(p_shadow_atlas, quadrant, shadow_idx); + // Copy from shadowmap to debug atlas. + if (is_omni) { + glBindTexture(GL_TEXTURE_CUBE_MAP, shadow_tex); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_COMPARE_MODE, GL_NONE); + + copy_effects->copy_cube_to_rect(atlas_uv_rect); + + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_COMPARE_FUNC, GL_LESS); + } else { + glBindTexture(GL_TEXTURE_2D, shadow_tex); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE); + + copy_effects->copy_to_rect(atlas_uv_rect); -void RasterizerSceneGLES3::_render_buffers_debug_draw(Ref<RenderSceneBuffersGLES3> p_render_buffers, RID p_shadow_atlas, RID p_occlusion_buffer) { + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LESS); + } + } + } + + // Set back to FBO + glBindFramebuffer(GL_FRAMEBUFFER, p_fbo); + Size2i size = p_render_buffers->get_internal_size(); + glViewport(0, 0, size.width, size.height); + glBindTexture(GL_TEXTURE_2D, shadow_atlas_texture); + + copy_effects->copy_to_rect(Rect2(Vector2(), Vector2(0.5, 0.5))); + glBindTexture(GL_TEXTURE_2D, 0); + glBindFramebuffer(GL_FRAMEBUFFER, 0); + } + } + if (debug_draw == RS::VIEWPORT_DEBUG_DRAW_DIRECTIONAL_SHADOW_ATLAS) { + if (light_storage->directional_shadow_get_texture() != 0) { + GLuint shadow_atlas_texture = light_storage->directional_shadow_get_texture(); + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, shadow_atlas_texture); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_R, GL_RED); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_G, GL_RED); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, GL_RED); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_A, GL_ONE); + + glDisable(GL_DEPTH_TEST); + glDepthMask(GL_FALSE); + + copy_effects->copy_to_rect(Rect2(Vector2(), Vector2(0.5, 0.5))); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_R, GL_RED); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_G, GL_GREEN); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, GL_BLUE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_A, GL_ALPHA); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LESS); + glBindTexture(GL_TEXTURE_2D, 0); + } + } } void RasterizerSceneGLES3::gi_set_use_half_resolution(bool p_enable) { @@ -2569,7 +3738,155 @@ void RasterizerSceneGLES3::sub_surface_scattering_set_scale(float p_scale, float } TypedArray<Image> RasterizerSceneGLES3::bake_render_uv2(RID p_base, const TypedArray<RID> &p_material_overrides, const Size2i &p_image_size) { - return TypedArray<Image>(); + GLES3::Config *config = GLES3::Config::get_singleton(); + ERR_FAIL_COND_V_MSG(p_image_size.width <= 0, TypedArray<Image>(), "Image width must be greater than 0."); + ERR_FAIL_COND_V_MSG(p_image_size.height <= 0, TypedArray<Image>(), "Image height must be greater than 0."); + + GLuint albedo_alpha_tex = 0; + GLuint normal_tex = 0; + GLuint orm_tex = 0; + GLuint emission_tex = 0; + GLuint depth_tex = 0; + glGenTextures(1, &albedo_alpha_tex); + glGenTextures(1, &normal_tex); + glGenTextures(1, &orm_tex); + glGenTextures(1, &emission_tex); + glGenTextures(1, &depth_tex); + + glBindTexture(GL_TEXTURE_2D, albedo_alpha_tex); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, p_image_size.width, p_image_size.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); + GLES3::Utilities::get_singleton()->texture_allocated_data(albedo_alpha_tex, p_image_size.width * p_image_size.height * 4, "Lightmap albedo texture"); + + glBindTexture(GL_TEXTURE_2D, normal_tex); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, p_image_size.width, p_image_size.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); + GLES3::Utilities::get_singleton()->texture_allocated_data(normal_tex, p_image_size.width * p_image_size.height * 4, "Lightmap normal texture"); + + glBindTexture(GL_TEXTURE_2D, orm_tex); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, p_image_size.width, p_image_size.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); + GLES3::Utilities::get_singleton()->texture_allocated_data(orm_tex, p_image_size.width * p_image_size.height * 4, "Lightmap ORM texture"); + + // Consider rendering to RGBA8 encoded as RGBE, then manually convert to RGBAH on CPU. + glBindTexture(GL_TEXTURE_2D, emission_tex); + if (config->float_texture_supported) { + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, p_image_size.width, p_image_size.height, 0, GL_RGBA, GL_FLOAT, nullptr); + GLES3::Utilities::get_singleton()->texture_allocated_data(emission_tex, p_image_size.width * p_image_size.height * 16, "Lightmap emission texture"); + } else { + // Fallback to RGBA8 on devices that don't support rendering to floating point textures. This will look bad, but we have no choice. + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, p_image_size.width, p_image_size.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); + GLES3::Utilities::get_singleton()->texture_allocated_data(emission_tex, p_image_size.width * p_image_size.height * 4, "Lightmap emission texture"); + } + + glBindTexture(GL_TEXTURE_2D, depth_tex); + glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, p_image_size.width, p_image_size.height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, nullptr); + GLES3::Utilities::get_singleton()->texture_allocated_data(depth_tex, p_image_size.width * p_image_size.height * 3, "Lightmap depth texture"); + + GLuint fbo = 0; + glGenFramebuffers(1, &fbo); + glBindFramebuffer(GL_FRAMEBUFFER, fbo); + + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, albedo_alpha_tex, 0); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, normal_tex, 0); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, orm_tex, 0); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT3, GL_TEXTURE_2D, emission_tex, 0); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depth_tex, 0); + + GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); + if (status != GL_FRAMEBUFFER_COMPLETE) { + glDeleteFramebuffers(1, &fbo); + GLES3::Utilities::get_singleton()->texture_free_data(albedo_alpha_tex); + GLES3::Utilities::get_singleton()->texture_free_data(normal_tex); + GLES3::Utilities::get_singleton()->texture_free_data(orm_tex); + GLES3::Utilities::get_singleton()->texture_free_data(emission_tex); + GLES3::Utilities::get_singleton()->texture_free_data(depth_tex); + + WARN_PRINT("Could not create render target, status: " + GLES3::TextureStorage::get_singleton()->get_framebuffer_error(status)); + return TypedArray<Image>(); + } + + RenderGeometryInstance *gi_inst = geometry_instance_create(p_base); + ERR_FAIL_NULL_V(gi_inst, TypedArray<Image>()); + + uint32_t sc = RSG::mesh_storage->mesh_get_surface_count(p_base); + Vector<RID> materials; + materials.resize(sc); + + for (uint32_t i = 0; i < sc; i++) { + if (i < (uint32_t)p_material_overrides.size()) { + materials.write[i] = p_material_overrides[i]; + } + } + + gi_inst->set_surface_materials(materials); + + if (cull_argument.size() == 0) { + cull_argument.push_back(nullptr); + } + cull_argument[0] = gi_inst; + _render_uv2(cull_argument, fbo, Rect2i(0, 0, p_image_size.width, p_image_size.height)); + + geometry_instance_free(gi_inst); + + TypedArray<Image> ret; + + // Create a dummy texture so we can use texture_2d_get. + RID tex_rid = GLES3::TextureStorage::get_singleton()->texture_allocate(); + GLES3::Texture texture; + texture.width = p_image_size.width; + texture.height = p_image_size.height; + texture.alloc_width = p_image_size.width; + texture.alloc_height = p_image_size.height; + texture.format = Image::FORMAT_RGBA8; + texture.real_format = Image::FORMAT_RGBA8; + texture.gl_format_cache = GL_RGBA; + texture.gl_type_cache = GL_UNSIGNED_BYTE; + texture.type = GLES3::Texture::TYPE_2D; + texture.target = GL_TEXTURE_2D; + texture.active = true; + texture.is_render_target = true; // Enable this so the texture isn't cached in the editor. + + GLES3::TextureStorage::get_singleton()->texture_2d_initialize_from_texture(tex_rid, texture); + GLES3::Texture *tex = GLES3::TextureStorage::get_singleton()->get_texture(tex_rid); + + { + tex->tex_id = albedo_alpha_tex; + Ref<Image> img = GLES3::TextureStorage::get_singleton()->texture_2d_get(tex_rid); + GLES3::Utilities::get_singleton()->texture_free_data(albedo_alpha_tex); + ret.push_back(img); + } + + { + tex->tex_id = normal_tex; + Ref<Image> img = GLES3::TextureStorage::get_singleton()->texture_2d_get(tex_rid); + GLES3::Utilities::get_singleton()->texture_free_data(normal_tex); + ret.push_back(img); + } + + { + tex->tex_id = orm_tex; + Ref<Image> img = GLES3::TextureStorage::get_singleton()->texture_2d_get(tex_rid); + GLES3::Utilities::get_singleton()->texture_free_data(orm_tex); + ret.push_back(img); + } + + { + tex->tex_id = emission_tex; + if (config->float_texture_supported) { + tex->format = Image::FORMAT_RGBAF; + tex->real_format = Image::FORMAT_RGBAH; + tex->gl_type_cache = GL_FLOAT; + } + Ref<Image> img = GLES3::TextureStorage::get_singleton()->texture_2d_get(tex_rid); + GLES3::Utilities::get_singleton()->texture_free_data(emission_tex); + ret.push_back(img); + } + + tex->is_render_target = false; + tex->tex_id = 0; + GLES3::TextureStorage::get_singleton()->texture_free(tex_rid); + + GLES3::Utilities::get_singleton()->texture_free_data(depth_tex); + glDeleteFramebuffers(1, &fbo); + return ret; } bool RasterizerSceneGLES3::free(RID p_rid) { @@ -2577,7 +3894,7 @@ bool RasterizerSceneGLES3::free(RID p_rid) { environment_free(p_rid); } else if (sky_owner.owns(p_rid)) { Sky *sky = sky_owner.get_or_null(p_rid); - ERR_FAIL_COND_V(!sky, false); + ERR_FAIL_NULL_V(sky, false); _free_sky_data(sky); sky_owner.free(p_rid); } else if (GLES3::LightStorage::get_singleton()->owns_light_instance(p_rid)) { @@ -2610,9 +3927,14 @@ RasterizerSceneGLES3::RasterizerSceneGLES3() { GLES3::MaterialStorage *material_storage = GLES3::MaterialStorage::get_singleton(); GLES3::Config *config = GLES3::Config::get_singleton(); + cull_argument.set_page_pool(&cull_argument_pool); + // Quality settings. use_physical_light_units = GLOBAL_GET("rendering/lights_and_shadows/use_physical_light_units"); + positional_soft_shadow_filter_set_quality((RS::ShadowQuality)(int)GLOBAL_GET("rendering/lights_and_shadows/positional_shadow/soft_shadow_filter_quality")); + directional_soft_shadow_filter_set_quality((RS::ShadowQuality)(int)GLOBAL_GET("rendering/lights_and_shadows/directional_shadow/soft_shadow_filter_quality")); + { // Setup Lights @@ -2638,6 +3960,18 @@ RasterizerSceneGLES3::RasterizerSceneGLES3() { glBindBuffer(GL_UNIFORM_BUFFER, scene_state.directional_light_buffer); 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"); + uint32_t shadow_buffer_size = config->max_renderable_lights * sizeof(ShadowData) * 2; + scene_state.positional_shadows = memnew_arr(ShadowData, config->max_renderable_lights * 2); + glGenBuffers(1, &scene_state.positional_shadow_buffer); + glBindBuffer(GL_UNIFORM_BUFFER, scene_state.positional_shadow_buffer); + 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"); + + uint32_t directional_shadow_buffer_size = MAX_DIRECTIONAL_LIGHTS * sizeof(DirectionalShadowData); + scene_state.directional_shadows = memnew_arr(DirectionalShadowData, MAX_DIRECTIONAL_LIGHTS); + glGenBuffers(1, &scene_state.directional_shadow_buffer); + glBindBuffer(GL_UNIFORM_BUFFER, scene_state.directional_shadow_buffer); + 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"); + glBindBuffer(GL_UNIFORM_BUFFER, 0); } @@ -2659,7 +3993,7 @@ RasterizerSceneGLES3::RasterizerSceneGLES3() { global_defines += "#define MAX_GLOBAL_SHADER_UNIFORMS 256\n"; // TODO: this is arbitrary for now global_defines += "\n#define MAX_LIGHT_DATA_STRUCTS " + itos(config->max_renderable_lights) + "\n"; global_defines += "\n#define MAX_DIRECTIONAL_LIGHT_DATA_STRUCTS " + itos(MAX_DIRECTIONAL_LIGHTS) + "\n"; - global_defines += "\n#define MAX_FORWARD_LIGHTS uint(" + itos(config->max_lights_per_object) + ")\n"; + global_defines += "\n#define MAX_FORWARD_LIGHTS " + itos(config->max_lights_per_object) + "u\n"; material_storage->shaders.scene_shader.initialize(global_defines); scene_globals.shader_default_version = material_storage->shaders.scene_shader.version_create(); material_storage->shaders.scene_shader.version_bind_shader(scene_globals.shader_default_version, SceneShaderGLES3::MODE_COLOR); @@ -2687,6 +4021,29 @@ void fragment() { scene_globals.default_material = material_storage->material_allocate(); material_storage->material_initialize(scene_globals.default_material); material_storage->material_set_shader(scene_globals.default_material, scene_globals.default_shader); + default_material_data_ptr = static_cast<GLES3::SceneMaterialData *>(GLES3::MaterialStorage::get_singleton()->material_get_data(scene_globals.default_material, RS::SHADER_SPATIAL)); + } + + { + // Overdraw material and shader. + scene_globals.overdraw_shader = material_storage->shader_allocate(); + material_storage->shader_initialize(scene_globals.overdraw_shader); + material_storage->shader_set_code(scene_globals.overdraw_shader, R"( +// 3D editor Overdraw debug draw mode shader. + +shader_type spatial; + +render_mode blend_add, unshaded; + +void fragment() { + ALBEDO = vec3(0.4, 0.8, 0.8); + ALPHA = 0.2; +} +)"); + scene_globals.overdraw_material = material_storage->material_allocate(); + material_storage->material_initialize(scene_globals.overdraw_material); + material_storage->material_set_shader(scene_globals.overdraw_material, scene_globals.overdraw_shader); + overdraw_material_data_ptr = static_cast<GLES3::SceneMaterialData *>(GLES3::MaterialStorage::get_singleton()->material_get_data(scene_globals.overdraw_material, RS::SHADER_SPATIAL)); } { @@ -2771,9 +4128,11 @@ void sky() { glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind } -#ifdef GLES_OVER_GL - glEnable(_EXT_TEXTURE_CUBE_MAP_SEAMLESS); -#endif +#ifdef GL_API_ENABLED + if (RasterizerGLES3::is_gles_over_gl()) { + glEnable(_EXT_TEXTURE_CUBE_MAP_SEAMLESS); + } +#endif // GL_API_ENABLED // MultiMesh may read from color when color is disabled, so make sure that the color defaults to white instead of black; glVertexAttrib4f(RS::ARRAY_COLOR, 1.0, 1.0, 1.0, 1.0); @@ -2783,11 +4142,15 @@ RasterizerSceneGLES3::~RasterizerSceneGLES3() { GLES3::Utilities::get_singleton()->buffer_free_data(scene_state.directional_light_buffer); GLES3::Utilities::get_singleton()->buffer_free_data(scene_state.omni_light_buffer); GLES3::Utilities::get_singleton()->buffer_free_data(scene_state.spot_light_buffer); + GLES3::Utilities::get_singleton()->buffer_free_data(scene_state.positional_shadow_buffer); + GLES3::Utilities::get_singleton()->buffer_free_data(scene_state.directional_shadow_buffer); memdelete_arr(scene_state.directional_lights); memdelete_arr(scene_state.omni_lights); memdelete_arr(scene_state.spot_lights); memdelete_arr(scene_state.omni_light_sort); memdelete_arr(scene_state.spot_light_sort); + memdelete_arr(scene_state.positional_shadows); + memdelete_arr(scene_state.directional_shadows); // Scene Shader GLES3::MaterialStorage::get_singleton()->shaders.scene_shader.version_free(scene_globals.shader_default_version); @@ -2795,6 +4158,10 @@ RasterizerSceneGLES3::~RasterizerSceneGLES3() { RSG::material_storage->material_free(scene_globals.default_material); RSG::material_storage->shader_free(scene_globals.default_shader); + // Overdraw Shader + RSG::material_storage->material_free(scene_globals.overdraw_material); + RSG::material_storage->shader_free(scene_globals.overdraw_shader); + // Sky Shader GLES3::MaterialStorage::get_singleton()->shaders.sky_shader.version_free(sky_globals.shader_default_version); RSG::material_storage->material_free(sky_globals.default_material); |