godot/servers/rendering/renderer_rd/renderer_compositor_rd.cpp

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

354 lines
16 KiB
C++
Raw Normal View History

/**************************************************************************/
2020-12-04 15:26:24 -03:00
/* renderer_compositor_rd.cpp */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
2020-12-04 15:26:24 -03:00
#include "renderer_compositor_rd.h"
#include "core/config/project_settings.h"
#include "core/io/dir_access.h"
#include "servers/rendering/renderer_rd/forward_clustered/render_forward_clustered.h"
#include "servers/rendering/renderer_rd/forward_mobile/render_forward_mobile.h"
2020-12-04 15:26:24 -03:00
void RendererCompositorRD::blit_render_targets_to_screen(DisplayServer::WindowID p_screen, const BlitToScreen *p_render_targets, int p_amount) {
Error err = RD::get_singleton()->screen_prepare_for_drawing(p_screen);
if (err != OK) {
// Window is minimized and does not have valid swapchain, skip drawing without printing errors.
return;
}
RD::DrawListID draw_list = RD::get_singleton()->draw_list_begin_for_screen(p_screen);
ERR_FAIL_COND(draw_list == RD::INVALID_ID);
for (int i = 0; i < p_amount; i++) {
RID rd_texture = texture_storage->render_target_get_rd_texture(p_render_targets[i].render_target);
ERR_CONTINUE(rd_texture.is_null());
2021-05-11 23:08:38 +10:00
HashMap<RID, RID>::Iterator it = render_target_descriptors.find(rd_texture);
if (it == render_target_descriptors.end() || !RD::get_singleton()->uniform_set_is_valid(it->value)) {
Vector<RD::Uniform> uniforms;
RD::Uniform u;
u.uniform_type = RD::UNIFORM_TYPE_SAMPLER_WITH_TEXTURE;
u.binding = 0;
u.append_id(blit.sampler);
u.append_id(rd_texture);
uniforms.push_back(u);
2021-05-11 23:08:38 +10:00
RID uniform_set = RD::get_singleton()->uniform_set_create(uniforms, blit.shader.version_get_shader(blit.shader_version, BLIT_MODE_NORMAL), 0);
it = render_target_descriptors.insert(rd_texture, uniform_set);
}
Size2 screen_size(RD::get_singleton()->screen_get_width(p_screen), RD::get_singleton()->screen_get_height(p_screen));
BlitMode mode = p_render_targets[i].lens_distortion.apply ? BLIT_MODE_LENS : (p_render_targets[i].multi_view.use_layer ? BLIT_MODE_USE_LAYER : BLIT_MODE_NORMAL);
2021-05-11 23:08:38 +10:00
RD::get_singleton()->draw_list_bind_render_pipeline(draw_list, blit.pipelines[mode]);
RD::get_singleton()->draw_list_bind_index_array(draw_list, blit.array);
RD::get_singleton()->draw_list_bind_uniform_set(draw_list, it->value, 0);
// We need to invert the phone rotation.
const int screen_rotation_degrees = -RD::get_singleton()->screen_get_pre_rotation_degrees(p_screen);
float screen_rotation = Math::deg_to_rad((float)screen_rotation_degrees);
blit.push_constant.rotation_cos = Math::cos(screen_rotation);
blit.push_constant.rotation_sin = Math::sin(screen_rotation);
// Swap width and height when the orientation is not the native one.
if (screen_rotation_degrees % 180 != 0) {
SWAP(screen_size.width, screen_size.height);
}
2021-08-29 14:52:43 +10:00
blit.push_constant.src_rect[0] = p_render_targets[i].src_rect.position.x;
blit.push_constant.src_rect[1] = p_render_targets[i].src_rect.position.y;
blit.push_constant.src_rect[2] = p_render_targets[i].src_rect.size.width;
blit.push_constant.src_rect[3] = p_render_targets[i].src_rect.size.height;
blit.push_constant.dst_rect[0] = p_render_targets[i].dst_rect.position.x / screen_size.width;
blit.push_constant.dst_rect[1] = p_render_targets[i].dst_rect.position.y / screen_size.height;
blit.push_constant.dst_rect[2] = p_render_targets[i].dst_rect.size.width / screen_size.width;
blit.push_constant.dst_rect[3] = p_render_targets[i].dst_rect.size.height / screen_size.height;
2021-05-11 23:08:38 +10:00
blit.push_constant.layer = p_render_targets[i].multi_view.layer;
blit.push_constant.eye_center[0] = p_render_targets[i].lens_distortion.eye_center.x;
blit.push_constant.eye_center[1] = p_render_targets[i].lens_distortion.eye_center.y;
blit.push_constant.k1 = p_render_targets[i].lens_distortion.k1;
blit.push_constant.k2 = p_render_targets[i].lens_distortion.k2;
blit.push_constant.upscale = p_render_targets[i].lens_distortion.upscale;
blit.push_constant.aspect_ratio = p_render_targets[i].lens_distortion.aspect_ratio;
blit.push_constant.convert_to_srgb = texture_storage->render_target_is_using_hdr(p_render_targets[i].render_target);
blit.push_constant.use_debanding = texture_storage->render_target_is_using_debanding(p_render_targets[i].render_target);
2021-05-11 23:08:38 +10:00
RD::get_singleton()->draw_list_set_push_constant(draw_list, &blit.push_constant, sizeof(BlitPushConstant));
RD::get_singleton()->draw_list_draw(draw_list, true);
}
RD::get_singleton()->draw_list_end();
}
2020-12-04 15:26:24 -03:00
void RendererCompositorRD::begin_frame(double frame_step) {
frame++;
delta = frame_step;
time += frame_step;
double time_roll_over = GLOBAL_GET_CACHED(double, "rendering/limits/time/time_rollover_secs");
time = Math::fmod(time, time_roll_over);
canvas->set_time(time);
2020-01-11 22:26:52 -03:00
scene->set_time(time, frame_step);
}
Keep processing Graphics if there are pending operations Fixes #90017 Fixes #90030 Fixes #98044 This PR makes the following changes: # Force processing of GPU commands for frame_count frames The variable `frames_pending_resources_for_processing` is added to track this. The ticket #98044 suggested to use `_flush_and_stall_for_all_frames()` while minimized. Technically this works and is a viable solution. However I noticed that this issue was happening because Logic/Physics continue to work "business as usual" while minimized(\*). Only Graphics was being deactivated (which caused commands to accumulate until window is restored). To continue this behavior of "business as usual", I decided that GPU work should also "continue as usual" by buffering commands in a double or triple buffer scheme until all commands are done processing (if they ever stop coming). This is specially important if the app specifically intends to keep processing while minimized. Calling `_flush_and_stall_for_all_frames()` would fix the leak, but it would make Godot's behavior different while minimized vs while the window is presenting. \* `OS::add_frame_delay` _does_ consider being minimized, but it just throttles CPU usage. Some platforms such as Android completely disable processing because the higher level code stops being called when the app goes into background. But this seems like an implementation-detail that diverges from the rest of the platforms (e.g. Windows, Linux & macOS continue to process while minimized). # Rename p_swap_buffers for p_present **This is potentially a breaking change** (if it actually breaks anything, I ignore. But I strongly suspect it doesn't break anything). "Swap Buffers" is a concept carried from OpenGL, where a frame is "done" when `glSwapBuffers()` is called, which basically means "present to the screen". However it _also_ means that OpenGL internally swaps its internal buffers in a double/triple buffer scheme (in Vulkan, we do that ourselves and is tracked by `RenderingDevice::frame`). Modern APIs like Vulkan differentiate between "submitting GPU work" and "presenting". Before this PR, calling `RendererCompositorRD::end_frame(false)` would literally do nothing. This is often undesired and the cause of the leak. After this PR, calling `RendererCompositorRD::end_frame(false)` will now process commands, swap our internal buffers in a double/triple buffer scheme **but avoid presenting to the screen**. Hence the rename of the variable from `p_swap_buffers` to `p_present` (which slightly alters its behavior). If we want `RendererCompositorRD::end_frame(false)` to do nothing, then we should not call it at all. This PR reflects such change: When we're minimized **_and_** `has_pending_resources_for_processing()` returns false, we don't call `RendererCompositorRD::end_frame()` at all. But if `has_pending_resources_for_processing()` returns true, we will call it, but with `p_present = false` because we're minimized. There's still the issue that Godot keeps processing work (logic, scripts, physics) while minimized, which we shouldn't do by default. But that's work for follow up PR.
2024-12-10 19:25:46 -03:00
void RendererCompositorRD::end_frame(bool p_present) {
RD::get_singleton()->swap_buffers(p_present);
}
2020-12-04 15:26:24 -03:00
void RendererCompositorRD::initialize() {
2021-05-11 23:08:38 +10:00
{
// Initialize blit
Vector<String> blit_modes;
blit_modes.push_back("\n");
blit_modes.push_back("\n#define USE_LAYER\n");
blit_modes.push_back("\n#define USE_LAYER\n#define APPLY_LENS_DISTORTION\n");
blit_modes.push_back("\n");
2021-05-11 23:08:38 +10:00
blit.shader.initialize(blit_modes);
blit.shader_version = blit.shader.version_create();
for (int i = 0; i < BLIT_MODE_MAX; i++) {
blit.pipelines[i] = RD::get_singleton()->render_pipeline_create(blit.shader.version_get_shader(blit.shader_version, i), RD::get_singleton()->screen_get_framebuffer_format(DisplayServer::MAIN_WINDOW_ID), RD::INVALID_ID, RD::RENDER_PRIMITIVE_TRIANGLES, RD::PipelineRasterizationState(), RD::PipelineMultisampleState(), RD::PipelineDepthStencilState(), i == BLIT_MODE_NORMAL_ALPHA ? RenderingDevice::PipelineColorBlendState::create_blend() : RenderingDevice::PipelineColorBlendState::create_disabled(), 0);
Improvements from TheForge (see description) The work was performed by collaboration of TheForge and Google. I am merely splitting it up into smaller PRs and cleaning it up. This is the most "risky" PR so far because the previous ones have been miscellaneous stuff aimed at either [improve debugging](https://github.com/godotengine/godot/pull/90993) (e.g. device lost), [improve Android experience](https://github.com/godotengine/godot/pull/96439) (add Swappy for better Frame Pacing + Pre-Transformed Swapchains for slightly better performance), or harmless [ASTC improvements](https://github.com/godotengine/godot/pull/96045) (better performance by simply toggling a feature when available). However this PR contains larger modifications aimed at improving performance or reducing memory fragmentation. With greater modifications, come greater risks of bugs or breakage. Changes introduced by this PR: TBDR GPUs (e.g. most of Android + iOS + M1 Apple) support rendering to Render Targets that are not backed by actual GPU memory (everything stays in cache). This works as long as load action isn't `LOAD`, and store action must be `DONT_CARE`. This saves VRAM (it also makes painfully obvious when a mistake introduces a performance regression). Of particular usefulness is when doing MSAA and keeping the raw MSAA content is not necessary. Some GPUs get faster when the sampler settings are hard-coded into the GLSL shaders (instead of being dynamically bound at runtime). This required changes to the GLSL shaders, PSO creation routines, Descriptor creation routines, and Descriptor binding routines. - `bool immutable_samplers_enabled = true` Setting it to false enforces the old behavior. Useful for debugging bugs and regressions. Immutable samplers requires that the samplers stay... immutable, hence this boolean is useful if the promise gets broken. We might want to turn this into a `GLOBAL_DEF` setting. Instead of creating dozen/hundreds/thousands of `VkDescriptorSet` every frame that need to be freed individually when they are no longer needed, they all get freed at once by resetting the whole pool. Once the whole pool is no longer in use by the GPU, it gets reset and its memory recycled. Descriptor sets that are created to be kept around for longer or forever (i.e. not created and freed within the same frame) **must not** use linear pools. There may be more than one pool per frame. How many pools per frame Godot ends up with depends on its capacity, and that is controlled by `rendering/rendering_device/vulkan/max_descriptors_per_pool`. - **Possible improvement for later:** It should be possible for Godot to adapt to how many descriptors per pool are needed on a per-key basis (i.e. grow their capacity like `std::vector` does) after rendering a few frames; which would be better than the current solution of having a single global value for all pools (`max_descriptors_per_pool`) that the user needs to tweak. - `bool linear_descriptor_pools_enabled = true` Setting it to false enforces the old behavior. Useful for debugging bugs and regressions. Setting it to false is required when workarounding driver bugs (e.g. Adreno 730). A ridiculous optimization. Ridiculous because the original code should've done this in the first place. Previously Godot was doing the following: 1. Create a command buffer **pool**. One per frame. 2. Create multiple command buffers from the pool in point 1. 3. Call `vkBeginCommandBuffer` on the cmd buffer in point 2. This resets the cmd buffer because Godot requests the `VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT` flag. 4. Add commands to the cmd buffers from point 2. 5. Submit those commands. 6. On frame N + 2, recycle the buffer pool and cmd buffers from pt 1 & 2, and repeat from step 3. The problem here is that step 3 resets each command buffer individually. Initially Godot used to have 1 cmd buffer per pool, thus the impact is very low. But not anymore (specially with Adreno workarounds to force splitting compute dispatches into a new cmd buffer, more on this later). However Godot keeps around a very low amount of command buffers per frame. The recommended method is to reset the whole pool, to reset all cmd buffers at once. Hence the new steps would be: 1. Create a command buffer **pool**. One per frame. 2. Create multiple command buffers from the pool in point 1. 3. Call `vkBeginCommandBuffer` on the cmd buffer in point 2, which is already reset/empty (see step 6). 4. Add commands to the cmd buffers from point 2. 5. Submit those commands. 6. On frame N + 2, recycle the buffer pool and cmd buffers from pt 1 & 2, call `vkResetCommandPool` and repeat from step 3. **Possible issues:** @dariosamo added `transfer_worker` which creates a command buffer pool: ```cpp transfer_worker->command_pool = driver->command_pool_create(transfer_queue_family, RDD::COMMAND_BUFFER_TYPE_PRIMARY); ``` As expected, validation was complaining that command buffers were being reused without being reset (that's good, we now know Validation Layers will warn us of wrong use). I fixed it by adding: ```cpp void RenderingDevice::_wait_for_transfer_worker(TransferWorker *p_transfer_worker) { driver->fence_wait(p_transfer_worker->command_fence); driver->command_pool_reset(p_transfer_worker->command_pool); // ! New line ! ``` **Secondary cmd buffers are subject to the same issue but I didn't alter them. I talked this with Dario and he is aware of this.** Secondary cmd buffers are currently disabled due to other issues (it's disabled on master). - `bool RenderingDeviceCommons::command_pool_reset_enabled` Setting it to false enforces the old behavior. Useful for debugging bugs and regressions. There's no other reason for this boolean. Possibly once it becomes well tested, the boolean could be removed entirely. Adds `command_bind_render_uniform_sets` and `add_draw_list_bind_uniform_sets` (+ compute variants). It performs the same as `add_draw_list_bind_uniform_set` (notice singular vs plural), but on multiple consecutive uniform sets, thus reducing graph and draw call overhead. - `bool descriptor_set_batching = true;` Setting it to false enforces the old behavior. Useful for debugging bugs and regressions. There's no other reason for this boolean. Possibly once it becomes well tested, the boolean could be removed entirely. Godot currently does the following: 1. Fill the entire cmd buffer with commands. 2. `submit()` - Wait with a semaphore for the swapchain. - Trigger a semaphore to indicate when we're done (so the swapchain can submit). 3. `present()` The optimization opportunity here is that 95% of Godot's rendering is done offscreen. Then a fullscreen pass copies everything to the swapchain. Godot doesn't practically render directly to the swapchain. The problem with this is that the GPU has to wait for the swapchain to be released **to start anything**, when we could start *much earlier*. Only the final blit pass must wait for the swapchain. TheForge changed it to the following (more complicated, I'm simplifying the idea): 1. Fill the entire cmd buffer with commands. 2. In `screen_prepare_for_drawing` do `submit()` - There are no semaphore waits for the swapchain. - Trigger a semaphore to indicate when we're done. 3. Fill a new cmd buffer that only does the final blit to the swapchain. 4. `submit()` - Wait with a semaphore for the submit() from step 2. - Wait with a semaphore for the swapchain (so the swapchain can submit). - Trigger a semaphore to indicate when we're done (so the swapchain can submit). 5. `present()` Dario discovered this problem independently while working on a different platform. **However TheForge's solution had to be rewritten from scratch:** The complexity to achieve the solution was high and quite difficult to maintain with the way Godot works now (after Übershaders PR). But on the other hand, re-implementing the solution became much simpler because Dario already had to do something similar: To fix an Adreno 730 driver bug, he had to implement splitting command buffers. **This is exactly what we need!**. Thus it was re-written using this existing functionality for a new purpose. To achieve this, I added a new argument, `bool p_split_cmd_buffer`, to `RenderingDeviceGraph::add_draw_list_begin`, which is only set to true by `RenderingDevice::draw_list_begin_for_screen`. The graph will split the draw list into its own command buffer. - `bool split_swapchain_into_its_own_cmd_buffer = true;` Setting it to false enforces the old behavior. This might be necessary for consoles which follow an alternate solution to the same problem. If not, then we should consider removing it. PR #90993 added `shader_destroy_modules()` but it was not actually in use. This PR adds several places where `shader_destroy_modules()` is called after initialization to free up memory of SPIR-V structures that are no longer needed.
2024-11-14 13:03:14 -03:00
// Unload shader modules to save memory.
RD::get_singleton()->shader_destroy_modules(blit.shader.version_get_shader(blit.shader_version, i));
}
2021-05-11 23:08:38 +10:00
//create index array for copy shader
Vector<uint8_t> pv;
pv.resize(6 * 2);
{
uint8_t *w = pv.ptrw();
uint16_t *p16 = (uint16_t *)w;
p16[0] = 0;
p16[1] = 1;
p16[2] = 2;
p16[3] = 0;
p16[4] = 2;
p16[5] = 3;
}
blit.index_buffer = RD::get_singleton()->index_buffer_create(6, RenderingDevice::INDEX_BUFFER_FORMAT_UINT16, pv);
2021-05-11 23:08:38 +10:00
blit.array = RD::get_singleton()->index_array_create(blit.index_buffer, 0, 6);
2021-05-11 23:08:38 +10:00
blit.sampler = RD::get_singleton()->sampler_create(RD::SamplerState());
}
}
2020-12-04 15:26:24 -03:00
uint64_t RendererCompositorRD::frame = 1;
2020-12-04 15:26:24 -03:00
void RendererCompositorRD::finalize() {
memdelete(scene);
memdelete(canvas);
memdelete(fog);
2022-04-12 21:41:50 +10:00
memdelete(particles_storage);
memdelete(light_storage);
memdelete(mesh_storage);
memdelete(material_storage);
memdelete(texture_storage);
memdelete(utilities);
//only need to erase these, the rest are erased by cascade
2021-05-11 23:08:38 +10:00
blit.shader.version_free(blit.shader_version);
RD::get_singleton()->free(blit.index_buffer);
RD::get_singleton()->free(blit.sampler);
}
void RendererCompositorRD::set_boot_image(const Ref<Image> &p_image, const Color &p_color, bool p_scale, bool p_use_filter) {
if (p_image.is_null() || p_image->is_empty()) {
return;
}
Error err = RD::get_singleton()->screen_prepare_for_drawing(DisplayServer::MAIN_WINDOW_ID);
if (err != OK) {
// Window is minimized and does not have valid swapchain, skip drawing without printing errors.
return;
}
RID texture = texture_storage->texture_allocate();
texture_storage->texture_2d_initialize(texture, p_image);
RID rd_texture = texture_storage->texture_get_rd_texture(texture, false);
RD::SamplerState sampler_state;
sampler_state.min_filter = p_use_filter ? RD::SAMPLER_FILTER_LINEAR : RD::SAMPLER_FILTER_NEAREST;
sampler_state.mag_filter = p_use_filter ? RD::SAMPLER_FILTER_LINEAR : RD::SAMPLER_FILTER_NEAREST;
sampler_state.max_lod = 0;
RID sampler = RD::get_singleton()->sampler_create(sampler_state);
RID uset;
{
Vector<RD::Uniform> uniforms;
RD::Uniform u;
u.uniform_type = RD::UNIFORM_TYPE_SAMPLER_WITH_TEXTURE;
u.binding = 0;
u.append_id(sampler);
u.append_id(rd_texture);
uniforms.push_back(u);
uset = RD::get_singleton()->uniform_set_create(uniforms, blit.shader.version_get_shader(blit.shader_version, BLIT_MODE_NORMAL), 0);
}
Size2 window_size = DisplayServer::get_singleton()->window_get_size();
Rect2 imgrect(0, 0, p_image->get_width(), p_image->get_height());
Rect2 screenrect;
if (p_scale) {
screenrect = OS::get_singleton()->calculate_boot_screen_rect(window_size, imgrect.size);
} else {
screenrect = imgrect;
screenrect.position += ((window_size - screenrect.size) / 2.0).floor();
}
screenrect.position /= window_size;
screenrect.size /= window_size;
RD::DrawListID draw_list = RD::get_singleton()->draw_list_begin_for_screen(DisplayServer::MAIN_WINDOW_ID, p_color);
RD::get_singleton()->draw_list_bind_render_pipeline(draw_list, blit.pipelines[BLIT_MODE_NORMAL_ALPHA]);
RD::get_singleton()->draw_list_bind_index_array(draw_list, blit.array);
RD::get_singleton()->draw_list_bind_uniform_set(draw_list, uset, 0);
const int screen_rotation_degrees = -RD::get_singleton()->screen_get_pre_rotation_degrees(DisplayServer::MAIN_WINDOW_ID);
float screen_rotation = Math::deg_to_rad((float)screen_rotation_degrees);
blit.push_constant.rotation_cos = Math::cos(screen_rotation);
blit.push_constant.rotation_sin = Math::sin(screen_rotation);
2021-08-29 14:52:43 +10:00
blit.push_constant.src_rect[0] = 0.0;
blit.push_constant.src_rect[1] = 0.0;
blit.push_constant.src_rect[2] = 1.0;
blit.push_constant.src_rect[3] = 1.0;
blit.push_constant.dst_rect[0] = screenrect.position.x;
blit.push_constant.dst_rect[1] = screenrect.position.y;
blit.push_constant.dst_rect[2] = screenrect.size.width;
blit.push_constant.dst_rect[3] = screenrect.size.height;
blit.push_constant.layer = 0;
blit.push_constant.eye_center[0] = 0;
blit.push_constant.eye_center[1] = 0;
blit.push_constant.k1 = 0;
blit.push_constant.k2 = 0;
blit.push_constant.upscale = 1.0;
blit.push_constant.aspect_ratio = 1.0;
blit.push_constant.convert_to_srgb = false;
blit.push_constant.use_debanding = false;
RD::get_singleton()->draw_list_set_push_constant(draw_list, &blit.push_constant, sizeof(BlitPushConstant));
RD::get_singleton()->draw_list_draw(draw_list, true);
RD::get_singleton()->draw_list_end();
Keep processing Graphics if there are pending operations Fixes #90017 Fixes #90030 Fixes #98044 This PR makes the following changes: # Force processing of GPU commands for frame_count frames The variable `frames_pending_resources_for_processing` is added to track this. The ticket #98044 suggested to use `_flush_and_stall_for_all_frames()` while minimized. Technically this works and is a viable solution. However I noticed that this issue was happening because Logic/Physics continue to work "business as usual" while minimized(\*). Only Graphics was being deactivated (which caused commands to accumulate until window is restored). To continue this behavior of "business as usual", I decided that GPU work should also "continue as usual" by buffering commands in a double or triple buffer scheme until all commands are done processing (if they ever stop coming). This is specially important if the app specifically intends to keep processing while minimized. Calling `_flush_and_stall_for_all_frames()` would fix the leak, but it would make Godot's behavior different while minimized vs while the window is presenting. \* `OS::add_frame_delay` _does_ consider being minimized, but it just throttles CPU usage. Some platforms such as Android completely disable processing because the higher level code stops being called when the app goes into background. But this seems like an implementation-detail that diverges from the rest of the platforms (e.g. Windows, Linux & macOS continue to process while minimized). # Rename p_swap_buffers for p_present **This is potentially a breaking change** (if it actually breaks anything, I ignore. But I strongly suspect it doesn't break anything). "Swap Buffers" is a concept carried from OpenGL, where a frame is "done" when `glSwapBuffers()` is called, which basically means "present to the screen". However it _also_ means that OpenGL internally swaps its internal buffers in a double/triple buffer scheme (in Vulkan, we do that ourselves and is tracked by `RenderingDevice::frame`). Modern APIs like Vulkan differentiate between "submitting GPU work" and "presenting". Before this PR, calling `RendererCompositorRD::end_frame(false)` would literally do nothing. This is often undesired and the cause of the leak. After this PR, calling `RendererCompositorRD::end_frame(false)` will now process commands, swap our internal buffers in a double/triple buffer scheme **but avoid presenting to the screen**. Hence the rename of the variable from `p_swap_buffers` to `p_present` (which slightly alters its behavior). If we want `RendererCompositorRD::end_frame(false)` to do nothing, then we should not call it at all. This PR reflects such change: When we're minimized **_and_** `has_pending_resources_for_processing()` returns false, we don't call `RendererCompositorRD::end_frame()` at all. But if `has_pending_resources_for_processing()` returns true, we will call it, but with `p_present = false` because we're minimized. There's still the issue that Godot keeps processing work (logic, scripts, physics) while minimized, which we shouldn't do by default. But that's work for follow up PR.
2024-12-10 19:25:46 -03:00
RD::get_singleton()->swap_buffers(true);
texture_storage->texture_free(texture);
RD::get_singleton()->free(sampler);
}
2020-12-04 15:26:24 -03:00
RendererCompositorRD *RendererCompositorRD::singleton = nullptr;
2020-12-04 15:26:24 -03:00
RendererCompositorRD::RendererCompositorRD() {
uniform_set_cache = memnew(UniformSetCacheRD);
framebuffer_cache = memnew(FramebufferCacheRD);
bool shader_cache_enabled = GLOBAL_GET("rendering/shader_compiler/shader_cache/enabled");
bool compress = GLOBAL_GET("rendering/shader_compiler/shader_cache/compress");
bool use_zstd = GLOBAL_GET("rendering/shader_compiler/shader_cache/use_zstd_compression");
bool strip_debug = GLOBAL_GET("rendering/shader_compiler/shader_cache/strip_debug");
ShaderRD::set_shader_cache_save_compressed(compress);
ShaderRD::set_shader_cache_save_compressed_zstd(use_zstd);
ShaderRD::set_shader_cache_save_debug(!strip_debug);
// Shader cache is forcefully enabled when running the editor.
if (shader_cache_enabled || Engine::get_singleton()->is_editor_hint()) {
// Attempt to create a folder for the shader cache that the user can write to. Shaders will only be attempted to be saved if this path exists.
String shader_cache_user_dir = Engine::get_singleton()->get_shader_cache_path();
if (shader_cache_user_dir.is_empty()) {
shader_cache_user_dir = "user://";
}
Ref<DirAccess> user_da = DirAccess::open(shader_cache_user_dir);
if (user_da.is_null()) {
ERR_PRINT("Can't create shader cache folder, no shader caching will happen: " + shader_cache_user_dir);
} else {
Error err = user_da->change_dir("shader_cache");
if (err != OK) {
err = user_da->make_dir("shader_cache");
}
if (err != OK) {
ERR_PRINT("Can't create shader cache folder, no shader caching will happen: " + shader_cache_user_dir);
} else {
shader_cache_user_dir = shader_cache_user_dir.path_join("shader_cache");
ShaderRD::set_shader_cache_user_dir(shader_cache_user_dir);
}
}
// Check if a directory exists for the shader cache to pull shaders from as read-only. This is used on exported projects with baked shaders.
String shader_cache_res_dir = "res://.godot/shader_cache";
Ref<DirAccess> res_da = DirAccess::open(shader_cache_res_dir);
if (res_da.is_valid()) {
ShaderRD::set_shader_cache_res_dir(shader_cache_res_dir);
}
}
ERR_FAIL_COND_MSG(singleton != nullptr, "A RendererCompositorRD singleton already exists.");
singleton = this;
utilities = memnew(RendererRD::Utilities);
texture_storage = memnew(RendererRD::TextureStorage);
material_storage = memnew(RendererRD::MaterialStorage);
mesh_storage = memnew(RendererRD::MeshStorage);
light_storage = memnew(RendererRD::LightStorage);
2022-04-12 21:41:50 +10:00
particles_storage = memnew(RendererRD::ParticlesStorage);
fog = memnew(RendererRD::Fog);
canvas = memnew(RendererCanvasRenderRD());
2021-03-10 22:23:55 +11:00
String rendering_method = OS::get_singleton()->get_current_rendering_method();
uint64_t textures_per_stage = RD::get_singleton()->limit_get(RD::LIMIT_MAX_TEXTURES_PER_SHADER_STAGE);
2021-03-10 22:23:55 +11:00
if (rendering_method == "mobile" || textures_per_stage < 48) {
if (rendering_method == "forward_plus") {
WARN_PRINT_ONCE("Platform supports less than 48 textures per stage which is less than required by the Clustered renderer. Defaulting to Mobile renderer.");
}
scene = memnew(RendererSceneRenderImplementation::RenderForwardMobile());
} else if (rendering_method == "forward_plus") {
scene = memnew(RendererSceneRenderImplementation::RenderForwardClustered());
} else {
// Fall back to our high end renderer.
ERR_PRINT(vformat("Cannot instantiate RenderingDevice-based renderer with renderer type '%s'. Defaulting to Forward+ renderer.", rendering_method));
scene = memnew(RendererSceneRenderImplementation::RenderForwardClustered());
2021-03-10 22:23:55 +11:00
}
scene->init();
}
RendererCompositorRD::~RendererCompositorRD() {
singleton = nullptr;
memdelete(uniform_set_cache);
memdelete(framebuffer_cache);
ShaderRD::set_shader_cache_user_dir(String());
ShaderRD::set_shader_cache_res_dir(String());
}