From 605e76a1541c85a718c980044dfaa094315f3450 Mon Sep 17 00:00:00 2001 From: Chinmay Garde Date: Mon, 27 Feb 2023 21:14:06 -0800 Subject: [PATCH] [Impeller] Patch up sundry issues in the Vulkan backend. (flutter/engine#39905) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Kaushik already did most of the great work. This patch gets us to a point where all the playgrounds tests pass and the common performance optimizations are in place. All known non-compute Impeller features should be implemented. There are iOS only performance optimizations that haven’t been opted into because these are behind define guards. These need to be generalized. Without that, the performance of this backend will lag behind that of the Metal backend but only because it is not an apples to apples comparison. The general rubric was to keep the code and concepts as similar to the Metal backend as possible. The list of updates, all to the Vulkan Impeller backend: * MSAA is wired up. * Depth and stencil attachments and pipeline states are wired up. * Got rid of Vulkan specific hacks in the inline pass context that were preventing clips from working. * Storage modes for both device buffer and texture allocation are respected. This includes optimal usage of tile memory for device transient attachments. * Host coherent memory for textures is no longer a requirement with explicit mapping management and write flushes. * Texture uploads should be optimized for the UMA case without needing a staging buffer. That entire pipeline has been reworked. * Textures track their current layout and ensure they get to the right layout based on usage without redundant transitions. * Cube textures are now supported. * Mipmapping has been reworked to correct image layout errors. With the new texture layout transition management, blit passes should be a whole lot easier to read and reason about. * Allocator allocations are named using Vulkan debug utilities and the allocator (VMA). Comes in handy when chasing leaks. All of which are chased down. * Left some handy utilities in there to debug resource leaks after context shutdown. These are validation errors. * Debug groups are pushed around render pass command encoding as well as the entire pass contents. This mimics the behavior of the Metal backend and it should be easy to map traces using both backends in Xcode and RenderDoc. * Command buffer submission allows for tracking the life cycles of all resources referenced in the command stream and ensuring that the objects stay alive till past the submission of the command buffer. All use-after-free issues due to this class of issue have been chased down. * Command pools are now context global instead of being created per pass. * Descriptor pool are now context global instead of being created per pass. Individual descriptor types are now reference counted and returned to the pool when not needed. The pool is still fixed size though (and hence relatively large). * All instances of global waitIdle on the device are removed during normal operation. The only times a waitIdle may happen is during swapchain recreation and context destruction. * Swapchain adapt to them going out of date with the underlying surface and seamlessly resize as necessary on the next drawable acquisition. * Playgrounds are resizable. * Pipeline front face and cull modes are respected. * Clears for all attachments are respected. * Maximum textures sizes supported on the device are respected instead of hardcoding the minimum Vulkan requirement. Fixes https://github.com/flutter/flutter/issues/112388 Fixes https://github.com/flutter/flutter/issues/112648 Fixes https://github.com/flutter/flutter/issues/112647 and a few other issues... --- .../ci/licenses_golden/licenses_flutter | 48 +- engine/src/flutter/flutter_vma/flutter_vma.cc | 15 + .../impeller/entity/inline_pass_context.cc | 6 - .../backend/vulkan/playground_impl_vk.cc | 36 +- .../backend/vulkan/playground_impl_vk.h | 6 +- .../renderer/backend/metal/surface_mtl.mm | 66 +- .../renderer/backend/metal/texture_mtl.mm | 4 - .../impeller/renderer/backend/vulkan/BUILD.gn | 24 +- .../renderer/backend/vulkan/allocator_vk.cc | 418 ++++++--- .../renderer/backend/vulkan/allocator_vk.h | 7 +- .../backend/vulkan/blit_command_vk.cc | 354 ++++---- .../renderer/backend/vulkan/blit_command_vk.h | 16 +- .../renderer/backend/vulkan/blit_pass_vk.cc | 17 +- .../renderer/backend/vulkan/blit_pass_vk.h | 9 +- .../backend/vulkan/command_buffer_vk.cc | 117 +-- .../backend/vulkan/command_buffer_vk.h | 30 +- .../backend/vulkan/command_encoder_vk.cc | 120 +++ .../backend/vulkan/command_encoder_vk.h | 57 ++ .../backend/vulkan/command_pool_vk.cc | 33 - .../renderer/backend/vulkan/command_pool_vk.h | 29 - .../renderer/backend/vulkan/commands_vk.cc | 71 -- .../renderer/backend/vulkan/commands_vk.h | 33 - .../renderer/backend/vulkan/context_vk.cc | 194 +++-- .../renderer/backend/vulkan/context_vk.h | 85 +- .../backend/vulkan/deletion_queue_vk.cc | 27 - .../backend/vulkan/deletion_queue_vk.h | 32 - .../backend/vulkan/descriptor_pool_vk.cc | 53 -- .../backend/vulkan/descriptor_pool_vk.h | 31 - .../backend/vulkan/device_buffer_vk.cc | 51 +- .../backend/vulkan/device_buffer_vk.h | 32 +- .../vulkan/fenced_command_buffer_vk.cc | 101 --- .../backend/vulkan/fenced_command_buffer_vk.h | 44 - .../renderer/backend/vulkan/formats_vk.cc | 27 +- .../renderer/backend/vulkan/formats_vk.h | 212 ++++- .../backend/vulkan/pipeline_library_vk.cc | 211 +++-- .../backend/vulkan/pipeline_library_vk.h | 3 +- .../renderer/backend/vulkan/pipeline_vk.cc | 2 +- .../renderer/backend/vulkan/pipeline_vk.h | 2 +- .../renderer/backend/vulkan/render_pass_vk.cc | 815 +++++++++++------- .../renderer/backend/vulkan/render_pass_vk.h | 46 +- .../renderer/backend/vulkan/sampler_vk.cc | 19 +- .../renderer/backend/vulkan/sampler_vk.h | 5 +- .../backend/vulkan/shared_object_vk.cc | 11 + .../backend/vulkan/shared_object_vk.h | 43 + .../backend/vulkan/surface_producer_vk.cc | 196 ----- .../backend/vulkan/surface_producer_vk.h | 63 -- .../renderer/backend/vulkan/surface_vk.cc | 106 ++- .../renderer/backend/vulkan/surface_vk.h | 14 +- .../backend/vulkan/swapchain_details_vk.cc | 124 --- .../backend/vulkan/swapchain_details_vk.h | 46 - .../backend/vulkan/swapchain_image_vk.cc | 59 ++ .../backend/vulkan/swapchain_image_vk.h | 47 + .../backend/vulkan/swapchain_impl_vk.cc | 432 ++++++++++ .../backend/vulkan/swapchain_impl_vk.h | 80 ++ .../renderer/backend/vulkan/swapchain_vk.cc | 178 ++-- .../renderer/backend/vulkan/swapchain_vk.h | 63 +- .../backend/vulkan/texture_source_vk.cc | 16 + .../backend/vulkan/texture_source_vk.h | 27 + .../renderer/backend/vulkan/texture_vk.cc | 140 +-- .../renderer/backend/vulkan/texture_vk.h | 50 +- .../impeller/renderer/backend/vulkan/vk.h | 50 +- .../impeller/renderer/pipeline_descriptor.cc | 8 + .../impeller/renderer/pipeline_descriptor.h | 2 + .../flutter/impeller/renderer/render_pass.cc | 4 + .../flutter/impeller/renderer/render_pass.h | 2 + .../impeller/renderer/render_target.cc | 27 + .../flutter/impeller/renderer/render_target.h | 6 +- .../shell/gpu/gpu_surface_vulkan_impeller.cc | 11 +- .../shell/gpu/gpu_surface_vulkan_impeller.h | 1 - .../android_surface_vulkan_impeller.cc | 4 +- .../flutter/vulkan/procs/vulkan_proc_table.cc | 17 +- 71 files changed, 2887 insertions(+), 2448 deletions(-) create mode 100644 engine/src/flutter/impeller/renderer/backend/vulkan/command_encoder_vk.cc create mode 100644 engine/src/flutter/impeller/renderer/backend/vulkan/command_encoder_vk.h delete mode 100644 engine/src/flutter/impeller/renderer/backend/vulkan/command_pool_vk.cc delete mode 100644 engine/src/flutter/impeller/renderer/backend/vulkan/command_pool_vk.h delete mode 100644 engine/src/flutter/impeller/renderer/backend/vulkan/commands_vk.cc delete mode 100644 engine/src/flutter/impeller/renderer/backend/vulkan/commands_vk.h delete mode 100644 engine/src/flutter/impeller/renderer/backend/vulkan/deletion_queue_vk.cc delete mode 100644 engine/src/flutter/impeller/renderer/backend/vulkan/deletion_queue_vk.h delete mode 100644 engine/src/flutter/impeller/renderer/backend/vulkan/descriptor_pool_vk.cc delete mode 100644 engine/src/flutter/impeller/renderer/backend/vulkan/descriptor_pool_vk.h delete mode 100644 engine/src/flutter/impeller/renderer/backend/vulkan/fenced_command_buffer_vk.cc delete mode 100644 engine/src/flutter/impeller/renderer/backend/vulkan/fenced_command_buffer_vk.h create mode 100644 engine/src/flutter/impeller/renderer/backend/vulkan/shared_object_vk.cc create mode 100644 engine/src/flutter/impeller/renderer/backend/vulkan/shared_object_vk.h delete mode 100644 engine/src/flutter/impeller/renderer/backend/vulkan/surface_producer_vk.cc delete mode 100644 engine/src/flutter/impeller/renderer/backend/vulkan/surface_producer_vk.h delete mode 100644 engine/src/flutter/impeller/renderer/backend/vulkan/swapchain_details_vk.cc delete mode 100644 engine/src/flutter/impeller/renderer/backend/vulkan/swapchain_details_vk.h create mode 100644 engine/src/flutter/impeller/renderer/backend/vulkan/swapchain_image_vk.cc create mode 100644 engine/src/flutter/impeller/renderer/backend/vulkan/swapchain_image_vk.h create mode 100644 engine/src/flutter/impeller/renderer/backend/vulkan/swapchain_impl_vk.cc create mode 100644 engine/src/flutter/impeller/renderer/backend/vulkan/swapchain_impl_vk.h create mode 100644 engine/src/flutter/impeller/renderer/backend/vulkan/texture_source_vk.cc create mode 100644 engine/src/flutter/impeller/renderer/backend/vulkan/texture_source_vk.h diff --git a/engine/src/flutter/ci/licenses_golden/licenses_flutter b/engine/src/flutter/ci/licenses_golden/licenses_flutter index 45a4e78114..208cc69479 100644 --- a/engine/src/flutter/ci/licenses_golden/licenses_flutter +++ b/engine/src/flutter/ci/licenses_golden/licenses_flutter @@ -1406,20 +1406,12 @@ ORIGIN: ../../../flutter/impeller/renderer/backend/vulkan/capabilities_vk.cc + . ORIGIN: ../../../flutter/impeller/renderer/backend/vulkan/capabilities_vk.h + ../../../flutter/LICENSE ORIGIN: ../../../flutter/impeller/renderer/backend/vulkan/command_buffer_vk.cc + ../../../flutter/LICENSE ORIGIN: ../../../flutter/impeller/renderer/backend/vulkan/command_buffer_vk.h + ../../../flutter/LICENSE -ORIGIN: ../../../flutter/impeller/renderer/backend/vulkan/command_pool_vk.cc + ../../../flutter/LICENSE -ORIGIN: ../../../flutter/impeller/renderer/backend/vulkan/command_pool_vk.h + ../../../flutter/LICENSE -ORIGIN: ../../../flutter/impeller/renderer/backend/vulkan/commands_vk.cc + ../../../flutter/LICENSE -ORIGIN: ../../../flutter/impeller/renderer/backend/vulkan/commands_vk.h + ../../../flutter/LICENSE +ORIGIN: ../../../flutter/impeller/renderer/backend/vulkan/command_encoder_vk.cc + ../../../flutter/LICENSE +ORIGIN: ../../../flutter/impeller/renderer/backend/vulkan/command_encoder_vk.h + ../../../flutter/LICENSE ORIGIN: ../../../flutter/impeller/renderer/backend/vulkan/context_vk.cc + ../../../flutter/LICENSE ORIGIN: ../../../flutter/impeller/renderer/backend/vulkan/context_vk.h + ../../../flutter/LICENSE -ORIGIN: ../../../flutter/impeller/renderer/backend/vulkan/deletion_queue_vk.cc + ../../../flutter/LICENSE -ORIGIN: ../../../flutter/impeller/renderer/backend/vulkan/deletion_queue_vk.h + ../../../flutter/LICENSE -ORIGIN: ../../../flutter/impeller/renderer/backend/vulkan/descriptor_pool_vk.cc + ../../../flutter/LICENSE -ORIGIN: ../../../flutter/impeller/renderer/backend/vulkan/descriptor_pool_vk.h + ../../../flutter/LICENSE ORIGIN: ../../../flutter/impeller/renderer/backend/vulkan/device_buffer_vk.cc + ../../../flutter/LICENSE ORIGIN: ../../../flutter/impeller/renderer/backend/vulkan/device_buffer_vk.h + ../../../flutter/LICENSE -ORIGIN: ../../../flutter/impeller/renderer/backend/vulkan/fenced_command_buffer_vk.cc + ../../../flutter/LICENSE -ORIGIN: ../../../flutter/impeller/renderer/backend/vulkan/fenced_command_buffer_vk.h + ../../../flutter/LICENSE ORIGIN: ../../../flutter/impeller/renderer/backend/vulkan/formats_vk.cc + ../../../flutter/LICENSE ORIGIN: ../../../flutter/impeller/renderer/backend/vulkan/formats_vk.h + ../../../flutter/LICENSE ORIGIN: ../../../flutter/impeller/renderer/backend/vulkan/pipeline_library_vk.cc + ../../../flutter/LICENSE @@ -1436,14 +1428,18 @@ ORIGIN: ../../../flutter/impeller/renderer/backend/vulkan/shader_function_vk.cc ORIGIN: ../../../flutter/impeller/renderer/backend/vulkan/shader_function_vk.h + ../../../flutter/LICENSE ORIGIN: ../../../flutter/impeller/renderer/backend/vulkan/shader_library_vk.cc + ../../../flutter/LICENSE ORIGIN: ../../../flutter/impeller/renderer/backend/vulkan/shader_library_vk.h + ../../../flutter/LICENSE -ORIGIN: ../../../flutter/impeller/renderer/backend/vulkan/surface_producer_vk.cc + ../../../flutter/LICENSE -ORIGIN: ../../../flutter/impeller/renderer/backend/vulkan/surface_producer_vk.h + ../../../flutter/LICENSE +ORIGIN: ../../../flutter/impeller/renderer/backend/vulkan/shared_object_vk.cc + ../../../flutter/LICENSE +ORIGIN: ../../../flutter/impeller/renderer/backend/vulkan/shared_object_vk.h + ../../../flutter/LICENSE ORIGIN: ../../../flutter/impeller/renderer/backend/vulkan/surface_vk.cc + ../../../flutter/LICENSE ORIGIN: ../../../flutter/impeller/renderer/backend/vulkan/surface_vk.h + ../../../flutter/LICENSE -ORIGIN: ../../../flutter/impeller/renderer/backend/vulkan/swapchain_details_vk.cc + ../../../flutter/LICENSE -ORIGIN: ../../../flutter/impeller/renderer/backend/vulkan/swapchain_details_vk.h + ../../../flutter/LICENSE +ORIGIN: ../../../flutter/impeller/renderer/backend/vulkan/swapchain_image_vk.cc + ../../../flutter/LICENSE +ORIGIN: ../../../flutter/impeller/renderer/backend/vulkan/swapchain_image_vk.h + ../../../flutter/LICENSE +ORIGIN: ../../../flutter/impeller/renderer/backend/vulkan/swapchain_impl_vk.cc + ../../../flutter/LICENSE +ORIGIN: ../../../flutter/impeller/renderer/backend/vulkan/swapchain_impl_vk.h + ../../../flutter/LICENSE ORIGIN: ../../../flutter/impeller/renderer/backend/vulkan/swapchain_vk.cc + ../../../flutter/LICENSE ORIGIN: ../../../flutter/impeller/renderer/backend/vulkan/swapchain_vk.h + ../../../flutter/LICENSE +ORIGIN: ../../../flutter/impeller/renderer/backend/vulkan/texture_source_vk.cc + ../../../flutter/LICENSE +ORIGIN: ../../../flutter/impeller/renderer/backend/vulkan/texture_source_vk.h + ../../../flutter/LICENSE ORIGIN: ../../../flutter/impeller/renderer/backend/vulkan/texture_vk.cc + ../../../flutter/LICENSE ORIGIN: ../../../flutter/impeller/renderer/backend/vulkan/texture_vk.h + ../../../flutter/LICENSE ORIGIN: ../../../flutter/impeller/renderer/backend/vulkan/vertex_descriptor_vk.cc + ../../../flutter/LICENSE @@ -3906,20 +3902,12 @@ FILE: ../../../flutter/impeller/renderer/backend/vulkan/capabilities_vk.cc FILE: ../../../flutter/impeller/renderer/backend/vulkan/capabilities_vk.h FILE: ../../../flutter/impeller/renderer/backend/vulkan/command_buffer_vk.cc FILE: ../../../flutter/impeller/renderer/backend/vulkan/command_buffer_vk.h -FILE: ../../../flutter/impeller/renderer/backend/vulkan/command_pool_vk.cc -FILE: ../../../flutter/impeller/renderer/backend/vulkan/command_pool_vk.h -FILE: ../../../flutter/impeller/renderer/backend/vulkan/commands_vk.cc -FILE: ../../../flutter/impeller/renderer/backend/vulkan/commands_vk.h +FILE: ../../../flutter/impeller/renderer/backend/vulkan/command_encoder_vk.cc +FILE: ../../../flutter/impeller/renderer/backend/vulkan/command_encoder_vk.h FILE: ../../../flutter/impeller/renderer/backend/vulkan/context_vk.cc FILE: ../../../flutter/impeller/renderer/backend/vulkan/context_vk.h -FILE: ../../../flutter/impeller/renderer/backend/vulkan/deletion_queue_vk.cc -FILE: ../../../flutter/impeller/renderer/backend/vulkan/deletion_queue_vk.h -FILE: ../../../flutter/impeller/renderer/backend/vulkan/descriptor_pool_vk.cc -FILE: ../../../flutter/impeller/renderer/backend/vulkan/descriptor_pool_vk.h FILE: ../../../flutter/impeller/renderer/backend/vulkan/device_buffer_vk.cc FILE: ../../../flutter/impeller/renderer/backend/vulkan/device_buffer_vk.h -FILE: ../../../flutter/impeller/renderer/backend/vulkan/fenced_command_buffer_vk.cc -FILE: ../../../flutter/impeller/renderer/backend/vulkan/fenced_command_buffer_vk.h FILE: ../../../flutter/impeller/renderer/backend/vulkan/formats_vk.cc FILE: ../../../flutter/impeller/renderer/backend/vulkan/formats_vk.h FILE: ../../../flutter/impeller/renderer/backend/vulkan/pipeline_library_vk.cc @@ -3936,14 +3924,18 @@ FILE: ../../../flutter/impeller/renderer/backend/vulkan/shader_function_vk.cc FILE: ../../../flutter/impeller/renderer/backend/vulkan/shader_function_vk.h FILE: ../../../flutter/impeller/renderer/backend/vulkan/shader_library_vk.cc FILE: ../../../flutter/impeller/renderer/backend/vulkan/shader_library_vk.h -FILE: ../../../flutter/impeller/renderer/backend/vulkan/surface_producer_vk.cc -FILE: ../../../flutter/impeller/renderer/backend/vulkan/surface_producer_vk.h +FILE: ../../../flutter/impeller/renderer/backend/vulkan/shared_object_vk.cc +FILE: ../../../flutter/impeller/renderer/backend/vulkan/shared_object_vk.h FILE: ../../../flutter/impeller/renderer/backend/vulkan/surface_vk.cc FILE: ../../../flutter/impeller/renderer/backend/vulkan/surface_vk.h -FILE: ../../../flutter/impeller/renderer/backend/vulkan/swapchain_details_vk.cc -FILE: ../../../flutter/impeller/renderer/backend/vulkan/swapchain_details_vk.h +FILE: ../../../flutter/impeller/renderer/backend/vulkan/swapchain_image_vk.cc +FILE: ../../../flutter/impeller/renderer/backend/vulkan/swapchain_image_vk.h +FILE: ../../../flutter/impeller/renderer/backend/vulkan/swapchain_impl_vk.cc +FILE: ../../../flutter/impeller/renderer/backend/vulkan/swapchain_impl_vk.h FILE: ../../../flutter/impeller/renderer/backend/vulkan/swapchain_vk.cc FILE: ../../../flutter/impeller/renderer/backend/vulkan/swapchain_vk.h +FILE: ../../../flutter/impeller/renderer/backend/vulkan/texture_source_vk.cc +FILE: ../../../flutter/impeller/renderer/backend/vulkan/texture_source_vk.h FILE: ../../../flutter/impeller/renderer/backend/vulkan/texture_vk.cc FILE: ../../../flutter/impeller/renderer/backend/vulkan/texture_vk.h FILE: ../../../flutter/impeller/renderer/backend/vulkan/vertex_descriptor_vk.cc diff --git a/engine/src/flutter/flutter_vma/flutter_vma.cc b/engine/src/flutter/flutter_vma/flutter_vma.cc index 81df956c1d..4ec7f72482 100644 --- a/engine/src/flutter/flutter_vma/flutter_vma.cc +++ b/engine/src/flutter/flutter_vma/flutter_vma.cc @@ -16,4 +16,19 @@ #define VMA_IMPLEMENTATION +// Enable this to dump a list of all pending allocations to the log. This comes +// in handy if you are tracking a leak of a resource after context shutdown. +#if 0 +#include "flutter/fml/logging.h" // nogncheck +#define VMA_DEBUG_LOG VMADebugPrint +void VMADebugPrint(const char* message, ...) { + va_list args; + va_start(args, message); + char buffer[256]; + vsnprintf(buffer, sizeof(buffer) - 1, message, args); + va_end(args); + FML_DLOG(INFO) << buffer; +} +#endif + #include "flutter/flutter_vma/flutter_vma.h" diff --git a/engine/src/flutter/impeller/entity/inline_pass_context.cc b/engine/src/flutter/impeller/entity/inline_pass_context.cc index 99a1877c95..c5997802ee 100644 --- a/engine/src/flutter/impeller/entity/inline_pass_context.cc +++ b/engine/src/flutter/impeller/entity/inline_pass_context.cc @@ -104,7 +104,6 @@ InlinePassContext::RenderPassResult InlinePassContext::GetRenderPass( color0.store_action = StoreAction::kStore; } -#ifndef IMPELLER_ENABLE_VULKAN auto stencil = render_target_.GetStencilAttachment(); if (!stencil.has_value()) { VALIDATION_LOG << "Stencil attachment unexpectedly missing from the " @@ -122,11 +121,6 @@ InlinePassContext::RenderPassResult InlinePassContext::GetRenderPass( ? StoreAction::kDontCare : StoreAction::kStore; render_target_.SetStencilAttachment(stencil.value()); -#else - // Touch this variable to avoid a compiler warnings. - // This will go away once stencil support is added for vulkan. - total_pass_reads_ = 1; -#endif render_target_.SetColorAttachment(color0, 0); diff --git a/engine/src/flutter/impeller/playground/backend/vulkan/playground_impl_vk.cc b/engine/src/flutter/impeller/playground/backend/vulkan/playground_impl_vk.cc index 3b045b35d4..11261ddc3f 100644 --- a/engine/src/flutter/impeller/playground/backend/vulkan/playground_impl_vk.cc +++ b/engine/src/flutter/impeller/playground/backend/vulkan/playground_impl_vk.cc @@ -37,7 +37,6 @@ ShaderLibraryMappingsForPlayground() { impeller_imgui_shaders_vk_length), std::make_shared(impeller_scene_shaders_vk_data, impeller_scene_shaders_vk_length), - }; } @@ -59,11 +58,9 @@ PlaygroundImplVK::PlaygroundImplVK() ::glfwDefaultWindowHints(); ::glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); - ::glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE); ::glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); - auto window = - ::glfwCreateWindow(800, 600, "Test Vulkan Window", nullptr, nullptr); + auto window = ::glfwCreateWindow(1, 1, "Test", nullptr, nullptr); if (!window) { VALIDATION_LOG << "Unable to create glfw window"; return; @@ -84,25 +81,26 @@ PlaygroundImplVK::PlaygroundImplVK() return; } - context_ = std::move(context); - - SetupSwapchain(); -} - -void PlaygroundImplVK::SetupSwapchain() { - ContextVK* context_vk = reinterpret_cast(context_.get()); - auto window = reinterpret_cast(handle_.get()); - vk::Instance instance = context_vk->GetInstance(); - VkSurfaceKHR surface_tmp; - auto res = vk::Result{ - ::glfwCreateWindowSurface(instance, window, nullptr, &surface_tmp)}; + VkSurfaceKHR vk_surface; + auto res = + vk::Result{::glfwCreateWindowSurface(context->GetInstance(), // instance + window, // window + nullptr, // allocator + &vk_surface // surface + )}; if (res != vk::Result::eSuccess) { VALIDATION_LOG << "Could not create surface for GLFW window: " << vk::to_string(res); return; } - vk::UniqueSurfaceKHR surface{surface_tmp, instance}; - context_vk->SetupSwapchain(std::move(surface)); + + vk::UniqueSurfaceKHR surface{vk_surface, context->GetInstance()}; + if (!context->SetWindowSurface(std::move(surface))) { + VALIDATION_LOG << "Could not setup surface for context."; + return; + } + + context_ = std::move(context); } PlaygroundImplVK::~PlaygroundImplVK() = default; @@ -121,7 +119,7 @@ PlaygroundImpl::WindowHandle PlaygroundImplVK::GetWindowHandle() const { std::unique_ptr PlaygroundImplVK::AcquireSurfaceFrame( std::shared_ptr context) { ContextVK* context_vk = reinterpret_cast(context_.get()); - return context_vk->AcquireSurface(current_frame_++); + return context_vk->AcquireNextSurface(); } } // namespace impeller diff --git a/engine/src/flutter/impeller/playground/backend/vulkan/playground_impl_vk.h b/engine/src/flutter/impeller/playground/backend/vulkan/playground_impl_vk.h index 37c847a92a..a1aa4afa6e 100644 --- a/engine/src/flutter/impeller/playground/backend/vulkan/playground_impl_vk.h +++ b/engine/src/flutter/impeller/playground/backend/vulkan/playground_impl_vk.h @@ -7,7 +7,6 @@ #include "flutter/fml/concurrent_message_loop.h" #include "flutter/fml/macros.h" #include "impeller/playground/playground_impl.h" -#include "impeller/renderer/backend/vulkan/swapchain_vk.h" #include "impeller/renderer/backend/vulkan/vk.h" namespace impeller { @@ -21,9 +20,8 @@ class PlaygroundImplVK final : public PlaygroundImpl { private: std::shared_ptr concurrent_loop_; std::shared_ptr context_; - size_t current_frame_ = 0; - // windows + // Windows management. static void DestroyWindowHandle(WindowHandle handle); using UniqueHandle = std::unique_ptr; UniqueHandle handle_; @@ -38,8 +36,6 @@ class PlaygroundImplVK final : public PlaygroundImpl { std::unique_ptr AcquireSurfaceFrame( std::shared_ptr context) override; - void SetupSwapchain(); - FML_DISALLOW_COPY_AND_ASSIGN(PlaygroundImplVK); }; diff --git a/engine/src/flutter/impeller/renderer/backend/metal/surface_mtl.mm b/engine/src/flutter/impeller/renderer/backend/metal/surface_mtl.mm index 4ddcb2dd40..70eedfd7ae 100644 --- a/engine/src/flutter/impeller/renderer/backend/metal/surface_mtl.mm +++ b/engine/src/flutter/impeller/renderer/backend/metal/surface_mtl.mm @@ -43,60 +43,64 @@ std::unique_ptr SurfaceMTL::WrapCurrentMetalLayerDrawable( return nullptr; } - TextureDescriptor color0_tex_desc; - color0_tex_desc.storage_mode = StorageMode::kDeviceTransient; - color0_tex_desc.type = TextureType::kTexture2DMultisample; - color0_tex_desc.sample_count = SampleCount::kCount4; - color0_tex_desc.format = color_format; - color0_tex_desc.size = { + TextureDescriptor msaa_tex_desc; + msaa_tex_desc.storage_mode = StorageMode::kDeviceTransient; + msaa_tex_desc.type = TextureType::kTexture2DMultisample; + msaa_tex_desc.sample_count = SampleCount::kCount4; + msaa_tex_desc.format = color_format; + msaa_tex_desc.size = { static_cast(current_drawable.texture.width), static_cast(current_drawable.texture.height)}; - color0_tex_desc.usage = static_cast(TextureUsage::kRenderTarget); + msaa_tex_desc.usage = static_cast(TextureUsage::kRenderTarget); - auto msaa_tex = - context->GetResourceAllocator()->CreateTexture(color0_tex_desc); + auto msaa_tex = context->GetResourceAllocator()->CreateTexture(msaa_tex_desc); if (!msaa_tex) { - VALIDATION_LOG << "Could not allocate MSAA resolve texture."; + VALIDATION_LOG << "Could not allocate MSAA color texture."; return nullptr; } - msaa_tex->SetLabel("ImpellerOnscreenColorMSAA"); - TextureDescriptor color0_resolve_tex_desc; - color0_resolve_tex_desc.format = color_format; - color0_resolve_tex_desc.size = color0_tex_desc.size; - color0_resolve_tex_desc.usage = - static_cast(TextureUsage::kRenderTarget); - color0_resolve_tex_desc.storage_mode = StorageMode::kDevicePrivate; + TextureDescriptor resolve_tex_desc; + resolve_tex_desc.format = color_format; + resolve_tex_desc.size = msaa_tex_desc.size; + resolve_tex_desc.usage = static_cast(TextureUsage::kRenderTarget); + resolve_tex_desc.storage_mode = StorageMode::kDevicePrivate; + + std::shared_ptr resolve_tex = + std::make_shared(resolve_tex_desc, current_drawable.texture); + if (!resolve_tex) { + VALIDATION_LOG << "Could not wrap resolve texture."; + return nullptr; + } + resolve_tex->SetLabel("ImpellerOnscreenResolve"); ColorAttachment color0; color0.texture = msaa_tex; color0.clear_color = Color::DarkSlateGray(); color0.load_action = LoadAction::kClear; color0.store_action = StoreAction::kMultisampleResolve; - color0.resolve_texture = std::make_shared( - color0_resolve_tex_desc, current_drawable.texture); + color0.resolve_texture = resolve_tex; - TextureDescriptor stencil0_tex; - stencil0_tex.storage_mode = StorageMode::kDeviceTransient; - stencil0_tex.type = TextureType::kTexture2DMultisample; - stencil0_tex.sample_count = SampleCount::kCount4; - stencil0_tex.format = + TextureDescriptor stencil_tex_desc; + stencil_tex_desc.storage_mode = StorageMode::kDeviceTransient; + stencil_tex_desc.type = TextureType::kTexture2DMultisample; + stencil_tex_desc.sample_count = SampleCount::kCount4; + stencil_tex_desc.format = context->GetDeviceCapabilities().GetDefaultStencilFormat(); - stencil0_tex.size = color0_tex_desc.size; - stencil0_tex.usage = + stencil_tex_desc.size = msaa_tex_desc.size; + stencil_tex_desc.usage = static_cast(TextureUsage::kRenderTarget); - auto stencil_texture = - context->GetResourceAllocator()->CreateTexture(stencil0_tex); + auto stencil_tex = + context->GetResourceAllocator()->CreateTexture(stencil_tex_desc); - if (!stencil_texture) { + if (!stencil_tex) { VALIDATION_LOG << "Could not create stencil texture."; return nullptr; } - stencil_texture->SetLabel("ImpellerOnscreenStencil"); + stencil_tex->SetLabel("ImpellerOnscreenStencil"); StencilAttachment stencil0; - stencil0.texture = stencil_texture; + stencil0.texture = stencil_tex; stencil0.clear_stencil = 0; stencil0.load_action = LoadAction::kClear; stencil0.store_action = StoreAction::kDontCare; diff --git a/engine/src/flutter/impeller/renderer/backend/metal/texture_mtl.mm b/engine/src/flutter/impeller/renderer/backend/metal/texture_mtl.mm index 6877c1b871..5c13323300 100644 --- a/engine/src/flutter/impeller/renderer/backend/metal/texture_mtl.mm +++ b/engine/src/flutter/impeller/renderer/backend/metal/texture_mtl.mm @@ -62,10 +62,6 @@ bool TextureMTL::OnSetContents(const uint8_t* contents, return false; } - // TODO(csg): Perhaps the storage mode should be added to the texture - // descriptor so that invalid region replacements on potentially non-host - // visible textures are disallowed. The annoying bit about the API below is - // that there seems to be no error handling guidance. const auto region = MTLRegionMake2D(0u, 0u, desc.size.width, desc.size.height); [texture_ replaceRegion:region // diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/BUILD.gn b/engine/src/flutter/impeller/renderer/backend/vulkan/BUILD.gn index dd1514a326..2c30458c84 100644 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/BUILD.gn +++ b/engine/src/flutter/impeller/renderer/backend/vulkan/BUILD.gn @@ -16,20 +16,12 @@ impeller_component("vulkan") { "capabilities_vk.h", "command_buffer_vk.cc", "command_buffer_vk.h", - "command_pool_vk.cc", - "command_pool_vk.h", - "commands_vk.cc", - "commands_vk.h", + "command_encoder_vk.cc", + "command_encoder_vk.h", "context_vk.cc", "context_vk.h", - "deletion_queue_vk.cc", - "deletion_queue_vk.h", - "descriptor_pool_vk.cc", - "descriptor_pool_vk.h", "device_buffer_vk.cc", "device_buffer_vk.h", - "fenced_command_buffer_vk.cc", - "fenced_command_buffer_vk.h", "formats_vk.cc", "formats_vk.h", "pipeline_library_vk.cc", @@ -46,14 +38,18 @@ impeller_component("vulkan") { "shader_function_vk.h", "shader_library_vk.cc", "shader_library_vk.h", - "surface_producer_vk.cc", - "surface_producer_vk.h", + "shared_object_vk.cc", + "shared_object_vk.h", "surface_vk.cc", "surface_vk.h", - "swapchain_details_vk.cc", - "swapchain_details_vk.h", + "swapchain_image_vk.cc", + "swapchain_image_vk.h", + "swapchain_impl_vk.cc", + "swapchain_impl_vk.h", "swapchain_vk.cc", "swapchain_vk.h", + "texture_source_vk.cc", + "texture_source_vk.h", "texture_vk.cc", "texture_vk.h", "vertex_descriptor_vk.cc", diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/allocator_vk.cc b/engine/src/flutter/impeller/renderer/backend/vulkan/allocator_vk.cc index ae862731b7..4119abab9f 100644 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/allocator_vk.cc +++ b/engine/src/flutter/impeller/renderer/backend/vulkan/allocator_vk.cc @@ -7,8 +7,6 @@ #include #include "flutter/fml/memory/ref_ptr.h" -#include "flutter/vulkan/procs/vulkan_handle.h" -#include "flutter/vulkan/procs/vulkan_proc_table.h" #include "impeller/renderer/backend/vulkan/device_buffer_vk.h" #include "impeller/renderer/backend/vulkan/formats_vk.h" #include "impeller/renderer/backend/vulkan/texture_vk.h" @@ -16,21 +14,29 @@ namespace impeller { -AllocatorVK::AllocatorVK(ContextVK& context, +AllocatorVK::AllocatorVK(std::weak_ptr context, uint32_t vulkan_api_version, const vk::PhysicalDevice& physical_device, const vk::Device& logical_device, const vk::Instance& instance, PFN_vkGetInstanceProcAddr get_instance_proc_address, PFN_vkGetDeviceProcAddr get_device_proc_address) - : context_(context), device_(logical_device) { + : context_(std::move(context)), device_(logical_device) { vk_ = fml::MakeRefCounted(get_instance_proc_address); auto instance_handle = vulkan::VulkanHandle(instance); - FML_CHECK(vk_->SetupInstanceProcAddresses(instance_handle)); + if (!vk_->SetupInstanceProcAddresses(instance_handle)) { + return; + } auto device_handle = vulkan::VulkanHandle(logical_device); - FML_CHECK(vk_->SetupDeviceProcAddresses(device_handle)); + if (!vk_->SetupDeviceProcAddresses(device_handle)) { + return; + } + + auto limits = physical_device.getProperties().limits; + max_texture_size_.width = max_texture_size_.height = + limits.maxImageDimension2D; VmaVulkanFunctions proc_table = {}; proc_table.vkGetInstanceProcAddr = get_instance_proc_address; @@ -97,130 +103,279 @@ bool AllocatorVK::IsValid() const { return is_valid_; } +// |Allocator| +ISize AllocatorVK::GetMaxTextureSizeSupported() const { + return max_texture_size_; +} + +static constexpr vk::ImageUsageFlags ToVKImageUsageFlags(PixelFormat format, + TextureUsageMask usage, + StorageMode mode) { + vk::ImageUsageFlags vk_usage; + + switch (mode) { + case StorageMode::kHostVisible: + case StorageMode::kDevicePrivate: + break; + case StorageMode::kDeviceTransient: + vk_usage |= vk::ImageUsageFlagBits::eTransientAttachment; + break; + } + + if (usage & static_cast(TextureUsage::kRenderTarget)) { + if (PixelFormatIsDepthStencil(format)) { + vk_usage |= vk::ImageUsageFlagBits::eDepthStencilAttachment; + } else { + vk_usage |= vk::ImageUsageFlagBits::eColorAttachment; + } + } + + if (usage & static_cast(TextureUsage::kShaderRead)) { + vk_usage |= vk::ImageUsageFlagBits::eSampled; + } + + if (usage & static_cast(TextureUsage::kShaderWrite)) { + vk_usage |= vk::ImageUsageFlagBits::eStorage; + } + + return vk_usage; +} + +static constexpr VmaMemoryUsage ToVMAMemoryUsage() { + return VMA_MEMORY_USAGE_AUTO; +} + +static constexpr VkMemoryPropertyFlags ToVKMemoryPropertyFlags( + StorageMode mode, + bool is_texture) { + switch (mode) { + case StorageMode::kHostVisible: + if (is_texture) { + return VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT; + } else { + return VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | + VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; + } + + case StorageMode::kDevicePrivate: + return VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; + case StorageMode::kDeviceTransient: + return VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT; + } + FML_UNREACHABLE(); +} + +static VmaAllocationCreateFlags ToVmaAllocationCreateFlags(StorageMode mode, + bool is_texture) { + VmaAllocationCreateFlags flags = 0; + switch (mode) { + case StorageMode::kHostVisible: + if (is_texture) { + flags |= VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT; + } else { + flags |= VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT; + flags |= VMA_ALLOCATION_CREATE_MAPPED_BIT; + } + return flags; + case StorageMode::kDevicePrivate: + if (is_texture) { + flags |= VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT; + } + return flags; + case StorageMode::kDeviceTransient: + return flags; + } + FML_UNREACHABLE(); +} + +class AllocatedTextureSourceVK final : public TextureSourceVK { + public: + AllocatedTextureSourceVK(const TextureDescriptor& desc, + VmaAllocator allocator, + vk::Device device) { + vk::ImageCreateInfo image_info; + image_info.imageType = vk::ImageType::e2D; + image_info.format = ToVKImageFormat(desc.format); + image_info.extent = VkExtent3D{ + static_cast(desc.size.width), // width + static_cast(desc.size.height), // height + 1u // depth + }; + image_info.samples = ToVKSampleCount(desc.sample_count); + image_info.mipLevels = desc.mip_count; + image_info.arrayLayers = ToArrayLayerCount(desc.type); + image_info.tiling = vk::ImageTiling::eOptimal; + image_info.initialLayout = vk::ImageLayout::eUndefined; + image_info.usage = + ToVKImageUsageFlags(desc.format, desc.usage, desc.storage_mode); + image_info.sharingMode = vk::SharingMode::eExclusive; + + VmaAllocationCreateInfo alloc_create_info = {}; + + alloc_create_info.usage = ToVMAMemoryUsage(); + alloc_create_info.preferredFlags = + ToVKMemoryPropertyFlags(desc.storage_mode, true); + alloc_create_info.flags = + ToVmaAllocationCreateFlags(desc.storage_mode, true); + + auto create_info_native = + static_cast(image_info); + + VkImage vk_image = VK_NULL_HANDLE; + VmaAllocation allocation = {}; + VmaAllocationInfo allocation_info = {}; + { + auto result = vk::Result{vmaCreateImage(allocator, // + &create_info_native, // + &alloc_create_info, // + &vk_image, // + &allocation, // + &allocation_info // + )}; + if (result != vk::Result::eSuccess) { + VALIDATION_LOG << "Unable to allocation Vulkan Image: " + << vk::to_string(result); + return; + } + } + + image_ = vk::Image{vk_image}; + allocator_ = allocator; + allocation_ = allocation; + + vk::ImageViewCreateInfo view_create_info = {}; + view_create_info.image = image_; + view_create_info.viewType = vk::ImageViewType::e2D; + view_create_info.format = image_info.format; + view_create_info.subresourceRange.aspectMask = + ToVKImageAspectFlags(desc.format); + view_create_info.subresourceRange.levelCount = image_info.mipLevels; + view_create_info.subresourceRange.layerCount = 1u; + + // Vulkan does not have an image format that is equivalent to + // `MTLPixelFormatA8Unorm`, so we use `R8Unorm` instead. Given that the + // shaders expect that alpha channel to be set in the cases, we swizzle. + // See: https://github.com/flutter/flutter/issues/115461 for more details. + if (desc.format == PixelFormat::kA8UNormInt) { + view_create_info.components.a = vk::ComponentSwizzle::eR; + view_create_info.components.r = vk::ComponentSwizzle::eA; + } + + auto [result, image_view] = device.createImageViewUnique(view_create_info); + if (result != vk::Result::eSuccess) { + VALIDATION_LOG << "Unable to create an image view for allocation: " + << vk::to_string(result); + return; + } + image_view_ = std::move(image_view); + + is_valid_ = true; + } + + ~AllocatedTextureSourceVK() { + image_view_.reset(); + if (image_) { + vmaDestroyImage( + allocator_, // + static_cast(image_), // + allocation_ // + ); + } + } + + bool SetContents(const TextureDescriptor& desc, + const uint8_t* contents, + size_t length, + size_t slice) override { + void* data = nullptr; + if (::vmaMapMemory(allocator_, allocation_, &data) != VK_SUCCESS) { + VALIDATION_LOG << "Could not map texture memory to write to."; + return false; + } + + std::memcpy(static_cast(data) + (length * slice), // + contents, // + length // + ); + + const auto flushed = ::vmaFlushAllocation(allocator_, // allocator + allocation_, // allocation + length * slice, // offset + length // size + ) == VK_SUCCESS; + + ::vmaUnmapMemory(allocator_, allocation_); + + if (!flushed) { + VALIDATION_LOG << "Could not flush written mapped memory."; + return false; + } + + return true; + } + + bool IsValid() const { return is_valid_; } + + vk::Image GetVKImage() const override { return image_; } + + vk::ImageView GetVKImageView() const override { return image_view_.get(); } + + private: + vk::Image image_ = {}; + VmaAllocator allocator_ = {}; + VmaAllocation allocation_ = {}; + vk::UniqueImageView image_view_; + bool is_valid_ = false; + + FML_DISALLOW_COPY_AND_ASSIGN(AllocatedTextureSourceVK); +}; + // |Allocator| std::shared_ptr AllocatorVK::OnCreateTexture( const TextureDescriptor& desc) { - auto image_create_info = vk::ImageCreateInfo{}; - image_create_info.imageType = vk::ImageType::e2D; - image_create_info.format = ToVKImageFormat(desc.format); - image_create_info.extent.width = desc.size.width; - image_create_info.extent.height = desc.size.height; - image_create_info.samples = ToVKSampleCount(desc.sample_count); - image_create_info.mipLevels = desc.mip_count; - - // TODO (kaushikiska): should we read these from desc? - image_create_info.extent.depth = 1; - image_create_info.arrayLayers = 1; - - image_create_info.tiling = vk::ImageTiling::eOptimal; - image_create_info.initialLayout = vk::ImageLayout::eUndefined; - image_create_info.usage = vk::ImageUsageFlagBits::eSampled | - vk::ImageUsageFlagBits::eColorAttachment | - vk::ImageUsageFlagBits::eTransferSrc | - vk::ImageUsageFlagBits::eTransferDst; - - VmaAllocationCreateInfo alloc_create_info = {}; - alloc_create_info.usage = VMA_MEMORY_USAGE_AUTO; - // docs recommend using `VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT` for image - // allocations, but setting them to be host visible for now. - alloc_create_info.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT | - VMA_ALLOCATION_CREATE_MAPPED_BIT; - - auto create_info_native = - static_cast(image_create_info); - - VkImage img; - VmaAllocation allocation; - VmaAllocationInfo allocation_info; - auto result = vk::Result{vmaCreateImage(allocator_, &create_info_native, - &alloc_create_info, &img, &allocation, - &allocation_info)}; - if (result != vk::Result::eSuccess) { - VALIDATION_LOG << "Unable to allocate an image"; + if (!IsValid()) { return nullptr; } - - vk::ImageViewCreateInfo view_create_info = {}; - view_create_info.image = vk::Image{img}; - view_create_info.viewType = vk::ImageViewType::e2D; - view_create_info.format = image_create_info.format; - view_create_info.subresourceRange.aspectMask = - vk::ImageAspectFlagBits::eColor; - view_create_info.subresourceRange.levelCount = image_create_info.mipLevels; - view_create_info.subresourceRange.layerCount = image_create_info.arrayLayers; - - // Vulkan does not have an image format that is equivalent to - // `MTLPixelFormatA8Unorm`, so we use `R8Unorm` instead. Given that the - // shaders expect that alpha channel to be set in the cases, we swizzle. - // See: https://github.com/flutter/flutter/issues/115461 for more details. - if (desc.format == PixelFormat::kA8UNormInt) { - view_create_info.components.a = vk::ComponentSwizzle::eR; - view_create_info.components.r = vk::ComponentSwizzle::eA; - } - - auto img_view_res = device_.createImageView(view_create_info); - if (img_view_res.result != vk::Result::eSuccess) { - VALIDATION_LOG << "Unable to create an image view: " - << vk::to_string(img_view_res.result); + auto source = std::make_shared(desc, // + allocator_, // + device_ // + ); + if (!source->IsValid()) { return nullptr; } - - auto image_view = static_cast(img_view_res.value); - auto staging_buffer = - CreateHostVisibleDeviceAllocation(desc.GetByteSizeOfBaseMipLevel()); - - auto texture_info = std::make_unique(TextureInfoVK{ - .backing_type = TextureBackingTypeVK::kAllocatedTexture, - .allocated_texture = - { - .staging_buffer = staging_buffer, - .backing_allocation = - { - .allocator = &allocator_, - .allocation = allocation, - .allocation_info = allocation_info, - }, - .image = img, - .image_view = image_view, - }, - }); - return std::make_shared(desc, &context_, std::move(texture_info)); + return std::make_shared(desc, context_, std::move(source)); } // |Allocator| std::shared_ptr AllocatorVK::OnCreateBuffer( const DeviceBufferDescriptor& desc) { - // TODO (kaushikiska): consider optimizing the usage flags based on - // StorageMode. - auto device_allocation = std::make_unique( - CreateHostVisibleDeviceAllocation(desc.size)); - return std::make_shared(desc, context_, - std::move(device_allocation)); -} + vk::BufferCreateInfo buffer_info; + buffer_info.usage = vk::BufferUsageFlagBits::eVertexBuffer | + vk::BufferUsageFlagBits::eIndexBuffer | + vk::BufferUsageFlagBits::eUniformBuffer | + vk::BufferUsageFlagBits::eTransferSrc | + vk::BufferUsageFlagBits::eTransferDst; + buffer_info.size = desc.size; + buffer_info.sharingMode = vk::SharingMode::eExclusive; + auto buffer_info_native = + static_cast(buffer_info); -DeviceBufferAllocationVK AllocatorVK::CreateHostVisibleDeviceAllocation( - size_t size) { - auto buffer_create_info = static_cast( - vk::BufferCreateInfo() - .setUsage(vk::BufferUsageFlagBits::eVertexBuffer | - vk::BufferUsageFlagBits::eIndexBuffer | - vk::BufferUsageFlagBits::eUniformBuffer | - vk::BufferUsageFlagBits::eTransferSrc | - vk::BufferUsageFlagBits::eTransferDst) - .setSize(size) - .setSharingMode(vk::SharingMode::eExclusive)); + VmaAllocationCreateInfo allocation_info = {}; + allocation_info.usage = ToVMAMemoryUsage(); + allocation_info.preferredFlags = + ToVKMemoryPropertyFlags(desc.storage_mode, false); + allocation_info.flags = ToVmaAllocationCreateFlags(desc.storage_mode, false); - VmaAllocationCreateInfo allocCreateInfo = {}; - allocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO; - allocCreateInfo.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT | - VMA_ALLOCATION_CREATE_MAPPED_BIT; - - VkBuffer buffer; - VmaAllocation buffer_allocation; - VmaAllocationInfo buffer_allocation_info; - auto result = vk::Result{ - vmaCreateBuffer(allocator_, &buffer_create_info, &allocCreateInfo, - &buffer, &buffer_allocation, &buffer_allocation_info)}; + VkBuffer buffer = {}; + VmaAllocation buffer_allocation = {}; + VmaAllocationInfo buffer_allocation_info = {}; + auto result = vk::Result{::vmaCreateBuffer(allocator_, // + &buffer_info_native, // + &allocation_info, // + &buffer, // + &buffer_allocation, // + &buffer_allocation_info // + )}; if (result != vk::Result::eSuccess) { VALIDATION_LOG << "Unable to allocate a device buffer: " @@ -228,30 +383,13 @@ DeviceBufferAllocationVK AllocatorVK::CreateHostVisibleDeviceAllocation( return {}; } - VkMemoryPropertyFlags memory_props; - vmaGetAllocationMemoryProperties(allocator_, buffer_allocation, - &memory_props); - if (!(memory_props & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)) { - VALIDATION_LOG << "Unable to create host visible device buffer."; - } - - return DeviceBufferAllocationVK{ - .buffer = vk::Buffer{buffer}, - .backing_allocation = - { - .allocator = &allocator_, - .allocation = buffer_allocation, - .allocation_info = buffer_allocation_info, - }, - }; -} - -// |Allocator| -ISize AllocatorVK::GetMaxTextureSizeSupported() const { - // TODO(magicianA): Get correct max texture size for Vulkan. - // 4096 is the required limit, see below: - // https://registry.khronos.org/vulkan/specs/1.2-extensions/html/vkspec.html#limits-minmax - return {4096, 4096}; + return std::make_shared(desc, // + context_, // + allocator_, // + buffer_allocation, // + buffer_allocation_info, // + vk::Buffer{buffer} // + ); } } // namespace impeller diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/allocator_vk.h b/engine/src/flutter/impeller/renderer/backend/vulkan/allocator_vk.h index 02b7662340..f4a9e8ee3b 100644 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/allocator_vk.h +++ b/engine/src/flutter/impeller/renderer/backend/vulkan/allocator_vk.h @@ -26,11 +26,12 @@ class AllocatorVK final : public Allocator { fml::RefPtr vk_; VmaAllocator allocator_ = {}; - ContextVK& context_; + std::weak_ptr context_; vk::Device device_; + ISize max_texture_size_ = {4096, 4096}; bool is_valid_ = false; - AllocatorVK(ContextVK& context, + AllocatorVK(std::weak_ptr context, uint32_t vulkan_api_version, const vk::PhysicalDevice& physical_device, const vk::Device& logical_device, @@ -52,8 +53,6 @@ class AllocatorVK final : public Allocator { // |Allocator| ISize GetMaxTextureSizeSupported() const override; - DeviceBufferAllocationVK CreateHostVisibleDeviceAllocation(size_t size); - FML_DISALLOW_COPY_AND_ASSIGN(AllocatorVK); }; diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/blit_command_vk.cc b/engine/src/flutter/impeller/renderer/backend/vulkan/blit_command_vk.cc index bde1d0338c..8c27935cf8 100644 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/blit_command_vk.cc +++ b/engine/src/flutter/impeller/renderer/backend/vulkan/blit_command_vk.cc @@ -4,7 +4,7 @@ #include "impeller/renderer/backend/vulkan/blit_command_vk.h" -#include "impeller/renderer/backend/vulkan/commands_vk.h" +#include "impeller/renderer/backend/vulkan/command_encoder_vk.h" #include "impeller/renderer/backend/vulkan/texture_vk.h" namespace impeller { @@ -22,19 +22,24 @@ std::string BlitCopyTextureToTextureCommandVK::GetLabel() const { return label; } -[[nodiscard]] bool BlitCopyTextureToTextureCommandVK::Encode( - FencedCommandBufferVK* fenced_command_buffer) const { - // cast source and destination to TextureVK - const auto& source_tex_vk = TextureVK::Cast(*source); - const auto& dest_tex_vk = TextureVK::Cast(*destination); +bool BlitCopyTextureToTextureCommandVK::Encode( + CommandEncoderVK& encoder) const { + const auto& cmd_buffer = encoder.GetCommandBuffer(); - // get the vulkan image and image view - const auto source_image = source_tex_vk.GetImage(); - const auto dest_image = dest_tex_vk.GetImage(); + const auto& src = TextureVK::Cast(*source); + const auto& dst = TextureVK::Cast(*destination); + + const auto src_layout = vk::ImageLayout::eTransferSrcOptimal; + const auto dst_layout = vk::ImageLayout::eTransferDstOptimal; + + if (!src.SetLayout(src_layout, cmd_buffer) || + !dst.SetLayout(dst_layout, cmd_buffer)) { + VALIDATION_LOG << "Could not complete layout transitions."; + return false; + } - // copy the source image to the destination image, from source_region to - // destination_origin. vk::ImageCopy image_copy; + image_copy.setSrcSubresource( vk::ImageSubresourceLayers(vk::ImageAspectFlagBits::eColor, 0, 0, 1)); image_copy.setDstSubresource( @@ -47,51 +52,14 @@ std::string BlitCopyTextureToTextureCommandVK::GetLabel() const { image_copy.extent = vk::Extent3D(source_region.size.width, source_region.size.height, 1); - // get single use command buffer - auto copy_cmd = fenced_command_buffer->GetSingleUseChild(); - - vk::CommandBufferBeginInfo begin_info; - begin_info.setFlags(vk::CommandBufferUsageFlagBits::eOneTimeSubmit); - auto res = copy_cmd.begin(begin_info); - - if (res != vk::Result::eSuccess) { - VALIDATION_LOG << "Failed to begin command buffer: " << vk::to_string(res); - return false; - } - - uint32_t mip_count = source_tex_vk.GetTextureDescriptor().mip_count; - - // transition the source image to transfer source optimal - TransitionImageLayoutCommandVK transition_source_cmd = - TransitionImageLayoutCommandVK(source_image, vk::ImageLayout::eUndefined, - vk::ImageLayout::eTransferSrcOptimal, - mip_count); - bool success = transition_source_cmd.Submit(fenced_command_buffer); - if (!success) { - VALIDATION_LOG << "Failed to transition source image layout"; - return false; - } - - // transition the destination image to transfer destination optimal - TransitionImageLayoutCommandVK transition_dest_cmd = - TransitionImageLayoutCommandVK(dest_image, vk::ImageLayout::eUndefined, - vk::ImageLayout::eTransferDstOptimal, - mip_count); - success = transition_dest_cmd.Submit(fenced_command_buffer); - if (!success) { - VALIDATION_LOG << "Failed to transition destination image layout"; - return false; - } - - // issue the copy command - copy_cmd.copyImage(source_image, vk::ImageLayout::eTransferSrcOptimal, - dest_image, vk::ImageLayout::eTransferDstOptimal, - image_copy); - res = copy_cmd.end(); - if (res != vk::Result::eSuccess) { - VALIDATION_LOG << "Failed to end command buffer: " << vk::to_string(res); - return false; - } + // Issue the copy command now that the images are already in the right + // layouts. + cmd_buffer.copyImage(src.GetImage(), // + src_layout, // + dst.GetImage(), // + dst_layout, // + image_copy // + ); return true; } @@ -106,21 +74,14 @@ std::string BlitCopyTextureToBufferCommandVK::GetLabel() const { return label; } -[[nodiscard]] bool BlitCopyTextureToBufferCommandVK::Encode( - FencedCommandBufferVK* fenced_command_buffer) const { +bool BlitCopyTextureToBufferCommandVK::Encode(CommandEncoderVK& encoder) const { + const auto& cmd_buffer = encoder.GetCommandBuffer(); + // cast source and destination to TextureVK - const auto& source_tex_vk = TextureVK::Cast(*source); - const auto& dest_buf_vk = DeviceBufferVK::Cast(*destination); + const auto& src = TextureVK::Cast(*source); + const auto& dst = DeviceBufferVK::Cast(*destination); - // get the vulkan image and image view - const auto source_image = source_tex_vk.GetImage(); - - // get buffer image handle - const auto dest_buffer = dest_buf_vk.GetVKBufferHandle(); - - // copy the source image to the destination buffer, from source_region to - // destination_origin. - vk::BufferImageCopy image_copy{}; + vk::BufferImageCopy image_copy; image_copy.setBufferOffset(destination_offset); image_copy.setBufferRowLength(0); image_copy.setBufferImageHeight(0); @@ -131,37 +92,16 @@ std::string BlitCopyTextureToBufferCommandVK::GetLabel() const { image_copy.setImageExtent( vk::Extent3D(source_region.size.width, source_region.size.height, 1)); - uint32_t mip_count = source_tex_vk.GetTextureDescriptor().mip_count; - - // transition the source image to transfer source optimal - TransitionImageLayoutCommandVK transition_source_cmd = - TransitionImageLayoutCommandVK(source_image, vk::ImageLayout::eUndefined, - vk::ImageLayout::eTransferSrcOptimal, - mip_count); - bool success = transition_source_cmd.Submit(fenced_command_buffer); - if (!success) { + if (!src.SetLayout(vk::ImageLayout::eTransferSrcOptimal, cmd_buffer)) { + VALIDATION_LOG << "Could not encode layout transition."; return false; } - // get single use command buffer - auto copy_cmd = fenced_command_buffer->GetSingleUseChild(); - - vk::CommandBufferBeginInfo begin_info; - begin_info.setFlags(vk::CommandBufferUsageFlagBits::eOneTimeSubmit); - auto res = copy_cmd.begin(begin_info); - - if (res != vk::Result::eSuccess) { - VALIDATION_LOG << "Failed to begin command buffer: " << vk::to_string(res); - return false; - } - - // issue the copy command - copy_cmd.copyImageToBuffer(source_image, vk::ImageLayout::eTransferSrcOptimal, - dest_buffer, image_copy); - res = copy_cmd.end(); - if (res != vk::Result::eSuccess) { - VALIDATION_LOG << "Failed to end command buffer: " << vk::to_string(res); - } + cmd_buffer.copyImageToBuffer(src.GetImage(), // + vk::ImageLayout::eTransferSrcOptimal, // + dst.GetVKBufferHandle(), // + image_copy // + ); return true; } @@ -176,130 +116,140 @@ std::string BlitGenerateMipmapCommandVK::GetLabel() const { return label; } -[[nodiscard]] bool BlitGenerateMipmapCommandVK::Encode( - FencedCommandBufferVK* fenced_command_buffer) const { - const auto& source_tex_vk = TextureVK::Cast(*texture); - const auto source_image = source_tex_vk.GetImage(); - - const auto size = source_tex_vk.GetTextureDescriptor().size; - uint32_t mip_count = source_tex_vk.GetTextureDescriptor().mip_count; - - uint32_t mip_width = size.width; - uint32_t mip_height = size.height; - - // create the subresource range - vk::ImageSubresourceRange subresource_range{}; - subresource_range.setAspectMask(vk::ImageAspectFlagBits::eColor); - subresource_range.setBaseArrayLayer(0); - subresource_range.setLayerCount(1); - subresource_range.setLevelCount(1); - - // create a barrier to transition the image to transfer source optimal - vk::ImageMemoryBarrier barrier{}; - barrier.setImage(source_image); - barrier.setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED); - barrier.setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED); - barrier.setSubresourceRange(subresource_range); - - auto gen_mip_cmd = fenced_command_buffer->Get(); - - vk::CommandBufferBeginInfo begin_info; - begin_info.setFlags(vk::CommandBufferUsageFlagBits::eOneTimeSubmit); - auto begin_res = gen_mip_cmd.begin(begin_info); - - if (begin_res != vk::Result::eSuccess) { - VALIDATION_LOG << "Failed to begin command buffer: " - << vk::to_string(begin_res); - return false; +static void InsertImageMemoryBarrier(const vk::CommandBuffer& cmd, + const vk::Image& image, + vk::AccessFlags src_access_mask, + vk::AccessFlags dst_access_mask, + vk::ImageLayout old_layout, + vk::ImageLayout new_layout, + vk::PipelineStageFlags src_stage, + vk::PipelineStageFlags dst_stage, + uint32_t base_mip_level, + uint32_t mip_level_count = 1u) { + if (old_layout == new_layout) { + return; } - // transition all layers to transfer dst optimal - for (uint32_t i = 0; i < mip_count; i++) { - barrier.subresourceRange.baseMipLevel = i; - barrier.oldLayout = vk::ImageLayout::eUndefined; - barrier.newLayout = vk::ImageLayout::eTransferDstOptimal; - barrier.srcAccessMask = vk::AccessFlagBits::eTransferWrite; - barrier.dstAccessMask = vk::AccessFlagBits::eTransferWrite; + vk::ImageMemoryBarrier barrier; + barrier.srcAccessMask = src_access_mask; + barrier.dstAccessMask = dst_access_mask; + barrier.oldLayout = old_layout; + barrier.newLayout = new_layout; + barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + barrier.image = image; + barrier.subresourceRange.aspectMask = vk::ImageAspectFlagBits::eColor; + barrier.subresourceRange.baseMipLevel = base_mip_level; + barrier.subresourceRange.levelCount = mip_level_count; + barrier.subresourceRange.baseArrayLayer = 0u; + barrier.subresourceRange.layerCount = 1u; - gen_mip_cmd.pipelineBarrier(vk::PipelineStageFlagBits::eTransfer, - vk::PipelineStageFlagBits::eTransfer, {}, - nullptr, nullptr, barrier); + cmd.pipelineBarrier(src_stage, dst_stage, {}, nullptr, nullptr, barrier); +} + +bool BlitGenerateMipmapCommandVK::Encode(CommandEncoderVK& encoder) const { + const auto& src = TextureVK::Cast(*texture); + + const auto size = src.GetTextureDescriptor().size; + uint32_t mip_count = src.GetTextureDescriptor().mip_count; + + if (mip_count < 2u) { + return true; } - for (uint32_t i = 1; i < mip_count; i++) { - barrier.subresourceRange.baseMipLevel = i - 1; - barrier.oldLayout = vk::ImageLayout::eTransferDstOptimal; - barrier.newLayout = vk::ImageLayout::eTransferSrcOptimal; - barrier.srcAccessMask = vk::AccessFlagBits::eTransferWrite; - barrier.dstAccessMask = vk::AccessFlagBits::eTransferRead; + const auto& image = src.GetImage(); + const auto& cmd = encoder.GetCommandBuffer(); - gen_mip_cmd.pipelineBarrier(vk::PipelineStageFlagBits::eTransfer, - vk::PipelineStageFlagBits::eTransfer, {}, - nullptr, nullptr, barrier); + // Transition the base mip level to transfer-src layout so we can read from + // it and transition the rest to dst-optimal since they are going to be + // written to. + InsertImageMemoryBarrier( + cmd, // command buffer + image, // image + vk::AccessFlagBits::eTransferWrite, // src access mask + vk::AccessFlagBits::eTransferRead, // dst access mask + src.GetLayout(), // old layout + vk::ImageLayout::eTransferSrcOptimal, // new layout + vk::PipelineStageFlagBits::eTransfer, // src stage + vk::PipelineStageFlagBits::eTransfer, // dst stage + 0u // mip level + ); + InsertImageMemoryBarrier( + cmd, // command buffer + image, // image + {}, // src access mask + vk::AccessFlagBits::eTransferWrite, // dst access mask + vk::ImageLayout::eUndefined, // old layout + vk::ImageLayout::eTransferDstOptimal, // new layout + vk::PipelineStageFlagBits::eTransfer, // src stage + vk::PipelineStageFlagBits::eTransfer, // dst stage + 1u, // mip level + mip_count - 1 // mip level count + ); - vk::ImageBlit blit{}; + // Blit from the base mip level to all other levels. + for (size_t mip_level = 1u; mip_level < mip_count; mip_level++) { + vk::ImageBlit blit; - // src - blit.srcOffsets[0] = vk::Offset3D(0, 0, 0); - blit.srcOffsets[1] = vk::Offset3D(mip_width, mip_height, 1); blit.srcSubresource.aspectMask = vk::ImageAspectFlagBits::eColor; - blit.srcSubresource.mipLevel = i - 1; - blit.srcSubresource.baseArrayLayer = 0; - blit.srcSubresource.layerCount = 1; + blit.srcSubresource.baseArrayLayer = 0u; + blit.srcSubresource.layerCount = 1u; + blit.srcSubresource.mipLevel = 0u; - // dst - blit.dstOffsets[0] = vk::Offset3D(0, 0, 0); - blit.dstOffsets[1] = vk::Offset3D(mip_width > 1 ? mip_width / 2 : 1, - mip_height > 1 ? mip_height / 2 : 1, 1); blit.dstSubresource.aspectMask = vk::ImageAspectFlagBits::eColor; - blit.dstSubresource.mipLevel = i; - blit.dstSubresource.baseArrayLayer = 0; - blit.dstSubresource.layerCount = 1; + blit.dstSubresource.baseArrayLayer = 0u; + blit.dstSubresource.layerCount = 1u; + blit.dstSubresource.mipLevel = mip_level; - gen_mip_cmd.blitImage(source_image, vk::ImageLayout::eTransferSrcOptimal, - source_image, vk::ImageLayout::eTransferDstOptimal, - blit, vk::Filter::eLinear); + // offsets[0] is origin. + blit.srcOffsets[1].x = size.width; + blit.srcOffsets[1].y = size.height; - // transition the previous mip level to shader read only optimal - barrier.oldLayout = vk::ImageLayout::eUndefined; - barrier.newLayout = vk::ImageLayout::eShaderReadOnlyOptimal; - barrier.srcAccessMask = vk::AccessFlagBits::eTransferRead; - barrier.dstAccessMask = vk::AccessFlagBits::eShaderRead; + // offsets[0] is origin. + blit.dstOffsets[1].x = size.width >> mip_level; + blit.dstOffsets[1].y = size.height >> mip_level; - gen_mip_cmd.pipelineBarrier(vk::PipelineStageFlagBits::eTransfer, - vk::PipelineStageFlagBits::eFragmentShader, {}, - nullptr, nullptr, barrier); - - if (mip_width > 1) { - mip_width /= 2; - } - - if (mip_height > 1) { - mip_height /= 2; - } + cmd.blitImage(image, // src image + vk::ImageLayout::eTransferSrcOptimal, // src layout + image, // dst image + vk::ImageLayout::eTransferDstOptimal, // dst layout + 1u, // region count + &blit, // regions + vk::Filter::eLinear // filter + ); } - // transition the last mip level to shader read only optimal - barrier.subresourceRange.baseMipLevel = mip_count - 1; - barrier.oldLayout = vk::ImageLayout::eUndefined; - barrier.newLayout = vk::ImageLayout::eShaderReadOnlyOptimal; - barrier.srcAccessMask = vk::AccessFlagBits::eTransferRead; - barrier.dstAccessMask = vk::AccessFlagBits::eShaderRead; + // Transition all mip levels to shader read. The base mip level has a + // different "old" layout than the rest now. + InsertImageMemoryBarrier( + cmd, // command buffer + image, // image + vk::AccessFlagBits::eTransferRead, // src access mask + vk::AccessFlagBits::eShaderRead, // dst access mask + vk::ImageLayout::eTransferSrcOptimal, // old layout + vk::ImageLayout::eShaderReadOnlyOptimal, // new layout + vk::PipelineStageFlagBits::eTransfer, // src stage + vk::PipelineStageFlagBits::eAllGraphics, // dst stage + 0u // mip level + ); + InsertImageMemoryBarrier( + cmd, // command buffer + image, // image + vk::AccessFlagBits::eTransferRead, // src access mask + vk::AccessFlagBits::eShaderRead, // dst access mask + vk::ImageLayout::eTransferDstOptimal, // old layout + vk::ImageLayout::eShaderReadOnlyOptimal, // new layout + vk::PipelineStageFlagBits::eTransfer, // src stage + vk::PipelineStageFlagBits::eAllGraphics, // dst stage + 1u, // mip level + mip_count - 1 // mip level count + ); - gen_mip_cmd.pipelineBarrier(vk::PipelineStageFlagBits::eTransfer, - vk::PipelineStageFlagBits::eFragmentShader, {}, - nullptr, nullptr, barrier); - - // submit the command buffer - auto res = gen_mip_cmd.end(); - if (res != vk::Result::eSuccess) { - VALIDATION_LOG << "Failed to end command buffer: " << vk::to_string(res); - return false; - } + // We modified the layouts of this image from underneath it. Tell it its new + // state so it doesn't try to perform redundant transitions under the hood. + src.SetLayoutWithoutEncoding(vk::ImageLayout::eShaderReadOnlyOptimal); return true; } -// END: BlitGenerateMipmapCommandVK - } // namespace impeller diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/blit_command_vk.h b/engine/src/flutter/impeller/renderer/backend/vulkan/blit_command_vk.h index dda7f4266b..4e84d931b7 100644 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/blit_command_vk.h +++ b/engine/src/flutter/impeller/renderer/backend/vulkan/blit_command_vk.h @@ -7,20 +7,21 @@ #include #include "impeller/base/backend_cast.h" #include "impeller/renderer/backend/vulkan/context_vk.h" -#include "impeller/renderer/backend/vulkan/fenced_command_buffer_vk.h" #include "impeller/renderer/blit_command.h" #include "impeller/renderer/context.h" namespace impeller { +class CommandEncoderVK; + +// TODO(csg): Should these be backend castable to blit command? /// Mixin for dispatching Vulkan commands. struct BlitEncodeVK : BackendCast { virtual ~BlitEncodeVK(); virtual std::string GetLabel() const = 0; - [[nodiscard]] virtual bool Encode( - FencedCommandBufferVK* fenced_command_buffer) const = 0; + [[nodiscard]] virtual bool Encode(CommandEncoderVK& encoder) const = 0; }; struct BlitCopyTextureToTextureCommandVK @@ -30,8 +31,7 @@ struct BlitCopyTextureToTextureCommandVK std::string GetLabel() const override; - [[nodiscard]] bool Encode( - FencedCommandBufferVK* fenced_command_buffer) const override; + [[nodiscard]] bool Encode(CommandEncoderVK& encoder) const override; }; struct BlitCopyTextureToBufferCommandVK : public BlitCopyTextureToBufferCommand, @@ -40,8 +40,7 @@ struct BlitCopyTextureToBufferCommandVK : public BlitCopyTextureToBufferCommand, std::string GetLabel() const override; - [[nodiscard]] bool Encode( - FencedCommandBufferVK* fenced_command_buffer) const override; + [[nodiscard]] bool Encode(CommandEncoderVK& encoder) const override; }; struct BlitGenerateMipmapCommandVK : public BlitGenerateMipmapCommand, @@ -50,8 +49,7 @@ struct BlitGenerateMipmapCommandVK : public BlitGenerateMipmapCommand, std::string GetLabel() const override; - [[nodiscard]] bool Encode( - FencedCommandBufferVK* fenced_command_buffer) const override; + [[nodiscard]] bool Encode(CommandEncoderVK& encoder) const override; }; } // namespace impeller diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/blit_pass_vk.cc b/engine/src/flutter/impeller/renderer/backend/vulkan/blit_pass_vk.cc index bdbd5915dc..f563681af3 100644 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/blit_pass_vk.cc +++ b/engine/src/flutter/impeller/renderer/backend/vulkan/blit_pass_vk.cc @@ -9,8 +9,8 @@ namespace impeller { -BlitPassVK::BlitPassVK(std::shared_ptr command_buffer) - : command_buffer_(std::move(command_buffer)) {} +BlitPassVK::BlitPassVK(std::weak_ptr encoder) + : encoder_(std::move(encoder)) {} BlitPassVK::~BlitPassVK() = default; @@ -23,7 +23,7 @@ void BlitPassVK::OnSetLabel(std::string label) { // |BlitPass| bool BlitPassVK::IsValid() const { - return command_buffer_ != nullptr; + return true; } // |BlitPass| @@ -35,9 +35,13 @@ bool BlitPassVK::EncodeCommands( return false; } + auto encoder = encoder_.lock(); + if (!encoder) { + return false; + } + for (auto& command : commands_) { - bool encode_res = command->Encode(command_buffer_.get()); - if (!encode_res) { + if (!command->Encode(*encoder)) { return false; } } @@ -53,6 +57,7 @@ bool BlitPassVK::OnCopyTextureToTextureCommand( IPoint destination_origin, std::string label) { auto command = std::make_unique(); + command->source = std::move(source); command->destination = std::move(destination); command->source_region = source_region; @@ -71,6 +76,7 @@ bool BlitPassVK::OnCopyTextureToBufferCommand( size_t destination_offset, std::string label) { auto command = std::make_unique(); + command->source = std::move(source); command->destination = std::move(destination); command->source_region = source_region; @@ -85,6 +91,7 @@ bool BlitPassVK::OnCopyTextureToBufferCommand( bool BlitPassVK::OnGenerateMipmapCommand(std::shared_ptr texture, std::string label) { auto command = std::make_unique(); + command->texture = std::move(texture); command->label = std::move(label); diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/blit_pass_vk.h b/engine/src/flutter/impeller/renderer/backend/vulkan/blit_pass_vk.h index aa8a3919e8..62e52c1547 100644 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/blit_pass_vk.h +++ b/engine/src/flutter/impeller/renderer/backend/vulkan/blit_pass_vk.h @@ -6,25 +6,26 @@ #include "flutter/fml/macros.h" #include "impeller/renderer/backend/vulkan/blit_command_vk.h" -#include "impeller/renderer/backend/vulkan/fenced_command_buffer_vk.h" #include "impeller/renderer/blit_pass.h" namespace impeller { +class CommandEncoderVK; + class BlitPassVK final : public BlitPass { public: - explicit BlitPassVK(std::shared_ptr command_buffer); - // |BlitPass| ~BlitPassVK() override; private: friend class CommandBufferVK; - std::shared_ptr command_buffer_; + std::weak_ptr encoder_; std::vector> commands_; std::string label_; + BlitPassVK(std::weak_ptr encoder); + // |BlitPass| bool IsValid() const override; diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/command_buffer_vk.cc b/engine/src/flutter/impeller/renderer/backend/vulkan/command_buffer_vk.cc index 01fc6f3dff..b024d0be45 100644 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/command_buffer_vk.cc +++ b/engine/src/flutter/impeller/renderer/backend/vulkan/command_buffer_vk.cc @@ -10,8 +10,8 @@ #include "flutter/fml/logging.h" #include "impeller/base/validation.h" #include "impeller/renderer/backend/vulkan/blit_pass_vk.h" +#include "impeller/renderer/backend/vulkan/command_encoder_vk.h" #include "impeller/renderer/backend/vulkan/context_vk.h" -#include "impeller/renderer/backend/vulkan/fenced_command_buffer_vk.h" #include "impeller/renderer/backend/vulkan/formats_vk.h" #include "impeller/renderer/backend/vulkan/render_pass_vk.h" #include "impeller/renderer/command_buffer.h" @@ -19,49 +19,35 @@ namespace impeller { -std::shared_ptr CommandBufferVK::Create( - const std::weak_ptr& context_arg, - vk::Device device) { - if (auto context = context_arg.lock()) { - auto context_vk = reinterpret_cast(context.get()); - auto queue = context_vk->GetGraphicsQueue(); - auto command_pool = context_vk->CreateGraphicsCommandPool(); - auto fenced_command_buffer = std::make_shared( - device, queue, command_pool->Get()); - return std::make_shared( - context, device, std::move(command_pool), fenced_command_buffer); - } else { - return nullptr; +CommandBufferVK::CommandBufferVK(std::weak_ptr context, + std::shared_ptr encoder) + : CommandBuffer(std::move(context)), encoder_(std::move(encoder)) { + if (!encoder_ || !encoder_->IsValid()) { + return; } -} - -CommandBufferVK::CommandBufferVK( - std::weak_ptr context, - vk::Device device, - std::unique_ptr command_pool, - std::shared_ptr command_buffer) - : CommandBuffer(std::move(context)), - device_(device), - command_pool_(std::move(command_pool)), - fenced_command_buffer_(std::move(command_buffer)) { is_valid_ = true; } CommandBufferVK::~CommandBufferVK() = default; void CommandBufferVK::SetLabel(const std::string& label) const { - if (auto context = context_.lock()) { - reinterpret_cast(context.get()) - ->SetDebugName(fenced_command_buffer_->Get(), label); + auto context = context_.lock(); + if (!context || !encoder_) { + return; } + ContextVK::Cast(*context).SetDebugName(encoder_->GetCommandBuffer(), label); } bool CommandBufferVK::IsValid() const { return is_valid_; } +const std::shared_ptr& CommandBufferVK::GetEncoder() const { + return encoder_; +} + bool CommandBufferVK::OnSubmitCommands(CompletionCallback callback) { - bool submit = fenced_command_buffer_->Submit(); + const auto submit = encoder_->Submit(); if (callback) { callback(submit ? CommandBuffer::Status::kCompleted : CommandBuffer::Status::kError); @@ -71,71 +57,34 @@ bool CommandBufferVK::OnSubmitCommands(CompletionCallback callback) { std::shared_ptr CommandBufferVK::OnCreateRenderPass( RenderTarget target) { - std::vector color_attachments; - for (const auto& [k, attachment] : target.GetColorAttachments()) { - const TextureDescriptor& tex_desc = - attachment.texture->GetTextureDescriptor(); - - vk::AttachmentDescription color_attachment; - color_attachment.setFormat(ToVKImageFormat(tex_desc.format)); - color_attachment.setSamples(ToVKSampleCountFlagBits(tex_desc.sample_count)); - color_attachment.setLoadOp(ToVKAttachmentLoadOp(attachment.load_action)); - color_attachment.setStoreOp(ToVKAttachmentStoreOp(attachment.store_action)); - - color_attachment.setStencilLoadOp(vk::AttachmentLoadOp::eDontCare); - color_attachment.setStencilStoreOp(vk::AttachmentStoreOp::eDontCare); - color_attachment.setInitialLayout(vk::ImageLayout::eColorAttachmentOptimal); - color_attachment.setFinalLayout(vk::ImageLayout::ePresentSrcKHR); - - color_attachments.push_back(color_attachment); - } - - // TODO (kaushikiska): support depth and stencil attachments. - - vk::AttachmentReference color_attachment_ref; - color_attachment_ref.setAttachment(0); - color_attachment_ref.setLayout(vk::ImageLayout::eColorAttachmentOptimal); - - vk::SubpassDescription subpass_desc; - subpass_desc.setPipelineBindPoint(vk::PipelineBindPoint::eGraphics); - subpass_desc.setColorAttachmentCount(color_attachments.size()); - subpass_desc.setPColorAttachments(&color_attachment_ref); - - vk::RenderPassCreateInfo render_pass_create; - render_pass_create.setAttachmentCount(color_attachments.size()); - render_pass_create.setPAttachments(color_attachments.data()); - render_pass_create.setSubpassCount(1); - render_pass_create.setPSubpasses(&subpass_desc); - - auto render_pass_create_res = device_.createRenderPass(render_pass_create); - if (render_pass_create_res.result != vk::Result::eSuccess) { - VALIDATION_LOG << "Failed to create render pass: " - << vk::to_string(render_pass_create_res.result); + auto context = context_.lock(); + if (!context) { return nullptr; } - - vk::RenderPass render_pass = render_pass_create_res.value; - return std::make_shared(context_, device_, std::move(target), - fenced_command_buffer_, render_pass); -} - -std::shared_ptr CommandBufferVK::OnCreateBlitPass() const { - // TODO(kaushikiska): https://github.com/flutter/flutter/issues/112649 - if (!IsValid()) { - return nullptr; - } - - auto pass = std::make_shared(fenced_command_buffer_); + auto pass = std::shared_ptr(new RenderPassVK(context, // + target, // + encoder_ //) + )); if (!pass->IsValid()) { return nullptr; } + return pass; +} +std::shared_ptr CommandBufferVK::OnCreateBlitPass() const { + if (!IsValid()) { + return nullptr; + } + auto pass = std::shared_ptr(new BlitPassVK(encoder_)); + if (!pass->IsValid()) { + return nullptr; + } return pass; } std::shared_ptr CommandBufferVK::OnCreateComputePass() const { - // TODO(dnfield): https://github.com/flutter/flutter/issues/110622 - VALIDATION_LOG << "ComputePasses unimplemented for Vulkan"; + // TODO(110622): Wire up compute passes in Vulkan. + IMPELLER_UNIMPLEMENTED; return nullptr; } diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/command_buffer_vk.h b/engine/src/flutter/impeller/renderer/backend/vulkan/command_buffer_vk.h index 74be5d91d5..eb1ff0fa01 100644 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/command_buffer_vk.h +++ b/engine/src/flutter/impeller/renderer/backend/vulkan/command_buffer_vk.h @@ -5,37 +5,33 @@ #pragma once #include "flutter/fml/macros.h" -#include "impeller/renderer/backend/vulkan/command_pool_vk.h" -#include "impeller/renderer/backend/vulkan/fenced_command_buffer_vk.h" -#include "impeller/renderer/backend/vulkan/surface_producer_vk.h" +#include "impeller/base/backend_cast.h" #include "impeller/renderer/backend/vulkan/vk.h" #include "impeller/renderer/command_buffer.h" namespace impeller { -class CommandBufferVK final : public CommandBuffer { +class ContextVK; +class CommandEncoderVK; + +class CommandBufferVK final + : public CommandBuffer, + public BackendCast { public: - static std::shared_ptr Create( - const std::weak_ptr& context, - vk::Device device); - - CommandBufferVK(std::weak_ptr context, - vk::Device device, - std::unique_ptr command_pool, - std::shared_ptr command_buffer); - // |CommandBuffer| ~CommandBufferVK() override; + const std::shared_ptr& GetEncoder() const; + private: friend class ContextVK; - vk::Device device_; - std::unique_ptr command_pool_; - vk::UniqueRenderPass render_pass_; - std::shared_ptr fenced_command_buffer_; + std::shared_ptr encoder_; bool is_valid_ = false; + CommandBufferVK(std::weak_ptr context, + std::shared_ptr encoder); + // |CommandBuffer| void SetLabel(const std::string& label) const override; diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/command_encoder_vk.cc b/engine/src/flutter/impeller/renderer/backend/vulkan/command_encoder_vk.cc new file mode 100644 index 0000000000..6fbf12950f --- /dev/null +++ b/engine/src/flutter/impeller/renderer/backend/vulkan/command_encoder_vk.cc @@ -0,0 +1,120 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/command_encoder_vk.h" + +#include "flutter/fml/closure.h" +#include "impeller/renderer/backend/vulkan/context_vk.h" + +namespace impeller { + +CommandEncoderVK::CommandEncoderVK(vk::Device device, + vk::Queue queue, + vk::CommandPool pool) { + vk::CommandBufferAllocateInfo alloc_info; + alloc_info.commandPool = pool; + alloc_info.commandBufferCount = 1u; + alloc_info.level = vk::CommandBufferLevel::ePrimary; + auto [result, buffers] = device.allocateCommandBuffersUnique(alloc_info); + if (result != vk::Result::eSuccess) { + VALIDATION_LOG << "Could not create command buffer."; + return; + } + vk::CommandBufferBeginInfo begin_info; + begin_info.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit; + if (buffers[0]->begin(begin_info) != vk::Result::eSuccess) { + VALIDATION_LOG << "Could not begin command buffer."; + return; + } + device_ = device; + queue_ = queue; + command_buffer_ = std::move(buffers[0]); + is_valid_ = true; +} + +CommandEncoderVK::~CommandEncoderVK() = default; + +bool CommandEncoderVK::IsValid() const { + return is_valid_; +} + +bool CommandEncoderVK::Submit() { + if (!IsValid()) { + return false; + } + + // Success or failure, you only get to submit once. + fml::ScopedCleanupClosure reset([&]() { Reset(); }); + + if (command_buffer_->end() != vk::Result::eSuccess) { + return false; + } + auto [fence_result, fence] = device_.createFenceUnique({}); + if (fence_result != vk::Result::eSuccess) { + return false; + } + vk::SubmitInfo submit_info; + submit_info.setCommandBuffers(*command_buffer_); + if (queue_.submit(submit_info, *fence) != vk::Result::eSuccess) { + return false; + } + if (device_.waitForFences( + *fence, // fences + true, // wait all + std::numeric_limits::max() // timeout (ns) + ) != vk::Result::eSuccess) { + return false; + } + + return true; +} + +const vk::CommandBuffer& CommandEncoderVK::GetCommandBuffer() const { + return *command_buffer_; +} + +void CommandEncoderVK::Reset() { + command_buffer_.reset(); + + tracked_objects_.clear(); + tracked_buffers_.clear(); + tracked_textures_.clear(); + + queue_ = nullptr; + device_ = nullptr; + is_valid_ = false; +} + +bool CommandEncoderVK::Track(std::shared_ptr object) { + tracked_objects_.push_back(std::move(object)); + return true; +} + +bool CommandEncoderVK::Track(std::shared_ptr buffer) { + tracked_buffers_.emplace_back(std::move(buffer)); + return true; +} + +bool CommandEncoderVK::Track(std::shared_ptr texture) { + tracked_textures_.emplace_back(std::move(texture)); + return true; +} + +void CommandEncoderVK::PushDebugGroup(const char* label) const { + if (!vk::HasValidationLayers() || !command_buffer_) { + return; + } + vk::DebugUtilsLabelEXT label_info; + label_info.pLabelName = label; + command_buffer_->beginDebugUtilsLabelEXT(label_info); +} + +void CommandEncoderVK::PopDebugGroup() const { + if (!vk::HasValidationLayers() || !command_buffer_) { + return; + } + command_buffer_->endDebugUtilsLabelEXT(); +} + +} // namespace impeller diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/command_encoder_vk.h b/engine/src/flutter/impeller/renderer/backend/vulkan/command_encoder_vk.h new file mode 100644 index 0000000000..66ac47f39b --- /dev/null +++ b/engine/src/flutter/impeller/renderer/backend/vulkan/command_encoder_vk.h @@ -0,0 +1,57 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#pragma once + +#include + +#include "flutter/fml/macros.h" +#include "impeller/renderer/backend/vulkan/shared_object_vk.h" +#include "impeller/renderer/backend/vulkan/vk.h" + +namespace impeller { + +class ContextVK; +class DeviceBuffer; +class Texture; + +class CommandEncoderVK { + public: + ~CommandEncoderVK(); + + bool IsValid() const; + + bool Submit(); + + bool Track(std::shared_ptr object); + + bool Track(std::shared_ptr buffer); + + bool Track(std::shared_ptr texture); + + const vk::CommandBuffer& GetCommandBuffer() const; + + void PushDebugGroup(const char* label) const; + + void PopDebugGroup() const; + + private: + friend class ContextVK; + + vk::Device device_ = {}; + vk::Queue queue_ = {}; + vk::UniqueCommandBuffer command_buffer_; + std::vector> tracked_objects_; + std::vector> tracked_buffers_; + std::vector> tracked_textures_; + bool is_valid_ = false; + + CommandEncoderVK(vk::Device device, vk::Queue queue, vk::CommandPool pool); + + void Reset(); + + FML_DISALLOW_COPY_AND_ASSIGN(CommandEncoderVK); +}; + +} // namespace impeller diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/command_pool_vk.cc b/engine/src/flutter/impeller/renderer/backend/vulkan/command_pool_vk.cc deleted file mode 100644 index 0655824024..0000000000 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/command_pool_vk.cc +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "impeller/renderer/backend/vulkan/command_pool_vk.h" - -namespace impeller { - -std::unique_ptr CommandPoolVK::Create(vk::Device device, - uint32_t queue_index) { - vk::CommandPoolCreateInfo create_info; - create_info.setQueueFamilyIndex(queue_index); - - auto res = device.createCommandPoolUnique(create_info); - if (res.result != vk::Result::eSuccess) { - FML_CHECK(false) << "Failed to create command pool: " - << vk::to_string(res.result); - return nullptr; - } - - return std::make_unique(std::move(res.value)); -} - -vk::CommandPool CommandPoolVK::Get() const { - return *command_pool_; -} - -CommandPoolVK::CommandPoolVK(vk::UniqueCommandPool command_pool) - : command_pool_(std::move(command_pool)) {} - -CommandPoolVK::~CommandPoolVK() = default; - -} // namespace impeller diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/command_pool_vk.h b/engine/src/flutter/impeller/renderer/backend/vulkan/command_pool_vk.h deleted file mode 100644 index 034813ed49..0000000000 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/command_pool_vk.h +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#pragma once - -#include "flutter/fml/macros.h" -#include "impeller/renderer/backend/vulkan/vk.h" - -namespace impeller { - -class CommandPoolVK { - public: - static std::unique_ptr Create(vk::Device device, - uint32_t queue_index); - - explicit CommandPoolVK(vk::UniqueCommandPool command_pool); - - ~CommandPoolVK(); - - vk::CommandPool Get() const; - - private: - vk::UniqueCommandPool command_pool_; - - FML_DISALLOW_COPY_AND_ASSIGN(CommandPoolVK); -}; - -} // namespace impeller diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/commands_vk.cc b/engine/src/flutter/impeller/renderer/backend/vulkan/commands_vk.cc deleted file mode 100644 index eda6462d76..0000000000 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/commands_vk.cc +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "impeller/renderer/backend/vulkan/commands_vk.h" - -namespace impeller { - -TransitionImageLayoutCommandVK::TransitionImageLayoutCommandVK( - vk::Image image, - vk::ImageLayout old_layout, - vk::ImageLayout new_layout, - uint32_t mip_levels) - : image_(image), - old_layout_(old_layout), - new_layout_(new_layout), - mip_levels_(mip_levels) {} - -TransitionImageLayoutCommandVK::~TransitionImageLayoutCommandVK() = default; - -bool TransitionImageLayoutCommandVK::Submit( - FencedCommandBufferVK* command_buffer) { - if (!command_buffer) { - return false; - } - - vk::ImageMemoryBarrier barrier = - vk::ImageMemoryBarrier() - .setSrcAccessMask(vk::AccessFlagBits::eColorAttachmentWrite | - vk::AccessFlagBits::eTransferWrite) - .setDstAccessMask(vk::AccessFlagBits::eColorAttachmentRead | - vk::AccessFlagBits::eShaderRead) - .setOldLayout(old_layout_) - .setNewLayout(new_layout_) - .setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED) - .setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED) - .setImage(image_) - .setSubresourceRange( - vk::ImageSubresourceRange() - .setAspectMask(vk::ImageAspectFlagBits::eColor) - .setBaseMipLevel(0) - .setLevelCount(mip_levels_) - .setBaseArrayLayer(0) - .setLayerCount(1)); - - vk::PipelineStageFlags src_stage = vk::PipelineStageFlagBits::eAllGraphics; - vk::PipelineStageFlags dst_stage = vk::PipelineStageFlagBits::eAllGraphics; - - auto transition_cmd = command_buffer->GetSingleUseChild(); - - vk::CommandBufferBeginInfo begin_info; - begin_info.setFlags(vk::CommandBufferUsageFlagBits::eOneTimeSubmit); - auto res = transition_cmd.begin(begin_info); - - if (res != vk::Result::eSuccess) { - FML_LOG(ERROR) << "Failed to begin command buffer: " << vk::to_string(res); - return false; - } - - transition_cmd.pipelineBarrier(src_stage, dst_stage, {}, nullptr, nullptr, - barrier); - res = transition_cmd.end(); - if (res != vk::Result::eSuccess) { - FML_LOG(ERROR) << "Failed to end command buffer: " << vk::to_string(res); - return false; - } - - return true; -} - -} // namespace impeller diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/commands_vk.h b/engine/src/flutter/impeller/renderer/backend/vulkan/commands_vk.h deleted file mode 100644 index 7bbd60ed72..0000000000 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/commands_vk.h +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#pragma once - -#include "impeller/renderer/backend/vulkan/context_vk.h" -#include "impeller/renderer/backend/vulkan/fenced_command_buffer_vk.h" - -// Set of common utility commands for Vulkan. -namespace impeller { - -class TransitionImageLayoutCommandVK { - public: - TransitionImageLayoutCommandVK(vk::Image image, - vk::ImageLayout old_layout, - vk::ImageLayout new_layout, - uint32_t mip_levels); - - ~TransitionImageLayoutCommandVK(); - - bool Submit(FencedCommandBufferVK* command_buffer); - - private: - vk::Image image_; - vk::ImageLayout old_layout_; - vk::ImageLayout new_layout_; - uint32_t mip_levels_; - - FML_DISALLOW_COPY_AND_ASSIGN(TransitionImageLayoutCommandVK); -}; - -} // namespace impeller diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/context_vk.cc b/engine/src/flutter/impeller/renderer/backend/vulkan/context_vk.cc index 2330f9a78f..41594818f7 100644 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/context_vk.cc +++ b/engine/src/flutter/impeller/renderer/backend/vulkan/context_vk.cc @@ -2,8 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// FLUTTER_NOLINT: https://github.com/flutter/flutter/issues/68331 - #include "impeller/renderer/backend/vulkan/context_vk.h" #include @@ -21,10 +19,9 @@ #include "impeller/renderer/backend/vulkan/allocator_vk.h" #include "impeller/renderer/backend/vulkan/capabilities_vk.h" #include "impeller/renderer/backend/vulkan/command_buffer_vk.h" -#include "impeller/renderer/backend/vulkan/deletion_queue_vk.h" +#include "impeller/renderer/backend/vulkan/command_encoder_vk.h" #include "impeller/renderer/backend/vulkan/formats_vk.h" -#include "impeller/renderer/backend/vulkan/surface_producer_vk.h" -#include "impeller/renderer/backend/vulkan/swapchain_details_vk.h" +#include "impeller/renderer/backend/vulkan/surface_vk.h" #include "impeller/renderer/backend/vulkan/vk.h" #include "impeller/renderer/device_capabilities.h" @@ -32,23 +29,34 @@ VULKAN_HPP_DEFAULT_DISPATCH_LOADER_DYNAMIC_STORAGE namespace { +// TODO(csg): Mimic vulkan_debug_report.cc for prettier reports. VKAPI_ATTR VkBool32 VKAPI_CALL DebugUtilsMessengerCallback( VkDebugUtilsMessageSeverityFlagBitsEXT severity, VkDebugUtilsMessageTypeFlagsEXT type, const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData, void* pUserData) { - const auto prefix = impeller::vk::to_string( - impeller::vk::DebugUtilsMessageSeverityFlagBitsEXT{severity}); - // There isn't stable messageIdNumber for this validation failure. if (strstr(pCallbackData->pMessageIdName, "CoreValidation-Shader-OutputNotConsumed") != nullptr) { return VK_FALSE; } - FML_DCHECK(false) << prefix << "[" << pCallbackData->messageIdNumber << "][" - << pCallbackData->pMessageIdName - << "] : " << pCallbackData->pMessage; + if (pCallbackData->messageIdNumber == static_cast(0x82ae5050)) { + // This is a real error but we can't fix it due to our headers being too + // old. More more details see: + // https://vulkan.lunarg.com/doc/view/1.3.224.1/mac/1.3-extensions/vkspec.html#VUID-VkImageViewCreateInfo-imageViewFormatSwizzle-04465 + // This validation error currently only trips on macOS due to the use of + // texture swizzles. + return VK_FALSE; + } + + const auto prefix = impeller::vk::to_string( + impeller::vk::DebugUtilsMessageSeverityFlagBitsEXT{severity}); + // Just so that the log doesn't say FML_DCHECK(false). + constexpr bool kVulkanValidationFailure = false; + FML_DCHECK(kVulkanValidationFailure) + << prefix << "[" << pCallbackData->messageIdNumber << "][" + << pCallbackData->pMessageIdName << "] : " << pCallbackData->pMessage; // The return value of this callback controls whether the Vulkan call that // caused the validation message will be aborted or not We return VK_TRUE as @@ -125,7 +133,9 @@ static std::vector HasRequiredExtensions( static vk::PhysicalDeviceFeatures GetRequiredPhysicalDeviceFeatures() { vk::PhysicalDeviceFeatures features; +#ifndef NDEBUG features.setRobustBufferAccess(true); +#endif // NDEBUG return features; }; @@ -203,23 +213,6 @@ static std::optional PickQueue(const vk::PhysicalDevice& device, return std::nullopt; } -static std::optional PickPresentQueue(const vk::PhysicalDevice& device, - vk::SurfaceKHR surface) { - const auto families = device.getQueueFamilyProperties(); - for (size_t i = 0u; i < families.size(); i++) { - auto res = device.getSurfaceSupportKHR(i, surface); - if (res.result != vk::Result::eSuccess) { - continue; - } - vk::Bool32 present_supported = res.value; - if (present_supported) { - return QueueVK{.family = i, .index = 0}; - } - } - VALIDATION_LOG << "No present queue found."; - return std::nullopt; -} - std::shared_ptr ContextVK::Create( PFN_vkGetInstanceProcAddr proc_address_callback, const std::vector>& shader_libraries_data, @@ -396,15 +389,20 @@ ContextVK::ContextVK( debug_messenger = std::move(debug_messenger_result.value); } + //---------------------------------------------------------------------------- + /// Pick the physical device. + /// auto physical_device = PickPhysicalDevice(instance.value.get()); if (!physical_device.has_value()) { VALIDATION_LOG << "No valid Vulkan device found."; return; } + //---------------------------------------------------------------------------- + /// Pick device queues. + /// auto graphics_queue = PickQueue(physical_device.value(), vk::QueueFlagBits::eGraphics); - graphics_queue_idx_ = graphics_queue->index; auto transfer_queue = PickQueue(physical_device.value(), vk::QueueFlagBits::eTransfer); auto compute_queue = @@ -429,6 +427,7 @@ ContextVK::ContextVK( const auto required_features = GetRequiredPhysicalDeviceFeatures(); vk::DeviceCreateInfo device_info; + device_info.setQueueCreateInfos(queue_create_infos); device_info.setPEnabledExtensionNames(required_extensions); device_info.setPEnabledFeatures(&required_features); @@ -441,7 +440,7 @@ ContextVK::ContextVK( } auto allocator = std::shared_ptr(new AllocatorVK( - *this, // + weak_from_this(), // application_info.apiVersion, // physical_device.value(), // device.value.get(), // @@ -455,6 +454,9 @@ ContextVK::ContextVK( return; } + //---------------------------------------------------------------------------- + /// Setup the pipeline library. + /// auto pipeline_library = std::shared_ptr( new PipelineLibraryVK(device.value.get(), // pipeline_cache_data, // @@ -484,6 +486,54 @@ ContextVK::ContextVK( return; } + //---------------------------------------------------------------------------- + /// Setup the command pool. + /// + vk::CommandPoolCreateInfo graphics_command_pool_info; + graphics_command_pool_info.queueFamilyIndex = graphics_queue->index; + graphics_command_pool_info.flags = vk::CommandPoolCreateFlagBits::eTransient; + auto graphics_command_pool = + device.value->createCommandPoolUnique(graphics_command_pool_info); + if (graphics_command_pool.result != vk::Result::eSuccess) { + VALIDATION_LOG << "Could not create graphics command pool."; + return; + } + + //---------------------------------------------------------------------------- + /// Setup the descriptor pool. This needs to be dynamic but we just allocate a + /// jumbo pool and hope for the best. + /// + constexpr size_t kPoolSize = 1024 * 3; + + std::vector pool_sizes = { + {vk::DescriptorType::eSampler, kPoolSize}, + {vk::DescriptorType::eCombinedImageSampler, kPoolSize}, + {vk::DescriptorType::eSampledImage, kPoolSize}, + {vk::DescriptorType::eStorageImage, kPoolSize}, + {vk::DescriptorType::eUniformTexelBuffer, kPoolSize}, + {vk::DescriptorType::eStorageTexelBuffer, kPoolSize}, + {vk::DescriptorType::eUniformBuffer, kPoolSize}, + {vk::DescriptorType::eStorageBuffer, kPoolSize}, + {vk::DescriptorType::eUniformBufferDynamic, kPoolSize}, + {vk::DescriptorType::eStorageBufferDynamic, kPoolSize}, + {vk::DescriptorType::eInputAttachment, kPoolSize}, + }; + vk::DescriptorPoolCreateInfo pool_info = { + vk::DescriptorPoolCreateFlagBits::eFreeDescriptorSet, // flags + static_cast(pool_sizes.size() * kPoolSize), // max sets + static_cast(pool_sizes.size()), // pool sizes count + pool_sizes.data() // pool sizes + }; + + auto descriptor_pool = device.value->createDescriptorPoolUnique(pool_info); + if (descriptor_pool.result != vk::Result::eSuccess) { + VALIDATION_LOG << "Unable to create a descriptor pool"; + return; + } + + //---------------------------------------------------------------------------- + /// All done! + /// instance_ = std::move(instance.value); debug_messenger_ = std::move(debug_messenger); device_ = std::move(device.value); @@ -498,7 +548,6 @@ ContextVK::ContextVK( device_->getQueue(compute_queue->family, compute_queue->index); transfer_queue_ = device_->getQueue(transfer_queue->family, transfer_queue->index); - device_capabilities_ = DeviceCapabilitiesBuilder() .SetHasThreadingRestrictions(false) @@ -508,11 +557,16 @@ ContextVK::ContextVK( .SetDefaultColorFormat(PixelFormat::kB8G8R8A8UNormInt) .SetDefaultStencilFormat(PixelFormat::kS8UInt) .Build(); - + graphics_command_pool_ = std::move(graphics_command_pool.value); + descriptor_pool_ = std::move(descriptor_pool.value); is_valid_ = true; } -ContextVK::~ContextVK() = default; +ContextVK::~ContextVK() { + if (device_) { + [[maybe_unused]] auto result = device_->waitIdle(); + } +} bool ContextVK::IsValid() const { return is_valid_; @@ -540,15 +594,22 @@ std::shared_ptr ContextVK::GetWorkQueue() const { } std::shared_ptr ContextVK::CreateCommandBuffer() const { - return CommandBufferVK::Create(weak_from_this(), *device_); + return std::shared_ptr( + new CommandBufferVK(shared_from_this(), // + CreateGraphicsCommandEncoder()) // + ); } vk::Instance ContextVK::GetInstance() const { return *instance_; } -std::unique_ptr ContextVK::AcquireSurface(size_t current_frame) { - return surface_producer_->AcquireSurface(current_frame); +vk::Device ContextVK::GetDevice() const { + return *device_; +} + +std::unique_ptr ContextVK::AcquireNextSurface() { + return swapchain_ ? swapchain_->AcquireNextDrawable() : nullptr; } #ifdef FML_OS_ANDROID @@ -573,38 +634,18 @@ vk::UniqueSurfaceKHR ContextVK::CreateAndroidSurface( #endif // FML_OS_ANDROID -void ContextVK::SetupSwapchain(vk::UniqueSurfaceKHR surface) { - surface_ = std::move(surface); - auto present_queue_out = PickPresentQueue(physical_device_, *surface_); - if (!present_queue_out.has_value()) { - return; +bool ContextVK::SetWindowSurface(vk::UniqueSurfaceKHR surface) { + auto swapchain = SwapchainVK::Create(shared_from_this(), std::move(surface)); + if (!swapchain) { + return false; } - present_queue_ = - device_->getQueue(present_queue_out->family, present_queue_out->index); - - auto swapchain_details = - SwapchainDetailsVK::Create(physical_device_, *surface_); - if (!swapchain_details) { - return; - } - surface_format_ = swapchain_details->PickSurfaceFormat().format; - swapchain_ = SwapchainVK::Create(*device_, *surface_, *swapchain_details); - auto weak_this = weak_from_this(); - surface_producer_ = SurfaceProducerVK::Create( - weak_this, { - .device = *device_, - .graphics_queue = graphics_queue_, - .present_queue = present_queue_, - .swapchain = swapchain_.get(), - }); -} - -std::unique_ptr ContextVK::CreateDescriptorPool() const { - return std::make_unique(*device_); + swapchain_ = std::move(swapchain); + return true; } PixelFormat ContextVK::GetColorAttachmentPixelFormat() const { - return ToPixelFormat(surface_format_); + return swapchain_ ? ToPixelFormat(swapchain_->GetSurfaceFormat()) + : PixelFormat::kB8G8R8A8UNormInt; } const IDeviceCapabilities& ContextVK::GetDeviceCapabilities() const { @@ -615,8 +656,29 @@ vk::Queue ContextVK::GetGraphicsQueue() const { return graphics_queue_; } -std::unique_ptr ContextVK::CreateGraphicsCommandPool() const { - return CommandPoolVK::Create(*device_, graphics_queue_idx_); +vk::CommandPool ContextVK::GetGraphicsCommandPool() const { + return *graphics_command_pool_; +} + +vk::DescriptorPool ContextVK::GetDescriptorPool() const { + return *descriptor_pool_; +} + +vk::PhysicalDevice ContextVK::GetPhysicalDevice() const { + return physical_device_; +} + +std::unique_ptr ContextVK::CreateGraphicsCommandEncoder() + const { + auto encoder = std::unique_ptr(new CommandEncoderVK( + *device_, // + graphics_queue_, // + *graphics_command_pool_ // + )); + if (!encoder->IsValid()) { + return nullptr; + } + return encoder; } } // namespace impeller diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/context_vk.h b/engine/src/flutter/impeller/renderer/backend/vulkan/context_vk.h index 7ef0603858..3cd22bb490 100644 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/context_vk.h +++ b/engine/src/flutter/impeller/renderer/backend/vulkan/context_vk.h @@ -10,23 +10,21 @@ #include "flutter/fml/macros.h" #include "flutter/fml/mapping.h" #include "impeller/base/backend_cast.h" -#include "impeller/renderer/backend/vulkan/command_pool_vk.h" -#include "impeller/renderer/backend/vulkan/deletion_queue_vk.h" -#include "impeller/renderer/backend/vulkan/descriptor_pool_vk.h" #include "impeller/renderer/backend/vulkan/pipeline_library_vk.h" #include "impeller/renderer/backend/vulkan/sampler_library_vk.h" #include "impeller/renderer/backend/vulkan/shader_library_vk.h" -#include "impeller/renderer/backend/vulkan/surface_producer_vk.h" #include "impeller/renderer/backend/vulkan/swapchain_vk.h" #include "impeller/renderer/backend/vulkan/vk.h" #include "impeller/renderer/context.h" #include "impeller/renderer/device_capabilities.h" #include "impeller/renderer/formats.h" +#include "impeller/renderer/surface.h" namespace impeller { namespace vk { +// TODO(csg): Move this to its own TU for validations. constexpr const char* kKhronosValidationLayerName = "VK_LAYER_KHRONOS_validation"; @@ -34,6 +32,8 @@ bool HasValidationLayers(); } // namespace vk +class CommandEncoderVK; + class ContextVK final : public Context, public BackendCast { public: static std::shared_ptr Create( @@ -49,6 +49,30 @@ class ContextVK final : public Context, public BackendCast { // |Context| bool IsValid() const override; + // |Context| + std::shared_ptr GetResourceAllocator() const override; + + // |Context| + std::shared_ptr GetShaderLibrary() const override; + + // |Context| + std::shared_ptr GetSamplerLibrary() const override; + + // |Context| + std::shared_ptr GetPipelineLibrary() const override; + + // |Context| + std::shared_ptr CreateCommandBuffer() const override; + + // |Context| + PixelFormat GetColorAttachmentPixelFormat() const override; + + // |Context| + std::shared_ptr GetWorkQueue() const override; + + // |Context| + const IDeviceCapabilities& GetDeviceCapabilities() const override; + template bool SetDebugName(T handle, std::string_view label) const { return SetDebugName(*device_, handle, label); @@ -74,7 +98,7 @@ class ContextVK final : public Context, public BackendCast { .setPObjectName(label_str.c_str())); if (ret != vk::Result::eSuccess) { - VALIDATION_LOG << "unable to set debug name"; + VALIDATION_LOG << "Unable to set debug name: " << label; return false; } @@ -83,11 +107,11 @@ class ContextVK final : public Context, public BackendCast { vk::Instance GetInstance() const; - void SetupSwapchain(vk::UniqueSurfaceKHR surface); + vk::Device GetDevice() const; - std::unique_ptr AcquireSurface(size_t current_frame); + [[nodiscard]] bool SetWindowSurface(vk::UniqueSurfaceKHR surface); - std::unique_ptr CreateDescriptorPool() const; + std::unique_ptr AcquireNextSurface(); #ifdef FML_OS_ANDROID vk::UniqueSurfaceKHR CreateAndroidSurface(ANativeWindow* window) const; @@ -95,7 +119,11 @@ class ContextVK final : public Context, public BackendCast { vk::Queue GetGraphicsQueue() const; - std::unique_ptr CreateGraphicsCommandPool() const; + vk::CommandPool GetGraphicsCommandPool() const; + + vk::DescriptorPool GetDescriptorPool() const; + + vk::PhysicalDevice GetPhysicalDevice() const; private: std::shared_ptr worker_task_runner_; @@ -107,17 +135,14 @@ class ContextVK final : public Context, public BackendCast { std::shared_ptr shader_library_; std::shared_ptr sampler_library_; std::shared_ptr pipeline_library_; - uint32_t graphics_queue_idx_; - vk::Queue graphics_queue_; - vk::Queue compute_queue_; - vk::Queue transfer_queue_; - vk::Queue present_queue_; - vk::UniqueSurfaceKHR surface_; - vk::Format surface_format_; - std::unique_ptr swapchain_; - std::unique_ptr surface_producer_; + vk::Queue graphics_queue_ = {}; + vk::Queue compute_queue_ = {}; + vk::Queue transfer_queue_ = {}; + std::shared_ptr swapchain_; std::shared_ptr work_queue_; std::unique_ptr device_capabilities_; + vk::UniqueCommandPool graphics_command_pool_; + vk::UniqueDescriptorPool descriptor_pool_; bool is_valid_ = false; ContextVK( @@ -127,29 +152,7 @@ class ContextVK final : public Context, public BackendCast { std::shared_ptr worker_task_runner, const std::string& label); - // |Context| - std::shared_ptr GetResourceAllocator() const override; - - // |Context| - std::shared_ptr GetShaderLibrary() const override; - - // |Context| - std::shared_ptr GetSamplerLibrary() const override; - - // |Context| - std::shared_ptr GetPipelineLibrary() const override; - - // |Context| - std::shared_ptr CreateCommandBuffer() const override; - - // |Context| - PixelFormat GetColorAttachmentPixelFormat() const override; - - // |Context| - std::shared_ptr GetWorkQueue() const override; - - // |Context| - const IDeviceCapabilities& GetDeviceCapabilities() const override; + std::unique_ptr CreateGraphicsCommandEncoder() const; FML_DISALLOW_COPY_AND_ASSIGN(ContextVK); }; diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/deletion_queue_vk.cc b/engine/src/flutter/impeller/renderer/backend/vulkan/deletion_queue_vk.cc deleted file mode 100644 index 2c202e7ed8..0000000000 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/deletion_queue_vk.cc +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "impeller/renderer/backend/vulkan/deletion_queue_vk.h" - -namespace impeller { - -DeletionQueueVK::DeletionQueueVK() = default; - -DeletionQueueVK::~DeletionQueueVK() { - Flush(); -} - -void DeletionQueueVK::Flush() { - for (auto it = deletors_.rbegin(); it != deletors_.rend(); ++it) { - (*it)(); - } - - deletors_.clear(); -} - -void DeletionQueueVK::Push(Deletor&& deletor) { - deletors_.push_back(std::move(deletor)); -} - -} // namespace impeller diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/deletion_queue_vk.h b/engine/src/flutter/impeller/renderer/backend/vulkan/deletion_queue_vk.h deleted file mode 100644 index 427844f752..0000000000 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/deletion_queue_vk.h +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#pragma once - -#include -#include - -#include "flutter/fml/macros.h" - -namespace impeller { - -class DeletionQueueVK { - public: - using Deletor = std::function; - - explicit DeletionQueueVK(); - - ~DeletionQueueVK(); - - void Flush(); - - void Push(Deletor&& deletor); - - private: - std::deque deletors_; - - FML_DISALLOW_COPY_AND_ASSIGN(DeletionQueueVK); -}; - -} // namespace impeller diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/descriptor_pool_vk.cc b/engine/src/flutter/impeller/renderer/backend/vulkan/descriptor_pool_vk.cc deleted file mode 100644 index 47e2cfe444..0000000000 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/descriptor_pool_vk.cc +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "impeller/renderer/backend/vulkan/descriptor_pool_vk.h" - -#include "fml/logging.h" -#include "impeller/base/validation.h" -#include "vulkan/vulkan_enums.hpp" - -namespace impeller { - -DescriptorPoolVK::DescriptorPoolVK(vk::Device device) { - constexpr size_t kPoolSize = 1024; - - std::vector pool_sizes = { - {vk::DescriptorType::eSampler, kPoolSize}, - {vk::DescriptorType::eCombinedImageSampler, kPoolSize}, - {vk::DescriptorType::eSampledImage, kPoolSize}, - {vk::DescriptorType::eStorageImage, kPoolSize}, - {vk::DescriptorType::eUniformTexelBuffer, kPoolSize}, - {vk::DescriptorType::eStorageTexelBuffer, kPoolSize}, - {vk::DescriptorType::eUniformBuffer, kPoolSize}, - {vk::DescriptorType::eStorageBuffer, kPoolSize}, - {vk::DescriptorType::eUniformBufferDynamic, kPoolSize}, - {vk::DescriptorType::eStorageBufferDynamic, kPoolSize}, - {vk::DescriptorType::eInputAttachment, kPoolSize}, - }; - - vk::DescriptorPoolCreateInfo pool_info = { - vk::DescriptorPoolCreateFlagBits::eFreeDescriptorSet, // flags - static_cast(pool_sizes.size() * kPoolSize), // max sets - static_cast(pool_sizes.size()), // pool sizes count - pool_sizes.data() // pool sizes - }; - - auto res = device.createDescriptorPool(pool_info); - if (res.result != vk::Result::eSuccess) { - VALIDATION_LOG << "Unable to create a descriptor pool"; - return; - } - - pool_ = res.value; - is_valid_ = true; -} - -vk::DescriptorPool DescriptorPoolVK::GetPool() { - return pool_; -} - -DescriptorPoolVK::~DescriptorPoolVK() = default; - -} // namespace impeller diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/descriptor_pool_vk.h b/engine/src/flutter/impeller/renderer/backend/vulkan/descriptor_pool_vk.h deleted file mode 100644 index e7ff29ee92..0000000000 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/descriptor_pool_vk.h +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#pragma once - -#include - -#include "flutter/fml/macros.h" -#include "impeller/renderer/backend/vulkan/vk.h" -#include "vulkan/vulkan_enums.hpp" -#include "vulkan/vulkan_handles.hpp" - -namespace impeller { - -class DescriptorPoolVK { - public: - explicit DescriptorPoolVK(vk::Device device); - - ~DescriptorPoolVK(); - - vk::DescriptorPool GetPool(); - - private: - vk::DescriptorPool pool_; - bool is_valid_ = false; - - FML_DISALLOW_COPY_AND_ASSIGN(DescriptorPoolVK); -}; - -} // namespace impeller diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/device_buffer_vk.cc b/engine/src/flutter/impeller/renderer/backend/vulkan/device_buffer_vk.cc index 92c670da72..e38c63fa68 100644 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/device_buffer_vk.cc +++ b/engine/src/flutter/impeller/renderer/backend/vulkan/device_buffer_vk.cc @@ -9,32 +9,35 @@ namespace impeller { -void* DeviceBufferAllocationVK::GetMapping() const { - return backing_allocation.allocation_info.pMappedData; -} - -vk::Buffer DeviceBufferAllocationVK::GetBufferHandle() const { - return buffer; -} - -DeviceBufferVK::DeviceBufferVK( - DeviceBufferDescriptor desc, - ContextVK& context, - std::unique_ptr device_allocation) +DeviceBufferVK::DeviceBufferVK(DeviceBufferDescriptor desc, + std::weak_ptr context, + VmaAllocator allocator, + VmaAllocation allocation, + VmaAllocationInfo info, + vk::Buffer buffer) : DeviceBuffer(desc), - context_(context), - device_allocation_(std::move(device_allocation)) {} + context_(std::move(context)), + allocator_(allocator), + allocation_(allocation), + info_(info), + buffer_(buffer) {} -DeviceBufferVK::~DeviceBufferVK() = default; +DeviceBufferVK::~DeviceBufferVK() { + if (buffer_) { + ::vmaDestroyBuffer(allocator_, + static_cast(buffer_), + allocation_); + } +} uint8_t* DeviceBufferVK::OnGetContents() const { - return reinterpret_cast(device_allocation_->GetMapping()); + return static_cast(info_.pMappedData); } bool DeviceBufferVK::OnCopyHostBuffer(const uint8_t* source, Range source_range, size_t offset) { - auto dest = static_cast(device_allocation_->GetMapping()); + uint8_t* dest = OnGetContents(); if (!dest) { return false; @@ -48,16 +51,24 @@ bool DeviceBufferVK::OnCopyHostBuffer(const uint8_t* source, } bool DeviceBufferVK::SetLabel(const std::string& label) { - context_.SetDebugName(device_allocation_->GetBufferHandle(), label); - return true; + auto context = context_.lock(); + if (!context || !buffer_) { + // The context could have died at this point. + return false; + } + + ::vmaSetAllocationName(allocator_, allocation_, label.c_str()); + + return ContextVK::Cast(*context).SetDebugName(buffer_, label); } bool DeviceBufferVK::SetLabel(const std::string& label, Range range) { + // We do not have the ability to name ranges. Just name the whole thing. return SetLabel(label); } vk::Buffer DeviceBufferVK::GetVKBufferHandle() const { - return device_allocation_->GetBufferHandle(); + return buffer_; } } // namespace impeller diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/device_buffer_vk.h b/engine/src/flutter/impeller/renderer/backend/vulkan/device_buffer_vk.h index da8fd8a729..132be608c3 100644 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/device_buffer_vk.h +++ b/engine/src/flutter/impeller/renderer/backend/vulkan/device_buffer_vk.h @@ -13,30 +13,15 @@ namespace impeller { -// https://github.com/flutter/flutter/issues/112387 -// This buffer can be freed once the command buffer is disposed. -// vmaDestroyBuffer(allocator_, buffer_, allocation_); -struct BackingAllocationVK { - VmaAllocator* allocator = nullptr; - VmaAllocation allocation = nullptr; - VmaAllocationInfo allocation_info = {}; -}; - -struct DeviceBufferAllocationVK { - vk::Buffer buffer = VK_NULL_HANDLE; - BackingAllocationVK backing_allocation = {}; - - void* GetMapping() const; - - vk::Buffer GetBufferHandle() const; -}; - class DeviceBufferVK final : public DeviceBuffer, public BackendCast { public: DeviceBufferVK(DeviceBufferDescriptor desc, - ContextVK& context, - std::unique_ptr device_allocation); + std::weak_ptr context, + VmaAllocator allocator, + VmaAllocation allocation, + VmaAllocationInfo info, + vk::Buffer buffer); // |DeviceBuffer| ~DeviceBufferVK() override; @@ -46,8 +31,11 @@ class DeviceBufferVK final : public DeviceBuffer, private: friend class AllocatorVK; - ContextVK& context_; - std::unique_ptr device_allocation_; + std::weak_ptr context_; + VmaAllocator allocator_ = {}; + VmaAllocation allocation_ = {}; + VmaAllocationInfo info_ = {}; + vk::Buffer buffer_ = {}; // |DeviceBuffer| uint8_t* OnGetContents() const override; diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/fenced_command_buffer_vk.cc b/engine/src/flutter/impeller/renderer/backend/vulkan/fenced_command_buffer_vk.cc deleted file mode 100644 index 4ebda5ed37..0000000000 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/fenced_command_buffer_vk.cc +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "impeller/renderer/backend/vulkan/fenced_command_buffer_vk.h" - -#include - -#include "impeller/base/validation.h" -#include "impeller/renderer/backend/vulkan/deletion_queue_vk.h" - -namespace impeller { - -static vk::CommandBuffer CreateCommandBuffer(vk::Device device, - vk::CommandPool pool) { - vk::CommandBufferAllocateInfo allocate_info; - allocate_info.setLevel(vk::CommandBufferLevel::ePrimary); - allocate_info.setCommandBufferCount(1); - allocate_info.setCommandPool(pool); - - auto res = device.allocateCommandBuffers(allocate_info); - if (res.result != vk::Result::eSuccess) { - VALIDATION_LOG << "Failed to allocate command buffer: " - << vk::to_string(res.result); - return nullptr; - } - - return res.value[0]; -} - -FencedCommandBufferVK::FencedCommandBufferVK(vk::Device device, - vk::Queue queue, - vk::CommandPool command_pool) - : device_(device), - queue_(queue), - command_pool_(command_pool), - deletion_queue_(std::make_unique()) { - command_buffer_ = CreateCommandBuffer(device_, command_pool_); -} - -vk::CommandBuffer FencedCommandBufferVK::Get() const { - return command_buffer_; -} - -vk::CommandBuffer FencedCommandBufferVK::GetSingleUseChild() { - auto child = CreateCommandBuffer(device_, command_pool_); - children_.push_back(child); - return child; -} - -FencedCommandBufferVK::~FencedCommandBufferVK() { - if (!submitted_) { - FML_LOG(WARNING) - << "FencedCommandBufferVK is being destroyed without being submitted."; - children_.push_back(command_buffer_); - } - device_.freeCommandBuffers(command_pool_, children_); -} - -bool FencedCommandBufferVK::Submit() { - if (submitted_) { - VALIDATION_LOG << "Command buffer already submitted."; - return false; - } - - children_.push_back(command_buffer_); - - auto fence_res = device_.createFenceUnique(vk::FenceCreateInfo()); - if (fence_res.result != vk::Result::eSuccess) { - VALIDATION_LOG << "Failed to create fence: " - << vk::to_string(fence_res.result); - return false; - } - vk::UniqueFence fence = std::move(fence_res.value); - - vk::SubmitInfo submit_info; - submit_info.setCommandBuffers(children_); - auto res = queue_.submit(submit_info, *fence); - if (res != vk::Result::eSuccess) { - VALIDATION_LOG << "Failed to submit command buffer: " << vk::to_string(res); - return false; - } - - auto wait = device_.waitForFences(fence.get(), true, UINT64_MAX); - if (wait != vk::Result::eSuccess) { - VALIDATION_LOG << "Failed to wait for fence: " << vk::to_string(wait); - return false; - } - - // cleanup all the resources held by the command buffer and its children. - deletion_queue_->Flush(); - - submitted_ = true; - return true; -} - -DeletionQueueVK* FencedCommandBufferVK::GetDeletionQueue() const { - return deletion_queue_.get(); -} - -} // namespace impeller diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/fenced_command_buffer_vk.h b/engine/src/flutter/impeller/renderer/backend/vulkan/fenced_command_buffer_vk.h deleted file mode 100644 index 760d6f44d7..0000000000 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/fenced_command_buffer_vk.h +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#pragma once - -#include - -#include "flutter/fml/macros.h" -#include "impeller/renderer/backend/vulkan/deletion_queue_vk.h" -#include "impeller/renderer/backend/vulkan/vk.h" - -namespace impeller { - -class FencedCommandBufferVK { - public: - FencedCommandBufferVK(vk::Device device, - vk::Queue queue, - vk::CommandPool command_pool); - - ~FencedCommandBufferVK(); - - vk::CommandBuffer Get() const; - - vk::CommandBuffer GetSingleUseChild(); - - // this is a blocking call that waits for the fence to be signaled. - bool Submit(); - - DeletionQueueVK* GetDeletionQueue() const; - - private: - vk::Device device_; - vk::Queue queue_; - vk::CommandPool command_pool_; - std::unique_ptr deletion_queue_; - vk::CommandBuffer command_buffer_; - std::vector children_; - bool submitted_ = false; - - FML_DISALLOW_COPY_AND_ASSIGN(FencedCommandBufferVK); -}; - -} // namespace impeller diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/formats_vk.cc b/engine/src/flutter/impeller/renderer/backend/vulkan/formats_vk.cc index 6df84d0ea4..f27452ccdb 100644 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/formats_vk.cc +++ b/engine/src/flutter/impeller/renderer/backend/vulkan/formats_vk.cc @@ -6,6 +6,31 @@ namespace impeller { -// +vk::PipelineDepthStencilStateCreateInfo ToVKPipelineDepthStencilStateCreateInfo( + std::optional depth, + std::optional front, + std::optional back) { + vk::PipelineDepthStencilStateCreateInfo info; + + if (depth.has_value()) { + info.depthTestEnable = true; + info.depthWriteEnable = depth->depth_write_enabled; + info.depthCompareOp = ToVKCompareOp(depth->depth_compare); + info.minDepthBounds = 0.0f; + info.maxDepthBounds = 1.0f; + } + + if (front.has_value()) { + info.stencilTestEnable = true; + info.front = ToVKStencilOpState(*front); + } + + if (back.has_value()) { + info.stencilTestEnable = true; + info.back = ToVKStencilOpState(*back); + } + + return info; +} } // namespace impeller diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/formats_vk.h b/engine/src/flutter/impeller/renderer/backend/vulkan/formats_vk.h index 72bb915eb6..83ea4acc46 100644 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/formats_vk.h +++ b/engine/src/flutter/impeller/renderer/backend/vulkan/formats_vk.h @@ -142,6 +142,7 @@ constexpr vk::Format ToVKImageFormat(PixelFormat format) { case PixelFormat::kB10G10R10XRSRGB: return vk::Format::eUndefined; case PixelFormat::kA8UNormInt: + // TODO(csg): This is incorrect. Don't depend on swizzle support for GLES. return vk::Format::eR8Unorm; case PixelFormat::kR8G8B8A8UNormInt: return vk::Format::eR8G8B8A8Unorm; @@ -172,37 +173,26 @@ constexpr PixelFormat ToPixelFormat(vk::Format format) { switch (format) { case vk::Format::eUndefined: return PixelFormat::kUnknown; - case vk::Format::eR8G8B8A8Unorm: return PixelFormat::kR8G8B8A8UNormInt; - case vk::Format::eR8G8B8A8Srgb: return PixelFormat::kR8G8B8A8UNormIntSRGB; - case vk::Format::eB8G8R8A8Unorm: return PixelFormat::kB8G8R8A8UNormInt; - case vk::Format::eB8G8R8A8Srgb: return PixelFormat::kB8G8R8A8UNormIntSRGB; - case vk::Format::eR32G32B32A32Sfloat: return PixelFormat::kR32G32B32A32Float; - case vk::Format::eR16G16B16A16Sfloat: return PixelFormat::kR16G16B16A16Float; - case vk::Format::eS8Uint: return PixelFormat::kS8UInt; - case vk::Format::eD32SfloatS8Uint: return PixelFormat::kD32FloatS8UInt; - case vk::Format::eR8Unorm: return PixelFormat::kR8UNormInt; - case vk::Format::eR8G8Unorm: return PixelFormat::kR8G8UNormInt; - default: return PixelFormat::kUnknown; } @@ -316,7 +306,6 @@ constexpr vk::AttachmentStoreOp ToVKAttachmentStoreOp( return vk::AttachmentStoreOp::eDontCare; case StoreAction::kMultisampleResolve: case StoreAction::kStoreAndMultisampleResolve: - // TODO (kaushikiska): vulkan doesn't support multisample resolve. return vk::AttachmentStoreOp::eDontCare; } @@ -363,4 +352,203 @@ constexpr vk::PrimitiveTopology ToVKPrimitiveTopology(PrimitiveType primitive) { FML_UNREACHABLE(); } +constexpr bool PixelFormatIsDepthStencil(PixelFormat format) { + switch (format) { + case PixelFormat::kUnknown: + case PixelFormat::kA8UNormInt: + case PixelFormat::kR8UNormInt: + case PixelFormat::kR8G8UNormInt: + case PixelFormat::kR8G8B8A8UNormInt: + case PixelFormat::kR8G8B8A8UNormIntSRGB: + case PixelFormat::kB8G8R8A8UNormInt: + case PixelFormat::kB8G8R8A8UNormIntSRGB: + case PixelFormat::kR32G32B32A32Float: + case PixelFormat::kR16G16B16A16Float: + case PixelFormat::kB10G10R10XR: + case PixelFormat::kB10G10R10XRSRGB: + case PixelFormat::kB10G10R10A10XR: + return false; + case PixelFormat::kS8UInt: + case PixelFormat::kD32FloatS8UInt: + return true; + } + return false; +} + +enum class AttachmentKind { + kColor, + kDepth, + kStencil, +}; + +constexpr vk::AttachmentDescription CreateAttachmentDescription( + PixelFormat format, + SampleCount sample_count, + AttachmentKind kind, + LoadAction load_action, + StoreAction store_action) { + vk::AttachmentDescription vk_attachment; + + vk_attachment.format = ToVKImageFormat(format); + vk_attachment.samples = ToVKSampleCount(sample_count); + + // The Vulkan spec has somewhat complicated rules for when these ops are used + // and ignored. Just set safe defaults. + vk_attachment.loadOp = vk::AttachmentLoadOp::eDontCare; + vk_attachment.storeOp = vk::AttachmentStoreOp::eDontCare; + vk_attachment.stencilLoadOp = vk::AttachmentLoadOp::eDontCare; + vk_attachment.stencilStoreOp = vk::AttachmentStoreOp::eDontCare; + + switch (kind) { + case AttachmentKind::kColor: + // If the attachment uses a color format, then loadOp and storeOp are + // used, and stencilLoadOp and stencilStoreOp are ignored. + vk_attachment.loadOp = ToVKAttachmentLoadOp(load_action); + vk_attachment.storeOp = ToVKAttachmentStoreOp(store_action); + break; + case AttachmentKind::kDepth: + // If the format has depth and/or stencil components, loadOp and storeOp + // apply only to the depth data, while stencilLoadOp and stencilStoreOp + // define how the stencil data is handled. + vk_attachment.loadOp = ToVKAttachmentLoadOp(load_action); + vk_attachment.storeOp = ToVKAttachmentStoreOp(store_action); + [[fallthrough]]; + case AttachmentKind::kStencil: + vk_attachment.stencilLoadOp = ToVKAttachmentLoadOp(load_action); + vk_attachment.stencilStoreOp = ToVKAttachmentStoreOp(store_action); + break; + } + + switch (kind) { + case AttachmentKind::kColor: + vk_attachment.initialLayout = vk_attachment.finalLayout = + vk::ImageLayout::eColorAttachmentOptimal; + break; + case AttachmentKind::kDepth: + case AttachmentKind::kStencil: + // Separate depth stencil layouts feature is only available in Vulkan 1.2. + vk_attachment.initialLayout = vk_attachment.finalLayout = + vk::ImageLayout::eDepthStencilAttachmentOptimal; + break; + } + + return vk_attachment; +} + +static constexpr vk::AttachmentReference kUnusedAttachmentReference = { + VK_ATTACHMENT_UNUSED, vk::ImageLayout::eUndefined}; + +constexpr vk::CullModeFlags ToVKCullModeFlags(CullMode mode) { + switch (mode) { + case CullMode::kNone: + return vk::CullModeFlagBits::eNone; + case CullMode::kFrontFace: + return vk::CullModeFlagBits::eFront; + case CullMode::kBackFace: + return vk::CullModeFlagBits::eBack; + } + FML_UNREACHABLE(); +} + +constexpr vk::CompareOp ToVKCompareOp(CompareFunction op) { + switch (op) { + case CompareFunction::kNever: + return vk::CompareOp::eNever; + case CompareFunction::kAlways: + return vk::CompareOp::eAlways; + case CompareFunction::kLess: + return vk::CompareOp::eLess; + case CompareFunction::kEqual: + return vk::CompareOp::eEqual; + case CompareFunction::kLessEqual: + return vk::CompareOp::eLessOrEqual; + case CompareFunction::kGreater: + return vk::CompareOp::eGreater; + case CompareFunction::kNotEqual: + return vk::CompareOp::eNotEqual; + case CompareFunction::kGreaterEqual: + return vk::CompareOp::eGreaterOrEqual; + } + FML_UNREACHABLE(); +} + +constexpr vk::StencilOp ToVKStencilOp(StencilOperation op) { + switch (op) { + case StencilOperation::kKeep: + return vk::StencilOp::eKeep; + case StencilOperation::kZero: + return vk::StencilOp::eZero; + case StencilOperation::kSetToReferenceValue: + return vk::StencilOp::eReplace; + case StencilOperation::kIncrementClamp: + return vk::StencilOp::eIncrementAndClamp; + case StencilOperation::kDecrementClamp: + return vk::StencilOp::eDecrementAndClamp; + case StencilOperation::kInvert: + return vk::StencilOp::eInvert; + case StencilOperation::kIncrementWrap: + return vk::StencilOp::eIncrementAndWrap; + case StencilOperation::kDecrementWrap: + return vk::StencilOp::eDecrementAndWrap; + break; + } + FML_UNREACHABLE(); +} + +constexpr vk::StencilOpState ToVKStencilOpState( + const StencilAttachmentDescriptor& desc) { + vk::StencilOpState state; + state.failOp = ToVKStencilOp(desc.stencil_failure); + state.passOp = ToVKStencilOp(desc.depth_stencil_pass); + state.depthFailOp = ToVKStencilOp(desc.depth_failure); + state.compareOp = ToVKCompareOp(desc.stencil_compare); + state.compareMask = desc.read_mask; + state.writeMask = desc.write_mask; + // This is irrelevant as the stencil references are always dynamic state and + // will be set in the render pass. + state.reference = 1988; + return state; +} + +constexpr vk::ImageAspectFlags ToVKImageAspectFlags(PixelFormat format) { + switch (format) { + case PixelFormat::kUnknown: + case PixelFormat::kA8UNormInt: + case PixelFormat::kR8UNormInt: + case PixelFormat::kR8G8UNormInt: + case PixelFormat::kR8G8B8A8UNormInt: + case PixelFormat::kR8G8B8A8UNormIntSRGB: + case PixelFormat::kB8G8R8A8UNormInt: + case PixelFormat::kB8G8R8A8UNormIntSRGB: + case PixelFormat::kR32G32B32A32Float: + case PixelFormat::kR16G16B16A16Float: + case PixelFormat::kB10G10R10XR: + case PixelFormat::kB10G10R10XRSRGB: + case PixelFormat::kB10G10R10A10XR: + return vk::ImageAspectFlagBits::eColor; + case PixelFormat::kS8UInt: + return vk::ImageAspectFlagBits::eStencil; + case PixelFormat::kD32FloatS8UInt: + return vk::ImageAspectFlagBits::eDepth | + vk::ImageAspectFlagBits::eStencil; + } + FML_UNREACHABLE(); +} + +constexpr uint32_t ToArrayLayerCount(TextureType type) { + switch (type) { + case TextureType::kTexture2D: + case TextureType::kTexture2DMultisample: + return 1u; + case TextureType::kTextureCube: + return 6u; + } + FML_UNREACHABLE(); +} + +vk::PipelineDepthStencilStateCreateInfo ToVKPipelineDepthStencilStateCreateInfo( + std::optional depth, + std::optional front, + std::optional back); + } // namespace impeller diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/pipeline_library_vk.cc b/engine/src/flutter/impeller/renderer/backend/vulkan/pipeline_library_vk.cc index a7af767471..1cc9e23036 100644 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/pipeline_library_vk.cc +++ b/engine/src/flutter/impeller/renderer/backend/vulkan/pipeline_library_vk.cc @@ -97,40 +97,30 @@ PipelineFuture PipelineLibraryVK::GetPipeline( ComputePipelineDescriptor descriptor) { auto promise = std::make_shared< std::promise>>>(); - // TODO(dnfield): implement compute for GLES. promise->set_value(nullptr); return {descriptor, promise->get_future()}; } +//------------------------------------------------------------------------------ +/// @brief Creates an attachment description that does just enough to +/// ensure render pass compatibility with the pass associated later +/// with the framebuffer. +/// +/// See +/// https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/chap8.html#renderpass-compatibility +/// static vk::AttachmentDescription CreatePlaceholderAttachmentDescription( - vk::Format format, + PixelFormat format, SampleCount sample_count, - bool is_color) { - vk::AttachmentDescription desc; - - // See - // https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/chap8.html#renderpass-compatibility - - // Format and samples must match for sub-pass compatibility - desc.setFormat(format); - desc.setSamples(ToVKSampleCountFlagBits(sample_count)); - - // The rest of these are placeholders and the right values will be set when - // the render-pass to be used with the framebuffer is created. - desc.setLoadOp(vk::AttachmentLoadOp::eDontCare); - desc.setStoreOp(vk::AttachmentStoreOp::eDontCare); - desc.setStencilLoadOp(vk::AttachmentLoadOp::eDontCare); - desc.setStencilStoreOp(vk::AttachmentStoreOp::eDontCare); - - if (!is_color) { - desc.setInitialLayout(vk::ImageLayout::eGeneral); - desc.setFinalLayout(vk::ImageLayout::eGeneral); - } else { - desc.setInitialLayout(vk::ImageLayout::eColorAttachmentOptimal); - desc.setFinalLayout(vk::ImageLayout::ePresentSrcKHR); - } - - return desc; + AttachmentKind kind) { + // Load store ops are immaterial for pass compatibility. The right ops will be + // picked up when the pass associated with framebuffer. + return CreateAttachmentDescription(format, // + sample_count, // + kind, // + LoadAction::kDontCare, // + StoreAction::kDontCare // + ); } // |PipelineLibrary| @@ -155,69 +145,69 @@ void PipelineLibraryVK::RemovePipelinesWithEntryPoint( /// StencilAttachmentDescriptor, and, DepthAttachmentDescriptor. /// Right now, these are placeholders. /// -std::optional PipelineLibraryVK::CreateRenderPass( +vk::UniqueRenderPass PipelineLibraryVK::CreateRenderPass( const PipelineDescriptor& desc) { - std::vector render_pass_attachments; + std::vector attachments; + + std::vector color_refs; + vk::AttachmentReference depth_stencil_ref = kUnusedAttachmentReference; + + color_refs.resize(desc.GetMaxColorAttacmentBindIndex() + 1, + kUnusedAttachmentReference); + const auto sample_count = desc.GetSampleCount(); - // Set the color attachment. - const auto& format = desc.GetColorAttachmentDescriptor(0)->format; - render_pass_attachments.push_back(CreatePlaceholderAttachmentDescription( - ToVKImageFormat(format), sample_count, true)); - std::vector color_attachment_references; - std::vector resolve_attachment_references; - std::optional depth_stencil_attachment_reference; - - // TODO (kaushikiska): consider changing the image layout to - // eColorAttachmentOptimal. - color_attachment_references.push_back(vk::AttachmentReference( - render_pass_attachments.size() - 1u, vk::ImageLayout::eGeneral)); - -#if false - // see: https://github.com/flutter/flutter/issues/112388 - // Set the resolve attachment if MSAA is enabled. - if (sample_count != SampleCount::kCount1) { - render_pass_attachments.push_back(CreatePlaceholderAttachmentDescription( - vk::Format::eR8G8B8A8Unorm, SampleCount::kCount1, false)); - resolve_attachment_references.push_back(vk::AttachmentReference( - render_pass_attachments.size() - 1u, vk::ImageLayout::eGeneral)); + for (const auto& [bind_point, color] : desc.GetColorAttachmentDescriptors()) { + color_refs[bind_point] = + vk::AttachmentReference{static_cast(attachments.size()), + vk::ImageLayout::eColorAttachmentOptimal}; + attachments.emplace_back(CreatePlaceholderAttachmentDescription( + color.format, sample_count, AttachmentKind::kColor)); } - if (desc.HasStencilAttachmentDescriptors()) { - render_pass_attachments.push_back(CreatePlaceholderAttachmentDescription( - vk::Format::eS8Uint, sample_count, false)); - depth_stencil_attachment_reference = vk::AttachmentReference( - render_pass_attachments.size() - 1u, vk::ImageLayout::eGeneral); - } -#endif - - vk::SubpassDescription subpass_info; - subpass_info.setPipelineBindPoint(vk::PipelineBindPoint::eGraphics); - subpass_info.setColorAttachments(color_attachment_references); - -#if false - // see: https://github.com/flutter/flutter/issues/112388 - if (sample_count != SampleCount::kCount1) { - subpass_info.setResolveAttachments(resolve_attachment_references); - } - if (depth_stencil_attachment_reference.has_value()) { - subpass_info.setPDepthStencilAttachment( - &depth_stencil_attachment_reference.value()); - } -#endif - - vk::RenderPassCreateInfo render_pass_info; - render_pass_info.setSubpasses(subpass_info); - render_pass_info.setAttachments(render_pass_attachments); - auto render_pass = device_.createRenderPassUnique(render_pass_info); - if (render_pass.result != vk::Result::eSuccess) { - VALIDATION_LOG << "Could not create render pass for pipeline " - << desc.GetLabel() << ": " - << vk::to_string(render_pass.result); - return std::nullopt; + if (auto depth = desc.GetDepthStencilAttachmentDescriptor(); + depth.has_value()) { + depth_stencil_ref = vk::AttachmentReference{ + static_cast(attachments.size()), + vk::ImageLayout::eDepthStencilAttachmentOptimal}; + attachments.emplace_back(CreatePlaceholderAttachmentDescription( + desc.GetDepthPixelFormat(), sample_count, AttachmentKind::kDepth)); + } else if (desc.HasStencilAttachmentDescriptors()) { + depth_stencil_ref = vk::AttachmentReference{ + static_cast(attachments.size()), + vk::ImageLayout::eDepthStencilAttachmentOptimal}; + attachments.emplace_back(CreatePlaceholderAttachmentDescription( + desc.GetStencilPixelFormat(), sample_count, AttachmentKind::kStencil)); } - return std::move(render_pass.value); + vk::SubpassDescription subpass_desc; + subpass_desc.pipelineBindPoint = vk::PipelineBindPoint::eGraphics; + subpass_desc.setColorAttachments(color_refs); + subpass_desc.setPDepthStencilAttachment(&depth_stencil_ref); + + vk::RenderPassCreateInfo render_pass_desc; + render_pass_desc.setAttachments(attachments); + render_pass_desc.setPSubpasses(&subpass_desc); + render_pass_desc.setSubpassCount(1u); + + auto [result, pass] = device_.createRenderPassUnique(render_pass_desc); + if (result != vk::Result::eSuccess) { + VALIDATION_LOG << "Failed to create render pass for pipeline '" + << desc.GetLabel() << "'. Error: " << vk::to_string(result); + return {}; + } + + return std::move(pass); +} + +constexpr vk::FrontFace ToVKFrontFace(WindingOrder order) { + switch (order) { + case WindingOrder::kClockwise: + return vk::FrontFace::eClockwise; + case WindingOrder::kCounterClockwise: + return vk::FrontFace::eCounterClockwise; + } + FML_UNREACHABLE(); } std::unique_ptr PipelineLibraryVK::CreatePipeline( @@ -269,18 +259,13 @@ std::unique_ptr PipelineLibraryVK::CreatePipeline( //---------------------------------------------------------------------------- /// Rasterization State - /// TODO(106380): Move front face and cull mode to pipeline state instead of - /// draw command. These are hard-coded here for now. /// vk::PipelineRasterizationStateCreateInfo rasterization_state; - rasterization_state.setFrontFace(vk::FrontFace::eClockwise); - rasterization_state.setCullMode(vk::CullModeFlagBits::eNone); + rasterization_state.setFrontFace(ToVKFrontFace(desc.GetWindingOrder())); + rasterization_state.setCullMode(ToVKCullModeFlags(desc.GetCullMode())); rasterization_state.setPolygonMode(ToVKPolygonMode(desc.GetPolygonMode())); - // requires GPU extensions to change. - { - rasterization_state.setLineWidth(1.0f); - rasterization_state.setDepthClampEnable(false); - } + rasterization_state.setLineWidth(1.0f); + rasterization_state.setDepthClampEnable(false); rasterization_state.setRasterizerDiscardEnable(false); pipeline_info.setPRasterizationState(&rasterization_state); @@ -301,7 +286,6 @@ std::unique_ptr PipelineLibraryVK::CreatePipeline( //---------------------------------------------------------------------------- /// Color Blend State - /// std::vector attachment_blend_state; for (const auto& color_desc : desc.GetColorAttachmentDescriptors()) { // TODO(csg): The blend states are per color attachment. But it isn't clear @@ -315,16 +299,19 @@ std::unique_ptr PipelineLibraryVK::CreatePipeline( pipeline_info.setPColorBlendState(&blend_state); auto render_pass = CreateRenderPass(desc); - if (render_pass.has_value()) { + if (render_pass) { pipeline_info.setBasePipelineHandle(VK_NULL_HANDLE); pipeline_info.setSubpass(0); - pipeline_info.setRenderPass((*render_pass).get()); + pipeline_info.setRenderPass(render_pass.get()); } else { return nullptr; } - // only 1 stream of data is supported for now. - vk::VertexInputBindingDescription binding_description = {}; + //---------------------------------------------------------------------------- + /// Vertex Input Setup + /// + vk::VertexInputBindingDescription binding_description; + // Only 1 stream of data is supported for now. binding_description.setBinding(0); binding_description.setInputRate(vk::VertexInputRate::eVertex); @@ -374,8 +361,11 @@ std::unique_ptr PipelineLibraryVK::CreatePipeline( vk::UniqueDescriptorSetLayout descriptor_set_layout = std::move(descriptor_set_create_res.value); ContextVK::SetDebugName(device_, descriptor_set_layout.get(), - "descriptor_set_layout_" + desc.GetLabel()); + "Descriptor Set Layout" + desc.GetLabel()); + //---------------------------------------------------------------------------- + /// Create the pipeline layout. + /// vk::PipelineLayoutCreateInfo pipeline_layout_info; pipeline_layout_info.setSetLayouts(descriptor_set_layout.get()); auto pipeline_layout = @@ -388,14 +378,19 @@ std::unique_ptr PipelineLibraryVK::CreatePipeline( } pipeline_info.setLayout(pipeline_layout.value.get()); - vk::PipelineDepthStencilStateCreateInfo depth_stencil_state; - depth_stencil_state.setDepthTestEnable(true); - depth_stencil_state.setDepthWriteEnable(true); - depth_stencil_state.setDepthCompareOp(vk::CompareOp::eLess); - depth_stencil_state.setDepthBoundsTestEnable(false); - depth_stencil_state.setStencilTestEnable(false); + //---------------------------------------------------------------------------- + /// Create the depth stencil state. + /// + auto depth_stencil_state = ToVKPipelineDepthStencilStateCreateInfo( + desc.GetDepthStencilAttachmentDescriptor(), + desc.GetFrontStencilAttachmentDescriptor(), + desc.GetBackStencilAttachmentDescriptor()); pipeline_info.setPDepthStencilState(&depth_stencil_state); + //---------------------------------------------------------------------------- + /// Finally, all done with the setup info. Create the pipeline itself. + /// + // See the note in the header about why this is a reader lock. ReaderLock lock(cache_mutex_); auto pipeline = @@ -407,12 +402,12 @@ std::unique_ptr PipelineLibraryVK::CreatePipeline( } ContextVK::SetDebugName(device_, *pipeline_layout.value, - "pipeline_layout_" + desc.GetLabel()); + "Pipeline Layout" + desc.GetLabel()); ContextVK::SetDebugName(device_, *pipeline.value, - "pipeline_" + desc.GetLabel()); + "Pipeline" + desc.GetLabel()); return std::make_unique( - std::move(pipeline.value), std::move(render_pass.value()), + std::move(pipeline.value), std::move(render_pass), std::move(pipeline_layout.value), std::move(descriptor_set_layout)); } diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/pipeline_library_vk.h b/engine/src/flutter/impeller/renderer/backend/vulkan/pipeline_library_vk.h index ec03d99438..f4cd10b76f 100644 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/pipeline_library_vk.h +++ b/engine/src/flutter/impeller/renderer/backend/vulkan/pipeline_library_vk.h @@ -65,8 +65,7 @@ class PipelineLibraryVK final std::unique_ptr CreatePipeline( const PipelineDescriptor& desc); - std::optional CreateRenderPass( - const PipelineDescriptor& desc); + vk::UniqueRenderPass CreateRenderPass(const PipelineDescriptor& desc); FML_DISALLOW_COPY_AND_ASSIGN(PipelineLibraryVK); }; diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/pipeline_vk.cc b/engine/src/flutter/impeller/renderer/backend/vulkan/pipeline_vk.cc index b24a7acf67..87f65c9c99 100644 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/pipeline_vk.cc +++ b/engine/src/flutter/impeller/renderer/backend/vulkan/pipeline_vk.cc @@ -23,7 +23,7 @@ bool PipelineCreateInfoVK::IsValid() const { return is_valid_; } -vk::Pipeline PipelineCreateInfoVK::GetVKPipeline() const { +const vk::Pipeline& PipelineCreateInfoVK::GetVKPipeline() const { return *pipeline_; } diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/pipeline_vk.h b/engine/src/flutter/impeller/renderer/backend/vulkan/pipeline_vk.h index ce7b988d44..a10e31e12f 100644 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/pipeline_vk.h +++ b/engine/src/flutter/impeller/renderer/backend/vulkan/pipeline_vk.h @@ -22,7 +22,7 @@ class PipelineCreateInfoVK { bool IsValid() const; - vk::Pipeline GetVKPipeline() const; + const vk::Pipeline& GetVKPipeline() const; vk::RenderPass GetRenderPass() const; diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/render_pass_vk.cc b/engine/src/flutter/impeller/renderer/backend/vulkan/render_pass_vk.cc index 2bd665cfc7..b929e647e2 100644 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/render_pass_vk.cc +++ b/engine/src/flutter/impeller/renderer/backend/vulkan/render_pass_vk.cc @@ -10,13 +10,13 @@ #include "fml/logging.h" #include "impeller/base/validation.h" -#include "impeller/renderer/backend/vulkan/commands_vk.h" +#include "impeller/renderer/backend/vulkan/command_encoder_vk.h" #include "impeller/renderer/backend/vulkan/context_vk.h" #include "impeller/renderer/backend/vulkan/device_buffer_vk.h" #include "impeller/renderer/backend/vulkan/formats_vk.h" #include "impeller/renderer/backend/vulkan/pipeline_vk.h" #include "impeller/renderer/backend/vulkan/sampler_vk.h" -#include "impeller/renderer/backend/vulkan/surface_producer_vk.h" +#include "impeller/renderer/backend/vulkan/shared_object_vk.h" #include "impeller/renderer/backend/vulkan/texture_vk.h" #include "impeller/renderer/sampler.h" #include "impeller/renderer/shader_types.h" @@ -25,18 +25,102 @@ namespace impeller { -static uint32_t color_flash = 0; +static vk::AttachmentDescription CreateAttachmentDescription( + const Attachment& attachment, + AttachmentKind kind, + bool resolve_texture = false) { + const auto& texture = resolve_texture + ? attachment.resolve_texture->GetTextureDescriptor() + : attachment.texture->GetTextureDescriptor(); + return CreateAttachmentDescription(texture.format, // + texture.sample_count, // + kind, // + attachment.load_action, // + attachment.store_action // + ); +} -RenderPassVK::RenderPassVK( - std::weak_ptr context, - vk::Device device, - const RenderTarget& target, - std::shared_ptr command_buffer, - vk::RenderPass render_pass) - : RenderPass(std::move(context), target), - device_(device), - command_buffer_(std::move(command_buffer)), - render_pass_(render_pass) { +static vk::UniqueRenderPass CreateVKRenderPass(const vk::Device& device, + const RenderTarget& target) { + std::vector attachments; + + std::vector color_refs; + std::vector resolve_refs; + vk::AttachmentReference depth_stencil_ref = kUnusedAttachmentReference; + + // Spec says: "Each element of the pColorAttachments array corresponds to an + // output location in the shader, i.e. if the shader declares an output + // variable decorated with a Location value of X, then it uses the attachment + // provided in pColorAttachments[X]. If the attachment member of any element + // of pColorAttachments is VK_ATTACHMENT_UNUSED." + // + // Just initialize all the elements as unused and fill in the valid bind + // points in the loop below. + color_refs.resize(target.GetMaxColorAttacmentBindIndex() + 1u, + kUnusedAttachmentReference); + resolve_refs.resize(target.GetMaxColorAttacmentBindIndex() + 1u, + kUnusedAttachmentReference); + + for (const auto& [bind_point, color] : target.GetColorAttachments()) { + color_refs[bind_point] = + vk::AttachmentReference{static_cast(attachments.size()), + vk::ImageLayout::eColorAttachmentOptimal}; + attachments.emplace_back( + CreateAttachmentDescription(color, AttachmentKind::kColor)); + if (color.resolve_texture) { + resolve_refs[bind_point] = + vk::AttachmentReference{static_cast(attachments.size()), + vk::ImageLayout::eColorAttachmentOptimal}; + attachments.emplace_back( + CreateAttachmentDescription(color, AttachmentKind::kColor, true)); + } + } + + if (auto depth = target.GetDepthAttachment(); depth.has_value()) { + depth_stencil_ref = vk::AttachmentReference{ + static_cast(attachments.size()), + vk::ImageLayout::eDepthStencilAttachmentOptimal}; + attachments.emplace_back( + CreateAttachmentDescription(depth.value(), AttachmentKind::kDepth)); + } else if (auto stencil = target.GetStencilAttachment(); + stencil.has_value()) { + depth_stencil_ref = vk::AttachmentReference{ + static_cast(attachments.size()), + vk::ImageLayout::eDepthStencilAttachmentOptimal}; + attachments.emplace_back( + CreateAttachmentDescription(stencil.value(), AttachmentKind::kStencil)); + } + + vk::SubpassDescription subpass_desc; + subpass_desc.pipelineBindPoint = vk::PipelineBindPoint::eGraphics; + subpass_desc.setColorAttachments(color_refs); + subpass_desc.setResolveAttachments(resolve_refs); + subpass_desc.setPDepthStencilAttachment(&depth_stencil_ref); + + vk::RenderPassCreateInfo render_pass_desc; + render_pass_desc.setAttachments(attachments); + render_pass_desc.setPSubpasses(&subpass_desc); + render_pass_desc.setSubpassCount(1u); + + auto [result, pass] = device.createRenderPassUnique(render_pass_desc); + if (result != vk::Result::eSuccess) { + VALIDATION_LOG << "Failed to create render pass: " << vk::to_string(result); + return {}; + } + + return std::move(pass); +} + +RenderPassVK::RenderPassVK(const std::shared_ptr& context, + const RenderTarget& target, + std::weak_ptr encoder) + : RenderPass(context, target), + render_pass_( + CreateVKRenderPass(ContextVK::Cast(*context).GetDevice(), target)), + encoder_(std::move(encoder)) { + if (!render_pass_) { + return; + } is_valid_ = true; } @@ -47,226 +131,172 @@ bool RenderPassVK::IsValid() const { } void RenderPassVK::OnSetLabel(std::string label) { - label_ = std::move(label); + auto context = GetContext().lock(); + if (!context) { + return; + } + ContextVK::Cast(*context).SetDebugName(*render_pass_, label.c_str()); + debug_label_ = std::move(label); } -bool RenderPassVK::OnEncodeCommands(const Context& context) const { - if (!IsValid()) { - return false; - } +static vk::ClearColorValue VKClearValueFromColor(Color color) { + vk::ClearColorValue value; + value.setFloat32( + std::array{color.red, color.green, color.blue, color.alpha}); + return value; +} - const auto& render_target = GetRenderTarget(); - if (!render_target.HasColorAttachment(0u)) { - return false; - } +static vk::ClearDepthStencilValue VKClearValueFromDepth(Scalar depth) { + vk::ClearDepthStencilValue value; + value.depth = depth; + return value; +} - vk::CommandBufferBeginInfo begin_info; - auto res = command_buffer_->Get().begin(begin_info); - if (res != vk::Result::eSuccess) { - VALIDATION_LOG << "Failed to begin command buffer: " << vk::to_string(res); - return false; - } +static vk::ClearDepthStencilValue VKClearValueFromStencil(uint32_t stencil) { + vk::ClearDepthStencilValue value; + value.stencil = stencil; + return value; +} - const auto& color0 = render_target.GetColorAttachments().at(0u); - const auto& depth0 = render_target.GetDepthAttachment(); - const auto& stencil0 = render_target.GetStencilAttachment(); +static std::vector GetVKClearValues( + const RenderTarget& target) { + std::vector clears; - auto& texture = TextureVK::Cast(*color0.texture); - const auto& size = texture.GetTextureDescriptor().size; - vk::Framebuffer framebuffer = CreateFrameBuffer(texture); - uint32_t mip_count = texture.GetTextureDescriptor().mip_count; - - command_buffer_->GetDeletionQueue()->Push( - [device = device_, fbo = framebuffer]() { - device.destroyFramebuffer(fbo); - }); - - // layout transition. - if (!TransitionImageLayout(texture.GetImage(), vk::ImageLayout::eUndefined, - vk::ImageLayout::eColorAttachmentOptimal, - mip_count)) { - return false; - } - - vk::ClearValue clear_value; - clear_value.color = - vk::ClearColorValue(std::array{0.0f, 0.0f, 0.0, 0.0f}); - - vk::Rect2D render_area = - vk::Rect2D() - .setOffset(vk::Offset2D(0, 0)) - .setExtent(vk::Extent2D(size.width, size.height)); - auto rp_begin_info = vk::RenderPassBeginInfo() - .setRenderPass(render_pass_) - .setFramebuffer(framebuffer) - .setRenderArea(render_area) - .setClearValues(clear_value); - - command_buffer_->Get().beginRenderPass(rp_begin_info, - vk::SubpassContents::eInline); - - const auto& transients_allocator = context.GetResourceAllocator(); - - // encode the commands. - for (const auto& command : commands_) { - if (command.index_count == 0u) { - continue; + for (const auto& [_, color] : target.GetColorAttachments()) { + clears.emplace_back(VKClearValueFromColor(color.clear_color)); + if (color.resolve_texture) { + clears.emplace_back(VKClearValueFromColor(color.clear_color)); } + } - if (command.instance_count == 0u) { - continue; + if (auto depth = target.GetDepthAttachment(); depth.has_value()) { + clears.emplace_back(VKClearValueFromDepth(depth->clear_depth)); + } + + if (auto stencil = target.GetStencilAttachment(); stencil.has_value()) { + clears.emplace_back(VKClearValueFromStencil(stencil->clear_stencil)); + } + + return clears; +} + +static vk::UniqueFramebuffer CreateFramebuffer(const vk::Device& device, + const RenderTarget& target, + const vk::RenderPass& pass) { + vk::FramebufferCreateInfo fb_info; + + fb_info.renderPass = pass; + + const auto target_size = target.GetRenderTargetSize(); + fb_info.width = target_size.width; + fb_info.height = target_size.height; + + fb_info.layers = 1u; + + std::vector attachments; + + // This bit must be consistent to ensure compatibility with the pass created + // earlier. Follow this order: Color attachments, then depth, then stencil. + for (const auto& [_, color] : target.GetColorAttachments()) { + // The bind point doesn't matter here since that information is present in + // the render pass. + attachments.emplace_back(TextureVK::Cast(*color.texture).GetImageView()); + if (color.resolve_texture) { + attachments.emplace_back( + TextureVK::Cast(*color.resolve_texture).GetImageView()); } + } + if (auto depth = target.GetDepthAttachment(); depth.has_value()) { + attachments.emplace_back(TextureVK::Cast(*depth->texture).GetImageView()); + } + if (auto stencil = target.GetStencilAttachment(); stencil.has_value()) { + attachments.emplace_back(TextureVK::Cast(*stencil->texture).GetImageView()); + } - if (!command.pipeline) { - continue; + fb_info.setAttachments(attachments); + + auto [result, framebuffer] = device.createFramebufferUnique(fb_info); + + if (result != vk::Result::eSuccess) { + VALIDATION_LOG << "Could not create framebuffer: " << vk::to_string(result); + return {}; + } + + return std::move(framebuffer); +} + +static bool ConfigureRenderTargetAttachmentLayouts( + const RenderTarget& target, + const vk::CommandBuffer& command_buffer) { + for (const auto& [_, color] : target.GetColorAttachments()) { + if (!TextureVK::Cast(*color.texture) + .SetLayout(vk::ImageLayout::eColorAttachmentOptimal, + command_buffer)) { + return false; } - - if (!EncodeCommand(context, command)) { + if (color.resolve_texture) { + if (!TextureVK::Cast(*color.resolve_texture) + .SetLayout(vk::ImageLayout::eColorAttachmentOptimal, + command_buffer)) { + return false; + } + } + } + if (auto depth = target.GetDepthAttachment(); depth.has_value()) { + if (!TextureVK::Cast(*depth->texture) + .SetLayout(vk::ImageLayout::eDepthAttachmentOptimal, + command_buffer)) { return false; } } - - if (!TransitionImageLayout(texture.GetImage(), vk::ImageLayout::eUndefined, - vk::ImageLayout::eColorAttachmentOptimal, - mip_count)) { - return false; - } - - command_buffer_->Get().endRenderPass(); - - return const_cast(this)->EndCommandBuffer(); -} - -bool RenderPassVK::EndCommandBuffer() { - if (command_buffer_) { - auto res = command_buffer_->Get().end(); - if (res != vk::Result::eSuccess) { - VALIDATION_LOG << "Failed to end command buffer: " << vk::to_string(res); + if (auto stencil = target.GetStencilAttachment(); stencil.has_value()) { + if (!TextureVK::Cast(*stencil->texture) + .SetLayout(vk::ImageLayout::eStencilAttachmentOptimal, + command_buffer)) { return false; } - - const auto& context_vk = GetContextVK(); - command_buffer_->GetDeletionQueue()->Push( - [device = device_, render_pass = render_pass_]() { - device.destroyRenderPass(render_pass); - }); - - return true; } - return false; -} - -bool RenderPassVK::EncodeCommand(const Context& context, - const Command& command) const { - SetViewportAndScissor(command); - - auto& pipeline_vk = PipelineVK::Cast(*command.pipeline); - PipelineCreateInfoVK* pipeline_create_info = pipeline_vk.GetCreateInfo(); - - if (!AllocateAndBindDescriptorSets(context, command, pipeline_create_info)) { - return false; - } - - command_buffer_->Get().bindPipeline(vk::PipelineBindPoint::eGraphics, - pipeline_create_info->GetVKPipeline()); - - auto vertex_buffer_view = command.GetVertexBuffer(); - auto index_buffer_view = command.index_buffer; - - if (!vertex_buffer_view || !index_buffer_view) { - return false; - } - - auto& allocator = *context.GetResourceAllocator(); - const auto& pipeline_desc = command.pipeline->GetDescriptor(); - - auto vertex_buffer = vertex_buffer_view.buffer->GetDeviceBuffer(allocator); - auto index_buffer = index_buffer_view.buffer->GetDeviceBuffer(allocator); - - if (!vertex_buffer || !index_buffer) { - VALIDATION_LOG << "Failed to acquire device buffers" - << " for vertex and index buffer views"; - return false; - } - - // bind vertex buffer - auto vertex_buffer_handle = - DeviceBufferVK::Cast(*vertex_buffer).GetVKBufferHandle(); - vk::Buffer vertex_buffers[] = {vertex_buffer_handle}; - vk::DeviceSize vertex_buffer_offsets[] = {vertex_buffer_view.range.offset}; - command_buffer_->Get().bindVertexBuffers(0, 1, vertex_buffers, - vertex_buffer_offsets); - - // index buffer - auto index_buffer_handle = - DeviceBufferVK::Cast(*index_buffer).GetVKBufferHandle(); - command_buffer_->Get().bindIndexBuffer(index_buffer_handle, - index_buffer_view.range.offset, - ToVKIndexType(command.index_type)); - - // execute draw - command_buffer_->Get().drawIndexed(command.index_count, - command.instance_count, 0, 0, 0); return true; } -bool RenderPassVK::AllocateAndBindDescriptorSets( - - const Context& context, - const Command& command, - PipelineCreateInfoVK* pipeline_create_info) const { - auto& allocator = *context.GetResourceAllocator(); - vk::PipelineLayout pipeline_layout = - pipeline_create_info->GetPipelineLayout(); - - const auto& context_vk = GetContextVK(); - const auto& pool = context_vk.CreateDescriptorPool(); - - command_buffer_->GetDeletionQueue()->Push( - [pool = pool->GetPool(), device = device_]() { - device.destroyDescriptorPool(pool); - }); - - vk::DescriptorSetAllocateInfo alloc_info; - std::array dsls = { - pipeline_create_info->GetDescriptorSetLayout(), - }; - - alloc_info.setDescriptorPool(pool->GetPool()); - alloc_info.setSetLayouts(dsls); - - auto desc_sets_res = device_.allocateDescriptorSets(alloc_info); - if (desc_sets_res.result != vk::Result::eSuccess) { - VALIDATION_LOG << "Failed to allocate descriptor sets: " - << vk::to_string(desc_sets_res.result); - return false; +static bool UpdateBindingLayouts(const Bindings& bindings, + const vk::CommandBuffer& buffer) { + for (const auto& [_, texture] : bindings.textures) { + if (!TextureVK::Cast(*texture.resource) + .SetLayout(vk::ImageLayout::eShaderReadOnlyOptimal, buffer)) { + return false; + } } - - auto desc_sets = desc_sets_res.value; - bool update_vertex_descriptors = UpdateDescriptorSets( - "vertex_bindings", command.vertex_bindings, allocator, desc_sets[0]); - if (!update_vertex_descriptors) { - return false; - } - bool update_frag_descriptors = UpdateDescriptorSets( - "fragment_bindings", command.fragment_bindings, allocator, desc_sets[0]); - if (!update_frag_descriptors) { - return false; - } - - command_buffer_->Get().bindDescriptorSets( - vk::PipelineBindPoint::eGraphics, pipeline_layout, 0, desc_sets, nullptr); return true; } -bool RenderPassVK::UpdateDescriptorSets(const char* label, - const Bindings& bindings, - Allocator& allocator, - vk::DescriptorSet desc_set) const { +static bool UpdateBindingLayouts(const Command& command, + const vk::CommandBuffer& buffer) { + return UpdateBindingLayouts(command.vertex_bindings, buffer) && + UpdateBindingLayouts(command.fragment_bindings, buffer); +} + +static bool UpdateBindingLayouts(const std::vector& commands, + const vk::CommandBuffer& buffer) { + for (const auto& command : commands) { + if (!UpdateBindingLayouts(command, buffer)) { + return false; + } + } + return true; +} + +static bool UpdateDescriptorSets(vk::Device device, + const Bindings& bindings, + Allocator& allocator, + vk::DescriptorSet desc_set, + CommandEncoderVK& encoder) { std::vector writes; - std::vector buffer_infos; - std::vector image_infos; + //---------------------------------------------------------------------------- + /// Setup buffer descriptors. + /// + std::vector buffer_desc; for (const auto& [buffer_index, view] : bindings.buffers) { const auto& buffer_view = view.resource.buffer; @@ -281,180 +311,329 @@ bool RenderPassVK::UpdateDescriptorSets(const char* label, return false; } - // reserved index used for per-vertex data. + // Reserved index used for per-vertex data. if (buffer_index == VertexDescriptor::kReservedVertexBufferIndex) { continue; } + if (!encoder.Track(device_buffer)) { + return false; + } + uint32_t offset = view.resource.range.offset; vk::DescriptorBufferInfo desc_buffer_info; desc_buffer_info.setBuffer(buffer); desc_buffer_info.setOffset(offset); desc_buffer_info.setRange(view.resource.range.length); - buffer_infos.push_back(desc_buffer_info); + buffer_desc.push_back(desc_buffer_info); const ShaderUniformSlot& uniform = bindings.uniforms.at(buffer_index); - vk::WriteDescriptorSet setWrite; - setWrite.setDstSet(desc_set); - setWrite.setDstBinding(uniform.binding); - setWrite.setDescriptorCount(1); - setWrite.setDescriptorType(vk::DescriptorType::eUniformBuffer); - setWrite.setPBufferInfo(&buffer_infos.back()); + vk::WriteDescriptorSet write_set; + write_set.setDstSet(desc_set); + write_set.setDstBinding(uniform.binding); + write_set.setDescriptorCount(1); + write_set.setDescriptorType(vk::DescriptorType::eUniformBuffer); + write_set.setPBufferInfo(&buffer_desc.back()); - writes.push_back(setWrite); + writes.push_back(write_set); } + //---------------------------------------------------------------------------- + /// Setup image descriptors. + /// + std::vector image_descs; for (const auto& [index, sampler_handle] : bindings.samplers) { if (bindings.textures.find(index) == bindings.textures.end()) { VALIDATION_LOG << "Missing texture for sampler: " << index; return false; } - const auto& texture_vk = - TextureVK::Cast(*bindings.textures.at(index).resource); + auto texture = bindings.textures.at(index).resource; + const auto& texture_vk = TextureVK::Cast(*texture); + const SamplerVK& sampler = SamplerVK::Cast(*sampler_handle.resource); - const Sampler& sampler = *sampler_handle.resource; - const SamplerVK& sampler_vk = SamplerVK::Cast(sampler); + if (!encoder.Track(texture) || !encoder.Track(sampler.GetSharedSampler())) { + return false; + } const SampledImageSlot& slot = bindings.sampled_images.at(index); - uint32_t mip_levels = texture_vk.GetTextureDescriptor().mip_count; - - if (!TransitionImageLayout( - texture_vk.GetImage(), vk::ImageLayout::eUndefined, - vk::ImageLayout::eTransferDstOptimal, mip_levels)) { - return false; - } - - CopyBufferToImage(texture_vk); - - if (!TransitionImageLayout( - texture_vk.GetImage(), vk::ImageLayout::eTransferDstOptimal, - vk::ImageLayout::eShaderReadOnlyOptimal, mip_levels)) { - return false; - } vk::DescriptorImageInfo desc_image_info; desc_image_info.setImageLayout(vk::ImageLayout::eShaderReadOnlyOptimal); - desc_image_info.setSampler(sampler_vk.GetSamplerVK()); + desc_image_info.setSampler(sampler.GetSamplerVK()); desc_image_info.setImageView(texture_vk.GetImageView()); - image_infos.push_back(desc_image_info); + image_descs.push_back(desc_image_info); - vk::WriteDescriptorSet setWrite; - setWrite.setDstSet(desc_set); - setWrite.setDstBinding(slot.binding); - setWrite.setDescriptorCount(1); - setWrite.setDescriptorType(vk::DescriptorType::eCombinedImageSampler); - setWrite.setPImageInfo(&image_infos.back()); + vk::WriteDescriptorSet write_set; + write_set.setDstSet(desc_set); + write_set.setDstBinding(slot.binding); + write_set.setDescriptorCount(1); + write_set.setDescriptorType(vk::DescriptorType::eCombinedImageSampler); + write_set.setPImageInfo(&image_descs.back()); - writes.push_back(setWrite); + writes.push_back(write_set); } - std::array copies; - if (!writes.empty()) { - device_.updateDescriptorSets(writes, copies); + if (writes.empty()) { + return true; } - + device.updateDescriptorSets(writes, {}); return true; } -void RenderPassVK::SetViewportAndScissor(const Command& command) const { - // set viewport. +static bool AllocateAndBindDescriptorSets( + const ContextVK& context, + const Command& command, + CommandEncoderVK& encoder, + PipelineCreateInfoVK* pipeline_create_info) { + auto& allocator = *context.GetResourceAllocator(); + vk::PipelineLayout pipeline_layout = + pipeline_create_info->GetPipelineLayout(); + + vk::DescriptorSetAllocateInfo alloc_info; + std::array dsls = { + pipeline_create_info->GetDescriptorSetLayout(), + }; + + alloc_info.setDescriptorPool(context.GetDescriptorPool()); + alloc_info.setSetLayouts(dsls); + + auto [sets_result, sets] = + context.GetDevice().allocateDescriptorSetsUnique(alloc_info); + if (sets_result != vk::Result::eSuccess) { + VALIDATION_LOG << "Failed to allocate descriptor sets: " + << vk::to_string(sets_result); + return false; + } + + const auto set = MakeSharedVK(std::move(sets[0])); + + if (!encoder.Track(set)) { + return false; + } + + bool update_vertex_descriptors = + UpdateDescriptorSets(context.GetDevice(), // + command.vertex_bindings, // + allocator, // + *set, // + encoder // + ); + if (!update_vertex_descriptors) { + return false; + } + bool update_frag_descriptors = + UpdateDescriptorSets(context.GetDevice(), // + command.fragment_bindings, // + allocator, // + *set, // + encoder // + ); + if (!update_frag_descriptors) { + return false; + } + + encoder.GetCommandBuffer().bindDescriptorSets( + vk::PipelineBindPoint::eGraphics, // bind point + pipeline_layout, // layout + 0, // first set + {vk::DescriptorSet{*set}}, // sets + nullptr // offsets + ); + return true; +} + +static void SetViewportAndScissor(const Command& command, + const vk::CommandBuffer& cmd_buffer, + const ISize& target_size) { + // Set the viewport. const auto& vp = command.viewport.value_or( - {.rect = Rect::MakeSize(GetRenderTargetSize())}); + {.rect = Rect::MakeSize(target_size)}); vk::Viewport viewport = vk::Viewport() .setWidth(vp.rect.size.width) .setHeight(-vp.rect.size.height) .setY(vp.rect.size.height) .setMinDepth(0.0f) .setMaxDepth(1.0f); - command_buffer_->Get().setViewport(0, 1, &viewport); + cmd_buffer.setViewport(0, 1, &viewport); - // scissor - const auto& sc = - command.scissor.value_or(IRect::MakeSize(GetRenderTargetSize())); + // Set the scissor rect. + const auto& sc = command.scissor.value_or(IRect::MakeSize(target_size)); vk::Rect2D scissor = vk::Rect2D() .setOffset(vk::Offset2D(sc.origin.x, sc.origin.y)) .setExtent(vk::Extent2D(sc.size.width, sc.size.height)); - command_buffer_->Get().setScissor(0, 1, &scissor); + cmd_buffer.setScissor(0, 1, &scissor); } -vk::Framebuffer RenderPassVK::CreateFrameBuffer( - const TextureVK& texture) const { - auto img_view = texture.GetImageView(); - auto size = texture.GetTextureDescriptor().size; - vk::FramebufferCreateInfo fb_create_info = vk::FramebufferCreateInfo() - .setRenderPass(render_pass_) - .setAttachmentCount(1) - .setPAttachments(&img_view) - .setWidth(size.width) - .setHeight(size.height) - .setLayers(1); - auto res = device_.createFramebuffer(fb_create_info); - FML_CHECK(res.result == vk::Result::eSuccess); - return res.value; -} +static bool EncodeCommand(const Context& context, + const Command& command, + CommandEncoderVK& encoder, + const ISize& target_size) { + if (command.index_count == 0u || command.instance_count == 0u) { + return true; + } -bool RenderPassVK::TransitionImageLayout(vk::Image image, - vk::ImageLayout layout_old, - vk::ImageLayout layout_new, - uint32_t mip_levels) const { - auto transition_cmd = - TransitionImageLayoutCommandVK(image, layout_old, layout_new, mip_levels); - return transition_cmd.Submit(command_buffer_.get()); -} + fml::ScopedCleanupClosure pop_marker( + [&encoder]() { encoder.PopDebugGroup(); }); + if (!command.label.empty()) { + encoder.PushDebugGroup(command.label.c_str()); + } else { + pop_marker.Release(); + } -bool RenderPassVK::CopyBufferToImage(const TextureVK& texture_vk) const { - auto copy_cmd = command_buffer_->GetSingleUseChild(); + const auto& cmd_buffer = encoder.GetCommandBuffer(); - const auto& size = texture_vk.GetTextureDescriptor().size; + auto& pipeline_vk = PipelineVK::Cast(*command.pipeline); + PipelineCreateInfoVK* pipeline_create_info = pipeline_vk.GetCreateInfo(); - // actual copy happens here - vk::BufferImageCopy region = - vk::BufferImageCopy() - .setBufferOffset(0) - .setBufferRowLength(0) - .setBufferImageHeight(0) - .setImageSubresource( - vk::ImageSubresourceLayers() - .setAspectMask(vk::ImageAspectFlagBits::eColor) - .setMipLevel(0) - .setBaseArrayLayer(0) - .setLayerCount(1)) - .setImageOffset(vk::Offset3D(0, 0, 0)) - .setImageExtent(vk::Extent3D(size.width, size.height, 1)); - - vk::CommandBufferBeginInfo begin_info; - begin_info.setFlags(vk::CommandBufferUsageFlagBits::eOneTimeSubmit); - auto res = copy_cmd.begin(begin_info); - - if (res != vk::Result::eSuccess) { - VALIDATION_LOG << "Failed to begin command buffer: " << vk::to_string(res); + if (!AllocateAndBindDescriptorSets(ContextVK::Cast(context), // + command, // + encoder, // + pipeline_create_info // + )) { return false; } - copy_cmd.copyBufferToImage(texture_vk.GetStagingBuffer(), - texture_vk.GetImage(), - vk::ImageLayout::eTransferDstOptimal, region); + cmd_buffer.bindPipeline(vk::PipelineBindPoint::eGraphics, + pipeline_create_info->GetVKPipeline()); - res = copy_cmd.end(); - if (res != vk::Result::eSuccess) { - VALIDATION_LOG << "Failed to end command buffer: " << vk::to_string(res); + // Set the viewport and scissors. + SetViewportAndScissor(command, cmd_buffer, target_size); + + // Set the stencil reference. + cmd_buffer.setStencilReference( + vk::StencilFaceFlagBits::eVkStencilFrontAndBack, + command.stencil_reference); + + // Configure vertex and index and buffers for binding. + auto vertex_buffer_view = command.GetVertexBuffer(); + auto index_buffer_view = command.index_buffer; + + if (!vertex_buffer_view || !index_buffer_view) { return false; } + auto& allocator = *context.GetResourceAllocator(); + + auto vertex_buffer = vertex_buffer_view.buffer->GetDeviceBuffer(allocator); + auto index_buffer = index_buffer_view.buffer->GetDeviceBuffer(allocator); + + if (!vertex_buffer || !index_buffer) { + VALIDATION_LOG << "Failed to acquire device buffers" + << " for vertex and index buffer views"; + return false; + } + + if (!encoder.Track(vertex_buffer) || !encoder.Track(index_buffer)) { + return false; + } + + // Bind the vertex buffer. + auto vertex_buffer_handle = + DeviceBufferVK::Cast(*vertex_buffer).GetVKBufferHandle(); + vk::Buffer vertex_buffers[] = {vertex_buffer_handle}; + vk::DeviceSize vertex_buffer_offsets[] = {vertex_buffer_view.range.offset}; + cmd_buffer.bindVertexBuffers(0u, 1u, vertex_buffers, vertex_buffer_offsets); + + // Bind the index buffer. + auto index_buffer_handle = + DeviceBufferVK::Cast(*index_buffer).GetVKBufferHandle(); + cmd_buffer.bindIndexBuffer(index_buffer_handle, + index_buffer_view.range.offset, + ToVKIndexType(command.index_type)); + + // Engage! + cmd_buffer.drawIndexed(command.index_count, // index count + command.instance_count, // instance count + 0u, // first index + command.base_vertex, // vertex offset + 0u // first instance + ); + return true; +} + +bool RenderPassVK::OnEncodeCommands(const Context& context) const { + if (!IsValid()) { + return false; + } + + if (commands_.empty()) { + return true; + } + + const auto& vk_context = ContextVK::Cast(context); + + const auto& render_target = GetRenderTarget(); + if (!render_target.HasColorAttachment(0u)) { + VALIDATION_LOG + << "Render target doesn't have a color attachment at index 0."; + return false; + } + + auto encoder = encoder_.lock(); + if (!encoder) { + VALIDATION_LOG << "Command encoder died before commands could be encoded."; + return false; + } + + fml::ScopedCleanupClosure pop_marker( + [&encoder]() { encoder->PopDebugGroup(); }); + if (!debug_label_.empty()) { + encoder->PushDebugGroup(debug_label_.c_str()); + } else { + pop_marker.Release(); + } + + auto cmd_buffer = encoder->GetCommandBuffer(); + + if (!UpdateBindingLayouts(commands_, cmd_buffer)) { + return false; + } + + if (!ConfigureRenderTargetAttachmentLayouts(render_target, cmd_buffer)) { + VALIDATION_LOG << "Could not complete attachment layout transitions."; + return false; + } + + const auto& target_size = render_target.GetRenderTargetSize(); + + auto framebuffer = MakeSharedVK( + CreateFramebuffer(vk_context.GetDevice(), render_target_, *render_pass_)); + if (!encoder->Track(framebuffer)) { + return false; + } + + auto clear_values = GetVKClearValues(render_target); + + vk::RenderPassBeginInfo pass_info; + pass_info.renderPass = *render_pass_; + pass_info.framebuffer = *framebuffer; + pass_info.renderArea.extent.width = static_cast(target_size.width); + pass_info.renderArea.extent.height = + static_cast(target_size.height); + pass_info.setClearValues(clear_values); + + { + cmd_buffer.beginRenderPass(pass_info, vk::SubpassContents::eInline); + + fml::ScopedCleanupClosure end_render_pass( + [cmd_buffer]() { cmd_buffer.endRenderPass(); }); + + for (const auto& command : commands_) { + if (!command.pipeline) { + continue; + } + + if (!EncodeCommand(context, command, *encoder, target_size)) { + return false; + } + } + } + return true; } -const ContextVK& RenderPassVK::GetContextVK() const { - if (auto context = context_.lock()) { - const auto& context_vk = ContextVK::Cast(*context); - return context_vk; - } - - FML_UNREACHABLE(); -} - } // namespace impeller diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/render_pass_vk.h b/engine/src/flutter/impeller/renderer/backend/vulkan/render_pass_vk.h index 4955a83ad6..eae656062c 100644 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/render_pass_vk.h +++ b/engine/src/flutter/impeller/renderer/backend/vulkan/render_pass_vk.h @@ -6,8 +6,6 @@ #include "flutter/fml/macros.h" #include "impeller/renderer/backend/vulkan/context_vk.h" -#include "impeller/renderer/backend/vulkan/fenced_command_buffer_vk.h" -#include "impeller/renderer/backend/vulkan/surface_producer_vk.h" #include "impeller/renderer/backend/vulkan/texture_vk.h" #include "impeller/renderer/backend/vulkan/vk.h" #include "impeller/renderer/command.h" @@ -18,24 +16,21 @@ namespace impeller { class RenderPassVK final : public RenderPass { public: - RenderPassVK(std::weak_ptr context, - vk::Device device, - const RenderTarget& target, - std::shared_ptr command_buffer, - vk::RenderPass render_pass); - // |RenderPass| ~RenderPassVK() override; private: friend class CommandBufferVK; - vk::Device device_; - std::shared_ptr command_buffer_; - vk::RenderPass render_pass_; - std::string label_ = ""; + vk::UniqueRenderPass render_pass_; + std::weak_ptr encoder_; + std::string debug_label_; bool is_valid_ = false; + RenderPassVK(const std::shared_ptr& context, + const RenderTarget& target, + std::weak_ptr encoder); + // |RenderPass| bool IsValid() const override; @@ -45,33 +40,6 @@ class RenderPassVK final : public RenderPass { // |RenderPass| bool OnEncodeCommands(const Context& context) const override; - bool EncodeCommand(const Context& context, const Command& command) const; - - bool AllocateAndBindDescriptorSets( - const Context& context, - const Command& command, - PipelineCreateInfoVK* pipeline_create_info) const; - - bool EndCommandBuffer(); - - bool UpdateDescriptorSets(const char* label, - const Bindings& bindings, - Allocator& allocator, - vk::DescriptorSet desc_set) const; - - void SetViewportAndScissor(const Command& command) const; - - vk::Framebuffer CreateFrameBuffer(const TextureVK& texture) const; - - bool TransitionImageLayout(vk::Image image, - vk::ImageLayout layout_old, - vk::ImageLayout layout_new, - uint32_t mip_levels) const; - - bool CopyBufferToImage(const TextureVK& texture_vk) const; - - const ContextVK& GetContextVK() const; - FML_DISALLOW_COPY_AND_ASSIGN(RenderPassVK); }; diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/sampler_vk.cc b/engine/src/flutter/impeller/renderer/backend/vulkan/sampler_vk.cc index 6212bedd2c..7d2f9bb5c9 100644 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/sampler_vk.cc +++ b/engine/src/flutter/impeller/renderer/backend/vulkan/sampler_vk.cc @@ -5,17 +5,24 @@ #include "impeller/renderer/backend/vulkan/sampler_vk.h" namespace impeller { -SamplerVK::~SamplerVK() {} - -vk::Sampler SamplerVK::GetSamplerVK() const { - return sampler_.get(); -} SamplerVK::SamplerVK(SamplerDescriptor desc, vk::UniqueSampler sampler) - : Sampler(std::move(desc)), sampler_(std::move(sampler)) { + : Sampler(std::move(desc)), + sampler_(MakeSharedVK(std::move(sampler))) { is_valid_ = true; } +SamplerVK::~SamplerVK() = default; + +vk::Sampler SamplerVK::GetSamplerVK() const { + return *sampler_; +} + +const std::shared_ptr>& +SamplerVK::GetSharedSampler() const { + return sampler_; +} + bool SamplerVK::IsValid() const { return is_valid_; } diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/sampler_vk.h b/engine/src/flutter/impeller/renderer/backend/vulkan/sampler_vk.h index 4c11bd3660..d0268ced38 100644 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/sampler_vk.h +++ b/engine/src/flutter/impeller/renderer/backend/vulkan/sampler_vk.h @@ -6,6 +6,7 @@ #include "flutter/fml/macros.h" #include "impeller/base/backend_cast.h" +#include "impeller/renderer/backend/vulkan/shared_object_vk.h" #include "impeller/renderer/backend/vulkan/vk.h" #include "impeller/renderer/sampler.h" #include "vulkan/vulkan_handles.hpp" @@ -23,10 +24,12 @@ class SamplerVK final : public Sampler, public BackendCast { vk::Sampler GetSamplerVK() const; + const std::shared_ptr>& GetSharedSampler() const; + private: friend SamplerLibraryVK; - vk::UniqueSampler sampler_; + std::shared_ptr> sampler_; bool is_valid_ = false; // |Sampler| diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/shared_object_vk.cc b/engine/src/flutter/impeller/renderer/backend/vulkan/shared_object_vk.cc new file mode 100644 index 0000000000..ddfcdf545e --- /dev/null +++ b/engine/src/flutter/impeller/renderer/backend/vulkan/shared_object_vk.cc @@ -0,0 +1,11 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/shared_object_vk.h" + +namespace impeller { + +// + +} // namespace impeller diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/shared_object_vk.h b/engine/src/flutter/impeller/renderer/backend/vulkan/shared_object_vk.h new file mode 100644 index 0000000000..d3c42a50a0 --- /dev/null +++ b/engine/src/flutter/impeller/renderer/backend/vulkan/shared_object_vk.h @@ -0,0 +1,43 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#pragma once + +#include + +#include "flutter/fml/macros.h" +#include "impeller/renderer/backend/vulkan/vk.h" + +namespace impeller { + +class SharedObjectVK { + public: + virtual ~SharedObjectVK() = default; +}; + +template +class SharedObjectVKT : public SharedObjectVK { + public: + using Resource = T; + using UniqueResource = + vk::UniqueHandle; + + explicit SharedObjectVKT(UniqueResource res) : resource_(std::move(res)) {} + + operator Resource() const { return *resource_; } + + private: + UniqueResource resource_; +}; + +template +auto MakeSharedVK( + vk::UniqueHandle handle) { + if (!handle) { + return std::shared_ptr>{nullptr}; + } + return std::make_shared>(std::move(handle)); +} + +} // namespace impeller diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/surface_producer_vk.cc b/engine/src/flutter/impeller/renderer/backend/vulkan/surface_producer_vk.cc deleted file mode 100644 index 8bd9489375..0000000000 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/surface_producer_vk.cc +++ /dev/null @@ -1,196 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "impeller/renderer/backend/vulkan/surface_producer_vk.h" - -#include -#include - -#include "impeller/base/validation.h" -#include "impeller/renderer/backend/vulkan/surface_vk.h" -#include "impeller/renderer/backend/vulkan/vk.h" - -namespace impeller { - -std::unique_ptr SurfaceProducerVK::Create( - const std::weak_ptr& context, - const SurfaceProducerCreateInfoVK& create_info) { - auto surface_producer = - std::make_unique(context, create_info); - if (!surface_producer->SetupSyncObjects()) { - VALIDATION_LOG << "Failed to setup sync objects."; - return nullptr; - } - - return surface_producer; -} - -SurfaceProducerVK::SurfaceProducerVK( - std::weak_ptr context, - const SurfaceProducerCreateInfoVK& create_info) - : context_(std::move(context)), create_info_(create_info) {} - -SurfaceProducerVK::~SurfaceProducerVK() = default; - -std::unique_ptr SurfaceProducerVK::AcquireSurface( - size_t current_frame) { - current_frame = current_frame % kMaxFramesInFlight; - const auto& sync_objects = sync_objects_[current_frame]; - - auto fence_wait_res = create_info_.device.waitForFences( - {*sync_objects->in_flight_fence}, VK_TRUE, UINT64_MAX); - if (fence_wait_res != vk::Result::eSuccess) { - VALIDATION_LOG << "Failed to wait for fence: " - << vk::to_string(fence_wait_res); - return nullptr; - } - - auto fence_reset_res = - create_info_.device.resetFences({*sync_objects->in_flight_fence}); - if (fence_reset_res != vk::Result::eSuccess) { - VALIDATION_LOG << "Failed to reset fence: " - << vk::to_string(fence_reset_res); - return nullptr; - } - - uint32_t image_index; - auto acuire_image_res = create_info_.device.acquireNextImageKHR( - create_info_.swapchain->GetSwapchain(), UINT64_MAX, - *sync_objects->image_available_semaphore, {}, &image_index); - - if (acuire_image_res != vk::Result::eSuccess && - acuire_image_res != vk::Result::eSuboptimalKHR) { - VALIDATION_LOG << "Failed to acquire next image: " - << vk::to_string(acuire_image_res); - return nullptr; - } - - SurfaceVK::SwapCallback swap_callback = [this, current_frame, image_index]() { - return Present(current_frame, image_index); - }; - - if (auto context = context_.lock()) { - ContextVK* context_vk = reinterpret_cast(context.get()); - return SurfaceVK::WrapSwapchainImage( - current_frame, create_info_.swapchain->GetSwapchainImage(image_index), - context_vk, std::move(swap_callback)); - } else { - return nullptr; - } -} - -std::unique_ptr SurfaceSyncObjectsVK::Create( - vk::Device device) { - auto sync_objects = std::make_unique(); - vk::SemaphoreCreateInfo semaphore_create_info; - - { - auto image_avail_res = device.createSemaphoreUnique(semaphore_create_info); - if (image_avail_res.result != vk::Result::eSuccess) { - VALIDATION_LOG << "Failed to create image available semaphore: " - << vk::to_string(image_avail_res.result); - return nullptr; - } - sync_objects->image_available_semaphore = std::move(image_avail_res.value); - } - - { - auto render_finished_res = - device.createSemaphoreUnique(semaphore_create_info); - if (render_finished_res.result != vk::Result::eSuccess) { - VALIDATION_LOG << "Failed to create render finished semaphore: " - << vk::to_string(render_finished_res.result); - return nullptr; - } - sync_objects->render_finished_semaphore = - std::move(render_finished_res.value); - } - - vk::FenceCreateInfo fence_create_info; - fence_create_info.flags = vk::FenceCreateFlagBits::eSignaled; - { - auto fence_res = device.createFenceUnique(fence_create_info); - if (fence_res.result != vk::Result::eSuccess) { - VALIDATION_LOG << "Failed to create fence: " - << vk::to_string(fence_res.result); - return nullptr; - } - sync_objects->in_flight_fence = std::move(fence_res.value); - } - - return sync_objects; -} - -bool SurfaceProducerVK::SetupSyncObjects() { - for (size_t i = 0; i < kMaxFramesInFlight; i++) { - auto sync_objects = SurfaceSyncObjectsVK::Create(create_info_.device); - if (!sync_objects) { - return false; - } - sync_objects_[i] = std::move(sync_objects); - } - return true; -} - -bool SurfaceProducerVK::Submit(uint32_t frame_num) { - auto& sync_objects = sync_objects_[frame_num]; - vk::SubmitInfo submit_info; - std::array wait_stages = { - vk::PipelineStageFlagBits::eColorAttachmentOutput}; - submit_info.setWaitDstStageMask(wait_stages); - - std::array wait_semaphores = { - *sync_objects->image_available_semaphore}; - submit_info.setWaitSemaphores(wait_semaphores); - - std::array signal_semaphores = { - *sync_objects->render_finished_semaphore}; - submit_info.setSignalSemaphores(signal_semaphores); - - auto graphics_submit_res = create_info_.graphics_queue.submit( - {submit_info}, *sync_objects->in_flight_fence); - if (graphics_submit_res != vk::Result::eSuccess) { - VALIDATION_LOG << "Failed to submit graphics queue: " - << vk::to_string(graphics_submit_res); - return false; - } - - auto idle_wait_res = create_info_.graphics_queue.waitIdle(); - if (idle_wait_res != vk::Result::eSuccess) { - VALIDATION_LOG << "Failed to wait for graphics queue idle: " - << vk::to_string(idle_wait_res); - return false; - } - - return true; -} - -bool SurfaceProducerVK::Present(size_t frame_num, uint32_t image_index) { - Submit(frame_num); - - auto& sync_objects = sync_objects_[frame_num]; - - vk::PresentInfoKHR present_info; - - std::array signal_semaphores = { - *sync_objects->render_finished_semaphore}; - present_info.setWaitSemaphores(signal_semaphores); - - std::array swapchains = { - create_info_.swapchain->GetSwapchain()}; - present_info.setSwapchains(swapchains); - - std::array image_indices = {image_index}; - present_info.setImageIndices(image_indices); - - auto present_res = create_info_.present_queue.presentKHR(present_info); - if ((present_res != vk::Result::eSuccess) && - (present_res != vk::Result::eSuboptimalKHR)) { - return false; - } - - return true; -} - -} // namespace impeller diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/surface_producer_vk.h b/engine/src/flutter/impeller/renderer/backend/vulkan/surface_producer_vk.h deleted file mode 100644 index 88133ea6e9..0000000000 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/surface_producer_vk.h +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#pragma once - -#include - -#include "flutter/fml/macros.h" -#include "impeller/renderer/backend/vulkan/swapchain_vk.h" -#include "impeller/renderer/backend/vulkan/vk.h" -#include "impeller/renderer/surface.h" -#include "vulkan/vulkan_handles.hpp" - -namespace impeller { - -struct SurfaceProducerCreateInfoVK { - vk::Device device; - vk::Queue graphics_queue; - vk::Queue present_queue; - SwapchainVK* swapchain; -}; - -class SurfaceSyncObjectsVK { - public: - vk::UniqueSemaphore image_available_semaphore; - vk::UniqueSemaphore render_finished_semaphore; - vk::UniqueFence in_flight_fence; - - static std::unique_ptr Create(vk::Device device); -}; - -class SurfaceProducerVK { - public: - static std::unique_ptr Create( - const std::weak_ptr& context, - const SurfaceProducerCreateInfoVK& create_info); - - SurfaceProducerVK(std::weak_ptr context, - const SurfaceProducerCreateInfoVK& create_info); - - ~SurfaceProducerVK(); - - std::unique_ptr AcquireSurface(size_t current_frame); - - private: - std::weak_ptr context_; - - bool SetupSyncObjects(); - - bool Submit(uint32_t frame_num); - - bool Present(size_t frame_num, uint32_t image_index); - - const SurfaceProducerCreateInfoVK create_info_; - - // sync objects - std::unique_ptr sync_objects_[kMaxFramesInFlight]; - - FML_DISALLOW_COPY_AND_ASSIGN(SurfaceProducerVK); -}; - -} // namespace impeller diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/surface_vk.cc b/engine/src/flutter/impeller/renderer/backend/vulkan/surface_vk.cc index d3963fb7d5..a1f09a42b3 100644 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/surface_vk.cc +++ b/engine/src/flutter/impeller/renderer/backend/vulkan/surface_vk.cc @@ -4,78 +4,98 @@ #include "impeller/renderer/backend/vulkan/surface_vk.h" +#include "impeller/renderer/backend/vulkan/swapchain_image_vk.h" #include "impeller/renderer/backend/vulkan/texture_vk.h" #include "impeller/renderer/surface.h" namespace impeller { + std::unique_ptr SurfaceVK::WrapSwapchainImage( - uint32_t frame_num, - SwapchainImageVK* swapchain_image, - ContextVK* context, + const std::shared_ptr& context, + const std::shared_ptr& swapchain_image, SwapCallback swap_callback) { - if (!swapchain_image) { + if (!context || !swapchain_image || !swap_callback) { return nullptr; } - TextureDescriptor color0_tex; - color0_tex.type = TextureType::kTexture2D; - color0_tex.format = swapchain_image->GetPixelFormat(); - color0_tex.size = swapchain_image->GetSize(); - color0_tex.usage = static_cast(TextureUsage::kRenderTarget); - color0_tex.sample_count = SampleCount::kCount1; - color0_tex.storage_mode = StorageMode::kDevicePrivate; + TextureDescriptor msaa_tex_desc; + msaa_tex_desc.storage_mode = StorageMode::kDeviceTransient; + msaa_tex_desc.type = TextureType::kTexture2DMultisample; + msaa_tex_desc.sample_count = SampleCount::kCount4; + msaa_tex_desc.format = swapchain_image->GetPixelFormat(); + msaa_tex_desc.size = swapchain_image->GetSize(); + msaa_tex_desc.usage = static_cast(TextureUsage::kRenderTarget); + + auto msaa_tex = context->GetResourceAllocator()->CreateTexture(msaa_tex_desc); + if (!msaa_tex) { + VALIDATION_LOG << "Could not allocate MSAA color texture."; + return nullptr; + } + msaa_tex->SetLabel("ImpellerOnscreenColorMSAA"); + + TextureDescriptor resolve_tex_desc; + resolve_tex_desc.type = TextureType::kTexture2D; + resolve_tex_desc.format = swapchain_image->GetPixelFormat(); + resolve_tex_desc.size = swapchain_image->GetSize(); + resolve_tex_desc.usage = + static_cast(TextureUsage::kRenderTarget); + resolve_tex_desc.sample_count = SampleCount::kCount1; + resolve_tex_desc.storage_mode = StorageMode::kDevicePrivate; + + std::shared_ptr resolve_tex = + std::make_shared(resolve_tex_desc, // + context, // + swapchain_image // + ); + + if (!resolve_tex) { + VALIDATION_LOG << "Could not wrap resolve texture."; + return nullptr; + } + resolve_tex->SetLabel("ImpellerOnscreenResolve"); ColorAttachment color0; - auto color_texture_info = std::make_unique(TextureInfoVK{ - .backing_type = TextureBackingTypeVK::kWrappedTexture, - .wrapped_texture = - { - .swapchain_image = swapchain_image, - .frame_num = frame_num, - }, - }); - color0.texture = std::make_shared(color0_tex, context, - std::move(color_texture_info)); + color0.texture = msaa_tex; color0.clear_color = Color::DarkSlateGray(); color0.load_action = LoadAction::kClear; - color0.store_action = StoreAction::kDontCare; + color0.store_action = StoreAction::kMultisampleResolve; + color0.resolve_texture = resolve_tex; TextureDescriptor stencil0_tex; + stencil0_tex.storage_mode = StorageMode::kDeviceTransient; stencil0_tex.type = TextureType::kTexture2D; - stencil0_tex.format = swapchain_image->GetPixelFormat(); - stencil0_tex.size = swapchain_image->GetSize(); + stencil0_tex.sample_count = SampleCount::kCount4; + stencil0_tex.format = + context->GetDeviceCapabilities().GetDefaultStencilFormat(); + stencil0_tex.size = msaa_tex_desc.size; stencil0_tex.usage = static_cast(TextureUsage::kRenderTarget); - stencil0_tex.sample_count = SampleCount::kCount1; + + auto stencil_tex = + context->GetResourceAllocator()->CreateTexture(stencil0_tex); + if (!stencil_tex) { + VALIDATION_LOG << "Could not create stencil texture."; + return nullptr; + } + stencil_tex->SetLabel("ImpellerOnscreenStencil"); StencilAttachment stencil0; + stencil0.texture = stencil_tex; stencil0.clear_stencil = 0; - auto stencil_texture_info = std::make_unique(TextureInfoVK{ - .backing_type = TextureBackingTypeVK::kWrappedTexture, - .wrapped_texture = - { - .swapchain_image = swapchain_image, - .frame_num = frame_num, - }, - }); - stencil0.texture = std::make_shared( - stencil0_tex, context, std::move(stencil_texture_info)); stencil0.load_action = LoadAction::kClear; stencil0.store_action = StoreAction::kDontCare; RenderTarget render_target_desc; render_target_desc.SetColorAttachment(color0, 0u); + render_target_desc.SetStencilAttachment(stencil0); - return std::unique_ptr(new SurfaceVK( - render_target_desc, swapchain_image, std::move(swap_callback))); + // The constructor is private. So make_unique may not be used. + return std::unique_ptr( + new SurfaceVK(render_target_desc, std::move(swap_callback))); } -SurfaceVK::SurfaceVK(const RenderTarget& target, - SwapchainImageVK* swapchain_image, - SwapCallback swap_callback) - : Surface(target) { - swap_callback_ = std::move(swap_callback); -} +SurfaceVK::SurfaceVK(const RenderTarget& target, SwapCallback swap_callback) + : Surface(target), swap_callback_(std::move(swap_callback)) {} SurfaceVK::~SurfaceVK() = default; diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/surface_vk.h b/engine/src/flutter/impeller/renderer/backend/vulkan/surface_vk.h index 77d6367e3a..b6824f55cf 100644 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/surface_vk.h +++ b/engine/src/flutter/impeller/renderer/backend/vulkan/surface_vk.h @@ -8,7 +8,7 @@ #include "flutter/fml/macros.h" #include "impeller/renderer/backend/vulkan/context_vk.h" -#include "impeller/renderer/backend/vulkan/swapchain_vk.h" +#include "impeller/renderer/backend/vulkan/swapchain_image_vk.h" #include "impeller/renderer/surface.h" namespace impeller { @@ -18,22 +18,18 @@ class SurfaceVK final : public Surface { using SwapCallback = std::function; static std::unique_ptr WrapSwapchainImage( - uint32_t frame_num, - SwapchainImageVK* swapchain_image, - ContextVK* context, + const std::shared_ptr& context, + const std::shared_ptr& swapchain_image, SwapCallback swap_callback); - SurfaceVK(const RenderTarget& target, - SwapchainImageVK* swapchain_image, - SwapCallback swap_callback); - // |Surface| ~SurfaceVK() override; private: - const SwapchainImageVK* swapchain_image_; SwapCallback swap_callback_; + SurfaceVK(const RenderTarget& target, SwapCallback swap_callback); + // |Surface| bool Present() const override; diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain_details_vk.cc b/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain_details_vk.cc deleted file mode 100644 index 4caf552d5f..0000000000 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain_details_vk.cc +++ /dev/null @@ -1,124 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "impeller/renderer/backend/vulkan/swapchain_details_vk.h" - -#include "impeller/base/validation.h" - -namespace impeller { - -std::unique_ptr SwapchainDetailsVK::Create( - vk::PhysicalDevice physical_device, - vk::SurfaceKHR surface) { - FML_DCHECK(surface) << "surface provided as nullptr"; - - auto capabilities_res = physical_device.getSurfaceCapabilitiesKHR(surface); - if (capabilities_res.result != vk::Result::eSuccess) { - VALIDATION_LOG << "Failed to get surface capabilities: " - << vk::to_string(capabilities_res.result); - return nullptr; - } - vk::SurfaceCapabilitiesKHR capabilities = capabilities_res.value; - - auto surface_formats_res = physical_device.getSurfaceFormatsKHR(surface); - if (surface_formats_res.result != vk::Result::eSuccess) { - VALIDATION_LOG << "Failed to get surface formats: " - << vk::to_string(surface_formats_res.result); - return nullptr; - } - std::vector surface_formats = surface_formats_res.value; - - auto surface_present_modes_res = - physical_device.getSurfacePresentModesKHR(surface); - if (surface_present_modes_res.result != vk::Result::eSuccess) { - VALIDATION_LOG << "Failed to get surface present modes: " - << vk::to_string(surface_present_modes_res.result); - return nullptr; - } - std::vector surface_present_modes = - surface_present_modes_res.value; - - const auto composite_alphas = capabilities.supportedCompositeAlpha; - vk::CompositeAlphaFlagBitsKHR composite_alpha; - if (composite_alphas & vk::CompositeAlphaFlagBitsKHR::eOpaque) { - composite_alpha = vk::CompositeAlphaFlagBitsKHR::eOpaque; - } else if (composite_alphas & vk::CompositeAlphaFlagBitsKHR::eInherit) { - composite_alpha = vk::CompositeAlphaFlagBitsKHR::eInherit; - } else { - VALIDATION_LOG << "No supported composite alpha found."; - return nullptr; - } - - return std::make_unique( - capabilities, surface_formats, surface_present_modes, composite_alpha); -} - -vk::SurfaceFormatKHR SwapchainDetailsVK::PickSurfaceFormat() const { - for (const auto& format : surface_formats_) { - if ((format.format == vk::Format::eR8G8B8A8Unorm || - format.format == vk::Format::eB8G8R8A8Unorm) && - format.colorSpace == vk::ColorSpaceKHR::eSrgbNonlinear) { - return format; - } - } - - VALIDATION_LOG << "Picking a sub-optimal surface format."; - return surface_formats_[0]; -} - -vk::PresentModeKHR SwapchainDetailsVK::PickPresentationMode() const { - for (const auto& mode : present_modes_) { - if (mode == vk::PresentModeKHR::eMailbox) { - return mode; - } - } - - FML_LOG(ERROR) << "Picking a sub-optimal presentation mode."; - // Vulkan spec dictates that FIFO is always available. - return vk::PresentModeKHR::eFifo; -} - -vk::CompositeAlphaFlagBitsKHR SwapchainDetailsVK::PickCompositeAlpha() const { - return composite_alpha_; -} - -vk::Extent2D SwapchainDetailsVK::PickExtent() const { - if (surface_capabilities_.currentExtent.width != - std::numeric_limits::max()) { - return surface_capabilities_.currentExtent; - } - - vk::Extent2D actual_extent = { - std::max(surface_capabilities_.minImageExtent.width, - std::min(surface_capabilities_.maxImageExtent.width, - surface_capabilities_.currentExtent.width)), - std::max(surface_capabilities_.minImageExtent.height, - std::min(surface_capabilities_.maxImageExtent.height, - surface_capabilities_.currentExtent.height))}; - return actual_extent; -} - -uint32_t SwapchainDetailsVK::GetImageCount() const { - uint32_t image_count = surface_capabilities_.minImageCount; - // for triple buffering - return image_count + 1; -} - -vk::SurfaceTransformFlagBitsKHR SwapchainDetailsVK::GetTransform() const { - return surface_capabilities_.currentTransform; -} - -SwapchainDetailsVK::SwapchainDetailsVK( - vk::SurfaceCapabilitiesKHR capabilities, - std::vector surface_formats, - std::vector surface_present_modes, - vk::CompositeAlphaFlagBitsKHR composite_alpha) - : surface_capabilities_(capabilities), - surface_formats_(std::move(surface_formats)), - present_modes_(std::move(surface_present_modes)), - composite_alpha_(composite_alpha) {} - -SwapchainDetailsVK::~SwapchainDetailsVK() = default; - -} // namespace impeller diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain_details_vk.h b/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain_details_vk.h deleted file mode 100644 index 6c2264e0f8..0000000000 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain_details_vk.h +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#pragma once - -#include "flutter/fml/macros.h" -#include "impeller/renderer/backend/vulkan/vk.h" - -namespace impeller { - -class SwapchainDetailsVK { - public: - static std::unique_ptr Create( - vk::PhysicalDevice physical_device, - vk::SurfaceKHR surface); - - SwapchainDetailsVK(vk::SurfaceCapabilitiesKHR capabilities, - std::vector surface_formats, - std::vector surface_present_modes, - vk::CompositeAlphaFlagBitsKHR composite_alpha); - - ~SwapchainDetailsVK(); - - vk::SurfaceFormatKHR PickSurfaceFormat() const; - - vk::PresentModeKHR PickPresentationMode() const; - - vk::CompositeAlphaFlagBitsKHR PickCompositeAlpha() const; - - vk::Extent2D PickExtent() const; - - uint32_t GetImageCount() const; - - vk::SurfaceTransformFlagBitsKHR GetTransform() const; - - private: - vk::SurfaceCapabilitiesKHR surface_capabilities_; - std::vector surface_formats_; - std::vector present_modes_; - vk::CompositeAlphaFlagBitsKHR composite_alpha_; - - FML_DISALLOW_COPY_AND_ASSIGN(SwapchainDetailsVK); -}; - -} // namespace impeller diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain_image_vk.cc b/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain_image_vk.cc new file mode 100644 index 0000000000..843f0b44a8 --- /dev/null +++ b/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain_image_vk.cc @@ -0,0 +1,59 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/swapchain_image_vk.h" + +namespace impeller { + +SwapchainImageVK::SwapchainImageVK(vk::Device device, + vk::Image image, + PixelFormat image_format, + ISize image_size) + : image_(image), image_format_(image_format), image_size_(image_size) { + vk::ImageViewCreateInfo view_info; + view_info.image = image_; + view_info.viewType = vk::ImageViewType::e2D; + view_info.format = ToVKImageFormat(image_format_); + view_info.subresourceRange.aspectMask = vk::ImageAspectFlagBits::eColor; + view_info.subresourceRange.baseMipLevel = 0u; + view_info.subresourceRange.levelCount = 1u; + view_info.subresourceRange.baseArrayLayer = 0u; + view_info.subresourceRange.layerCount = 1u; + + auto [view_result, view] = device.createImageViewUnique(view_info); + if (view_result != vk::Result::eSuccess) { + VALIDATION_LOG << "Could not create image view: " + << vk::to_string(view_result); + return; + } + + image_view_ = std::move(view); + is_valid_ = true; +} + +SwapchainImageVK::~SwapchainImageVK() = default; + +bool SwapchainImageVK::IsValid() const { + return is_valid_; +} + +PixelFormat SwapchainImageVK::GetPixelFormat() const { + return image_format_; +} + +ISize SwapchainImageVK::GetSize() const { + return image_size_; +} + +// |TextureSourceVK| +vk::Image SwapchainImageVK::GetVKImage() const { + return image_; +} + +// |TextureSourceVK| +vk::ImageView SwapchainImageVK::GetVKImageView() const { + return image_view_.get(); +} + +} // namespace impeller diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain_image_vk.h b/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain_image_vk.h new file mode 100644 index 0000000000..9869b689aa --- /dev/null +++ b/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain_image_vk.h @@ -0,0 +1,47 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#pragma once + +#include "flutter/fml/macros.h" +#include "impeller/geometry/size.h" +#include "impeller/renderer/backend/vulkan/formats_vk.h" +#include "impeller/renderer/backend/vulkan/texture_source_vk.h" +#include "impeller/renderer/backend/vulkan/vk.h" + +namespace impeller { + +class SwapchainImageVK final : public TextureSourceVK { + public: + SwapchainImageVK(vk::Device device, + vk::Image image, + PixelFormat image_format, + ISize image_size); + + // |TextureSourceVK| + ~SwapchainImageVK() override; + + bool IsValid() const; + + PixelFormat GetPixelFormat() const; + + ISize GetSize() const; + + // |TextureSourceVK| + vk::Image GetVKImage() const override; + + // |TextureSourceVK| + vk::ImageView GetVKImageView() const override; + + private: + vk::Image image_ = VK_NULL_HANDLE; + PixelFormat image_format_ = PixelFormat::kUnknown; + ISize image_size_; + vk::UniqueImageView image_view_ = {}; + bool is_valid_ = false; + + FML_DISALLOW_COPY_AND_ASSIGN(SwapchainImageVK); +}; + +} // namespace impeller diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain_impl_vk.cc b/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain_impl_vk.cc new file mode 100644 index 0000000000..c7cb323a93 --- /dev/null +++ b/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain_impl_vk.cc @@ -0,0 +1,432 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/swapchain_impl_vk.h" + +#include "impeller/renderer/backend/vulkan/command_buffer_vk.h" +#include "impeller/renderer/backend/vulkan/command_encoder_vk.h" +#include "impeller/renderer/backend/vulkan/context_vk.h" +#include "impeller/renderer/backend/vulkan/formats_vk.h" +#include "impeller/renderer/backend/vulkan/surface_vk.h" +#include "impeller/renderer/backend/vulkan/swapchain_image_vk.h" + +namespace impeller { + +static constexpr size_t kMaxFramesInFlight = 3u; + +struct FrameSynchronizer { + vk::UniqueFence acquire; + vk::UniqueSemaphore render_ready; + vk::UniqueSemaphore present_ready; + bool is_valid = false; + + explicit FrameSynchronizer(const vk::Device& device) { + auto acquire_res = device.createFenceUnique( + vk::FenceCreateInfo{vk::FenceCreateFlagBits::eSignaled}); + auto render_res = device.createSemaphoreUnique({}); + auto present_res = device.createSemaphoreUnique({}); + if (acquire_res.result != vk::Result::eSuccess || + render_res.result != vk::Result::eSuccess || + present_res.result != vk::Result::eSuccess) { + VALIDATION_LOG << "Could not create synchornizer."; + return; + } + acquire = std::move(acquire_res.value); + render_ready = std::move(render_res.value); + present_ready = std::move(present_res.value); + is_valid = true; + } + + ~FrameSynchronizer() = default; + + bool WaitForFence(const vk::Device& device) { + if (device.waitForFences( + *acquire, // fence + true, // wait all + std::numeric_limits::max() // timeout (ns) + ) != vk::Result::eSuccess) { + return false; + } + if (device.resetFences(*acquire) != vk::Result::eSuccess) { + return false; + } + return true; + } +}; + +static bool ContainsFormat(const std::vector& formats, + vk::SurfaceFormatKHR format) { + return std::find(formats.begin(), formats.end(), format) != formats.end(); +} + +static std::optional ChooseSurfaceFormat( + const std::vector& formats, + PixelFormat preference) { + const auto colorspace = vk::ColorSpaceKHR::eSrgbNonlinear; + const auto vk_preference = + vk::SurfaceFormatKHR{ToVKImageFormat(preference), colorspace}; + if (ContainsFormat(formats, vk_preference)) { + return vk_preference; + } + + std::vector options = { + {vk::Format::eB8G8R8A8Unorm, colorspace}, + {vk::Format::eR8G8B8A8Unorm, colorspace}}; + for (const auto& format : options) { + if (ContainsFormat(formats, format)) { + return format; + } + } + + return std::nullopt; +} + +static std::optional ChooseAlphaCompositionMode( + vk::CompositeAlphaFlagsKHR flags) { + if (flags & vk::CompositeAlphaFlagBitsKHR::ePreMultiplied) { + return vk::CompositeAlphaFlagBitsKHR::ePreMultiplied; + } + if (flags & vk::CompositeAlphaFlagBitsKHR::eOpaque) { + return vk::CompositeAlphaFlagBitsKHR::eOpaque; + } + return std::nullopt; +} + +static std::optional ChoosePresentQueue( + const vk::PhysicalDevice& physical_device, + const vk::Device& device, + const vk::SurfaceKHR& surface) { + const auto families = physical_device.getQueueFamilyProperties(); + for (size_t family_index = 0u; family_index < families.size(); + family_index++) { + auto [result, supported] = + physical_device.getSurfaceSupportKHR(family_index, surface); + if (result == vk::Result::eSuccess && supported) { + return device.getQueue(family_index, 0u); + } + } + return std::nullopt; +} + +std::shared_ptr SwapchainImplVK::Create( + const std::shared_ptr& context, + vk::UniqueSurfaceKHR surface, + vk::SwapchainKHR old_swapchain) { + return std::shared_ptr( + new SwapchainImplVK(context, std::move(surface), old_swapchain)); +} + +SwapchainImplVK::SwapchainImplVK(const std::shared_ptr& context, + vk::UniqueSurfaceKHR surface, + vk::SwapchainKHR old_swapchain) { + if (!context) { + return; + } + + const auto& vk_context = ContextVK::Cast(*context); + + auto [caps_result, caps] = + vk_context.GetPhysicalDevice().getSurfaceCapabilitiesKHR(*surface); + if (caps_result != vk::Result::eSuccess) { + VALIDATION_LOG << "Could not get surface capabilities: " + << vk::to_string(caps_result); + return; + } + + auto [formats_result, formats] = + vk_context.GetPhysicalDevice().getSurfaceFormatsKHR(*surface); + if (formats_result != vk::Result::eSuccess) { + VALIDATION_LOG << "Could not get surface formats: " + << vk::to_string(formats_result); + return; + } + + const auto format = ChooseSurfaceFormat( + formats, vk_context.GetDeviceCapabilities().GetDefaultColorFormat()); + if (!format.has_value()) { + VALIDATION_LOG << "Swapchain has no supported formats."; + return; + } + + const auto composite = + ChooseAlphaCompositionMode(caps.supportedCompositeAlpha); + if (!composite.has_value()) { + VALIDATION_LOG << "No composition mode supported."; + return; + } + + auto present_queue = ChoosePresentQueue(vk_context.GetPhysicalDevice(), // + vk_context.GetDevice(), // + *surface // + ); + if (!present_queue.has_value()) { + VALIDATION_LOG << "Could not pick present queue."; + return; + } + + vk::SwapchainCreateInfoKHR swapchain_info; + swapchain_info.surface = *surface; + swapchain_info.imageFormat = format.value().format; + swapchain_info.imageColorSpace = format.value().colorSpace; + swapchain_info.presentMode = vk::PresentModeKHR::eFifo; + swapchain_info.imageExtent = vk::Extent2D{ + std::clamp(caps.currentExtent.width, caps.minImageExtent.width, + caps.maxImageExtent.width), + std::clamp(caps.currentExtent.height, caps.minImageExtent.height, + caps.maxImageExtent.height), + }; + swapchain_info.minImageCount = std::clamp( + caps.minImageCount + 1u, caps.minImageCount, caps.maxImageCount); + swapchain_info.imageArrayLayers = 1u; + swapchain_info.imageUsage = vk::ImageUsageFlagBits::eColorAttachment; + swapchain_info.preTransform = caps.currentTransform; + swapchain_info.compositeAlpha = composite.value(); + // If we set the clipped value to true, Vulkan expects we will never read back + // from the buffer. This is analogous to [CAMetalLayer framebufferOnly] in + // Metal. + swapchain_info.clipped = true; + // Setting queue family indices is irrelevant since the present mode is + // exclusive. + swapchain_info.imageSharingMode = vk::SharingMode::eExclusive; + swapchain_info.oldSwapchain = old_swapchain; + + auto [swapchain_result, swapchain] = + vk_context.GetDevice().createSwapchainKHRUnique(swapchain_info); + if (swapchain_result != vk::Result::eSuccess) { + VALIDATION_LOG << "Could not create swapchain: " + << vk::to_string(swapchain_result); + return; + } + + auto [images_result, images] = + vk_context.GetDevice().getSwapchainImagesKHR(*swapchain); + if (images_result != vk::Result::eSuccess) { + VALIDATION_LOG << "Could not get swapchain images."; + return; + } + + std::vector> swapchain_images; + for (const auto& image : images) { + auto swapchain_image = std::make_shared( + vk_context.GetDevice(), // + image, // + ToPixelFormat(swapchain_info.imageFormat), // + ISize::MakeWH(swapchain_info.imageExtent.width, + swapchain_info.imageExtent.height) // + ); + if (!swapchain_image->IsValid()) { + VALIDATION_LOG << "Could not create swapchain image."; + return; + } + swapchain_images.emplace_back(swapchain_image); + } + + std::vector> synchronizers; + for (size_t i = 0u; i < kMaxFramesInFlight; i++) { + auto sync = std::make_unique(vk_context.GetDevice()); + if (!sync->is_valid) { + VALIDATION_LOG << "Could not create frame synchronizers."; + return; + } + synchronizers.emplace_back(std::move(sync)); + } + FML_DCHECK(!synchronizers.empty()); + + context_ = context; + surface_ = std::move(surface); + present_queue_ = present_queue.value(); + surface_format_ = swapchain_info.imageFormat; + swapchain_ = std::move(swapchain); + images_ = std::move(swapchain_images); + synchronizers_ = std::move(synchronizers); + current_frame_ = synchronizers_.size() - 1u; + is_valid_ = true; +} + +SwapchainImplVK::~SwapchainImplVK() { + DestroySwapchain(); +} + +bool SwapchainImplVK::IsValid() const { + return is_valid_; +} + +void SwapchainImplVK::WaitIdle() const { + if (auto context = context_.lock()) { + [[maybe_unused]] auto result = + ContextVK::Cast(*context).GetDevice().waitIdle(); + } +} + +std::pair +SwapchainImplVK::DestroySwapchain() { + WaitIdle(); + is_valid_ = false; + synchronizers_.clear(); + images_.clear(); + context_.reset(); + return {std::move(surface_), std::move(swapchain_)}; +} + +vk::Format SwapchainImplVK::GetSurfaceFormat() const { + return surface_format_; +} + +std::shared_ptr SwapchainImplVK::GetContext() const { + return context_.lock(); +} + +SwapchainImplVK::AcquireResult SwapchainImplVK::AcquireNextDrawable() { + auto context_strong = context_.lock(); + if (!context_strong) { + return {}; + } + + const auto& context = ContextVK::Cast(*context_strong); + + current_frame_ = (current_frame_ + 1u) % synchronizers_.size(); + + const auto& sync = synchronizers_[current_frame_]; + + //---------------------------------------------------------------------------- + /// Wait on the host for the synchronizer fence. + /// + if (!sync->WaitForFence(context.GetDevice())) { + VALIDATION_LOG << "Could not wait for fence."; + return {}; + } + + //---------------------------------------------------------------------------- + /// Get the next image index. + /// + auto [acq_result, index] = context.GetDevice().acquireNextImageKHR( + *swapchain_, // swapchain + std::numeric_limits::max(), // timeout (nanoseconds) + *sync->render_ready, // signal semaphore + nullptr // fence + ); + + if (acq_result == vk::Result::eSuboptimalKHR) { + return AcquireResult{true /* out of date */}; + } + + if (acq_result != vk::Result::eSuccess) { + VALIDATION_LOG << "Could not acquire next swapchain image: " + << vk::to_string(acq_result); + return {}; + } + + if (index >= images_.size()) { + VALIDATION_LOG << "Swapchain returned an invalid image index."; + return {}; + } + + auto image = images_[index % images_.size()]; + uint32_t image_index = index; + return AcquireResult{SurfaceVK::WrapSwapchainImage( + context_strong, // context + image, // swapchain image + [weak_swapchain = weak_from_this(), image, image_index]() -> bool { + auto swapchain = weak_swapchain.lock(); + if (!swapchain) { + return false; + } + return swapchain->Present(image, image_index); + } // swap callback + )}; +} + +bool SwapchainImplVK::Present(const std::shared_ptr& image, + uint32_t index) { + auto context_strong = context_.lock(); + if (!context_strong) { + return false; + } + + const auto& context = ContextVK::Cast(*context_strong); + + const auto& sync = synchronizers_[current_frame_]; + + //---------------------------------------------------------------------------- + /// Transition the image to color-attachment-optimal. + /// + { + auto cmd_buffer = context.CreateCommandBuffer(); + if (!cmd_buffer) { + return false; + } + + auto vk_cmd_buffer = + CommandBufferVK::Cast(*cmd_buffer).GetEncoder()->GetCommandBuffer(); + vk::ImageMemoryBarrier image_barrier; + image_barrier.srcAccessMask = vk::AccessFlagBits::eColorAttachmentWrite; + image_barrier.dstAccessMask = vk::AccessFlagBits::eColorAttachmentRead; + image_barrier.image = image->GetVKImage(); + image_barrier.oldLayout = vk::ImageLayout::eColorAttachmentOptimal; + image_barrier.newLayout = vk::ImageLayout::ePresentSrcKHR; + image_barrier.subresourceRange.aspectMask = vk::ImageAspectFlagBits::eColor; + image_barrier.subresourceRange.baseMipLevel = 0u; + image_barrier.subresourceRange.levelCount = 1u; + image_barrier.subresourceRange.baseArrayLayer = 0u; + image_barrier.subresourceRange.layerCount = 1u; + vk_cmd_buffer.pipelineBarrier(vk::PipelineStageFlagBits::eAllGraphics, // + vk::PipelineStageFlagBits::eAllGraphics, // + {}, // + nullptr, // + nullptr, // + image_barrier // + ); + if (!cmd_buffer->SubmitCommands()) { + return false; + } + } + + //---------------------------------------------------------------------------- + /// Signal that the presentation semaphore is ready. + /// + { + vk::SubmitInfo submit_info; + vk::PipelineStageFlags wait_stage = + vk::PipelineStageFlagBits::eColorAttachmentOutput; + submit_info.setWaitDstStageMask(wait_stage); + submit_info.setWaitSemaphores(*sync->render_ready); + submit_info.setSignalSemaphores(*sync->present_ready); + auto result = + context.GetGraphicsQueue().submit(submit_info, *sync->acquire); + if (result != vk::Result::eSuccess) { + VALIDATION_LOG << "Could not wait on render semaphore: " + << vk::to_string(result); + return false; + } + } + + //---------------------------------------------------------------------------- + /// Present the image. + /// + uint32_t indices[] = {static_cast(index)}; + + vk::PresentInfoKHR present_info; + present_info.setSwapchains(*swapchain_); + present_info.setImageIndices(indices); + present_info.setWaitSemaphores(*sync->present_ready); + + switch (auto result = present_queue_.presentKHR(present_info)) { + case vk::Result::eErrorOutOfDateKHR: + // Caller will recreate the impl on acquisition, not submission. + [[fallthrough]]; + case vk::Result::eErrorSurfaceLostKHR: + // Vulkan guarantees that the set of queue operations will still complete + // successfully. + [[fallthrough]]; + case vk::Result::eSuccess: + return true; + default: + VALIDATION_LOG << "Could not present queue: " << vk::to_string(result); + return false; + } + FML_UNREACHABLE(); + return false; +} + +} // namespace impeller diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain_impl_vk.h b/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain_impl_vk.h new file mode 100644 index 0000000000..0df1a2f7a2 --- /dev/null +++ b/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain_impl_vk.h @@ -0,0 +1,80 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#pragma once + +#include +#include + +#include "flutter/fml/macros.h" +#include "impeller/renderer/backend/vulkan/vk.h" + +namespace impeller { + +class Context; +class SwapchainImageVK; +class Surface; +struct FrameSynchronizer; + +//------------------------------------------------------------------------------ +/// @brief An instance of a swapchain that does NOT adapt to going out of +/// date with the underlying surface. Errors will be indicated when +/// the next drawable is acquired from this implementation of the +/// swapchain. If the error is due the swapchain going out of date, +/// the caller must recreate another instance by optionally +/// stealing this implementations guts. +/// +class SwapchainImplVK final + : public std::enable_shared_from_this { + public: + static std::shared_ptr Create( + const std::shared_ptr& context, + vk::UniqueSurfaceKHR surface, + vk::SwapchainKHR old_swapchain = VK_NULL_HANDLE); + + ~SwapchainImplVK(); + + bool IsValid() const; + + struct AcquireResult { + std::unique_ptr surface; + bool out_of_date = false; + + AcquireResult(bool p_out_of_date = false) : out_of_date(p_out_of_date) {} + + AcquireResult(std::unique_ptr p_surface) + : surface(std::move(p_surface)) {} + }; + + AcquireResult AcquireNextDrawable(); + + vk::Format GetSurfaceFormat() const; + + std::shared_ptr GetContext() const; + + std::pair DestroySwapchain(); + + private: + std::weak_ptr context_; + vk::UniqueSurfaceKHR surface_; + vk::Queue present_queue_ = {}; + vk::Format surface_format_ = vk::Format::eUndefined; + vk::UniqueSwapchainKHR swapchain_; + std::vector> images_; + std::vector> synchronizers_; + size_t current_frame_ = 0u; + bool is_valid_ = false; + + SwapchainImplVK(const std::shared_ptr& context, + vk::UniqueSurfaceKHR surface, + vk::SwapchainKHR old_swapchain); + + bool Present(const std::shared_ptr& image, uint32_t index); + + void WaitIdle() const; + + FML_DISALLOW_COPY_AND_ASSIGN(SwapchainImplVK); +}; + +} // namespace impeller diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain_vk.cc b/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain_vk.cc index a2554ed61d..0bc6f9aca2 100644 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain_vk.cc +++ b/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain_vk.cc @@ -4,148 +4,70 @@ #include "impeller/renderer/backend/vulkan/swapchain_vk.h" -#include "fml/logging.h" -#include "impeller/base/validation.h" -#include "impeller/renderer/backend/vulkan/formats_vk.h" +#include "flutter/fml/trace_event.h" +#include "impeller/renderer/backend/vulkan/swapchain_impl_vk.h" namespace impeller { -std::unique_ptr SwapchainVK::Create(vk::Device device, - vk::SurfaceKHR surface, - SwapchainDetailsVK& details) { - vk::SurfaceFormatKHR surface_format = details.PickSurfaceFormat(); - vk::PresentModeKHR present_mode = details.PickPresentationMode(); - vk::Extent2D extent = details.PickExtent(); - - vk::SwapchainCreateInfoKHR create_info; - create_info.surface = surface; - create_info.imageFormat = surface_format.format; - create_info.imageColorSpace = surface_format.colorSpace; - create_info.presentMode = present_mode; - create_info.imageExtent = extent; - - create_info.minImageCount = details.GetImageCount(); - create_info.imageArrayLayers = 1; - create_info.imageUsage = vk::ImageUsageFlagBits::eColorAttachment; - create_info.preTransform = details.GetTransform(); - create_info.compositeAlpha = details.PickCompositeAlpha(); - create_info.clipped = VK_TRUE; - - create_info.imageSharingMode = vk::SharingMode::eExclusive; - { - // TODO (kaushikiska): This needs to change if graphics queue is not the - // same as present queue which is rare. - create_info.queueFamilyIndexCount = 0; - create_info.pQueueFamilyIndices = nullptr; - } - - create_info.oldSwapchain = nullptr; - - auto swapchain_res = device.createSwapchainKHRUnique(create_info); - if (swapchain_res.result != vk::Result::eSuccess) { - VALIDATION_LOG << "Failed to create swapchain: " - << vk::to_string(swapchain_res.result); +std::shared_ptr SwapchainVK::Create( + const std::shared_ptr& context, + vk::UniqueSurfaceKHR surface) { + auto impl = SwapchainImplVK::Create(context, std::move(surface)); + if (!impl || !impl->IsValid()) { return nullptr; } - - auto swapchain = std::make_unique( - device, std::move(swapchain_res.value), surface_format.format, extent); - if (!swapchain->CreateSwapchainImages()) { - VALIDATION_LOG << "Failed to create swapchain images."; - return nullptr; - } - - return swapchain; + return std::shared_ptr(new SwapchainVK(std::move(impl))); } -bool SwapchainVK::CreateSwapchainImages() { - FML_DCHECK(swapchain_images_.empty()) << "Swapchain images already created"; - auto res = device_.getSwapchainImagesKHR(*swapchain_); - if (res.result != vk::Result::eSuccess) { - FML_CHECK(false) << "Failed to get swapchain images: " - << vk::to_string(res.result); - return false; - } - - std::vector images = res.value; - for (const auto& image : images) { - vk::ImageViewCreateInfo create_info; - create_info.image = image; - create_info.viewType = vk::ImageViewType::e2D; - create_info.format = image_format_; - - create_info.components.r = vk::ComponentSwizzle::eIdentity; - create_info.components.g = vk::ComponentSwizzle::eIdentity; - create_info.components.b = vk::ComponentSwizzle::eIdentity; - create_info.components.a = vk::ComponentSwizzle::eIdentity; - - // TODO (kaushikiska): This has to match up to the texture we will be - // rendering to (TextureVK). - create_info.subresourceRange.aspectMask = vk::ImageAspectFlagBits::eColor; - create_info.subresourceRange.baseMipLevel = 0; - create_info.subresourceRange.levelCount = 1; - create_info.subresourceRange.baseArrayLayer = 0; - create_info.subresourceRange.layerCount = 1; - - auto img_view_res = device_.createImageViewUnique(create_info); - if (img_view_res.result != vk::Result::eSuccess) { - VALIDATION_LOG << "Failed to create image view: " - << vk::to_string(img_view_res.result); - return false; - } - - swapchain_images_.push_back(std::make_unique( - image, std::move(img_view_res.value), image_format_, extent_)); - } - - return true; -} - -SwapchainVK::SwapchainVK(vk::Device device, - vk::UniqueSwapchainKHR swapchain, - vk::Format image_format, - vk::Extent2D extent) - : device_(device), - swapchain_(std::move(swapchain)), - image_format_(image_format), - extent_(extent) {} +SwapchainVK::SwapchainVK(std::shared_ptr impl) + : impl_(std::move(impl)) {} SwapchainVK::~SwapchainVK() = default; -SwapchainImageVK::SwapchainImageVK(vk::Image image, - vk::UniqueImageView image_view, - vk::Format image_format, - vk::Extent2D extent) - : image_(image), - image_view_(std::move(image_view)), - image_format_(image_format), - extent_(extent) {} - -vk::SwapchainKHR SwapchainVK::GetSwapchain() const { - return *swapchain_; +bool SwapchainVK::IsValid() const { + return impl_ ? impl_->IsValid() : false; } -SwapchainImageVK* SwapchainVK::GetSwapchainImage(uint32_t image_index) const { - FML_DCHECK(image_index < swapchain_images_.size()); - return swapchain_images_[image_index].get(); +std::unique_ptr SwapchainVK::AcquireNextDrawable() { + if (!IsValid()) { + return nullptr; + } + + TRACE_EVENT0("impeller", __FUNCTION__); + + auto result = impl_->AcquireNextDrawable(); + if (!result.out_of_date) { + return std::move(result.surface); + } + + TRACE_EVENT0("impeller", "RecreateSwapchain"); + + // This swapchain implementation indicates that it is out of date. Tear it + // down and make a new one. + auto context = impl_->GetContext(); + auto [surface, old_swapchain] = impl_->DestroySwapchain(); + + auto new_impl = SwapchainImplVK::Create(context, // + std::move(surface), // + *old_swapchain // + ); + if (!new_impl || !new_impl->IsValid()) { + VALIDATION_LOG << "Could not update swapchain."; + // The old swapchain is dead because we took its surface. This is + // unrecoverable. + impl_.reset(); + return nullptr; + } + impl_ = std::move(new_impl); + + //---------------------------------------------------------------------------- + /// We managed to recreate the swapchain in the new configuration. Try again. + /// + return AcquireNextDrawable(); } -PixelFormat SwapchainImageVK::GetPixelFormat() const { - return ToPixelFormat(image_format_); +vk::Format SwapchainVK::GetSurfaceFormat() const { + return IsValid() ? impl_->GetSurfaceFormat() : vk::Format::eUndefined; } -ISize SwapchainImageVK::GetSize() const { - return ISize(extent_.width, extent_.height); -} - -vk::Image SwapchainImageVK::GetImage() const { - return image_; -} - -vk::ImageView SwapchainImageVK::GetImageView() const { - return image_view_.get(); -} - -SwapchainImageVK::~SwapchainImageVK() = default; - } // namespace impeller diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain_vk.h b/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain_vk.h index 11c51ee1de..d9fd159389 100644 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain_vk.h +++ b/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain_vk.h @@ -4,66 +4,41 @@ #pragma once -#include +#include #include "flutter/fml/macros.h" -#include "impeller/geometry/size.h" -#include "impeller/renderer/backend/vulkan/swapchain_details_vk.h" +#include "impeller/renderer/backend/vulkan/vk.h" +#include "impeller/renderer/context.h" #include "impeller/renderer/surface.h" namespace impeller { -class SwapchainImageVK { - public: - SwapchainImageVK(vk::Image image, - vk::UniqueImageView image_view, - vk::Format image_format, - vk::Extent2D extent); - - ~SwapchainImageVK(); - - PixelFormat GetPixelFormat() const; - - ISize GetSize() const; - - vk::Image GetImage() const; - - vk::ImageView GetImageView() const; - - private: - vk::Image image_; - vk::UniqueImageView image_view_; - vk::Format image_format_; - vk::Extent2D extent_; - - FML_DISALLOW_COPY_AND_ASSIGN(SwapchainImageVK); -}; +class SwapchainImplVK; +//------------------------------------------------------------------------------ +/// @brief A swapchain that adapts to the underlying surface going out of +/// date. If the caller cannot acquire the next drawable, it is due +/// to an unrecoverable error and the swapchain must be recreated +/// with a new surface. +/// class SwapchainVK { public: - static std::unique_ptr Create(vk::Device device, - vk::SurfaceKHR surface, - SwapchainDetailsVK& details); - - SwapchainVK(vk::Device device, - vk::UniqueSwapchainKHR swapchain, - vk::Format image_format, - vk::Extent2D extent); + static std::shared_ptr Create( + const std::shared_ptr& context, + vk::UniqueSurfaceKHR surface); ~SwapchainVK(); - vk::SwapchainKHR GetSwapchain() const; + bool IsValid() const; - SwapchainImageVK* GetSwapchainImage(uint32_t image_index) const; + std::unique_ptr AcquireNextDrawable(); + + vk::Format GetSurfaceFormat() const; private: - bool CreateSwapchainImages(); + std::shared_ptr impl_; - vk::Device device_; - vk::UniqueSwapchainKHR swapchain_; - vk::Format image_format_; - vk::Extent2D extent_; - std::vector> swapchain_images_; + explicit SwapchainVK(std::shared_ptr impl); FML_DISALLOW_COPY_AND_ASSIGN(SwapchainVK); }; diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/texture_source_vk.cc b/engine/src/flutter/impeller/renderer/backend/vulkan/texture_source_vk.cc new file mode 100644 index 0000000000..c411c62489 --- /dev/null +++ b/engine/src/flutter/impeller/renderer/backend/vulkan/texture_source_vk.cc @@ -0,0 +1,16 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/texture_source_vk.h" + +namespace impeller { + +bool TextureSourceVK::SetContents(const TextureDescriptor& desc, + const uint8_t* contents, + size_t length, + size_t slice) { + return false; +} + +} // namespace impeller diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/texture_source_vk.h b/engine/src/flutter/impeller/renderer/backend/vulkan/texture_source_vk.h new file mode 100644 index 0000000000..5fac2ce939 --- /dev/null +++ b/engine/src/flutter/impeller/renderer/backend/vulkan/texture_source_vk.h @@ -0,0 +1,27 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#pragma once + +#include "flutter/fml/macros.h" +#include "impeller/renderer/backend/vulkan/vk.h" +#include "impeller/renderer/texture_descriptor.h" + +namespace impeller { + +class TextureSourceVK { + public: + virtual ~TextureSourceVK() = default; + + virtual bool SetContents(const TextureDescriptor& desc, + const uint8_t* contents, + size_t length, + size_t slice); + + virtual vk::Image GetVKImage() const = 0; + + virtual vk::ImageView GetVKImageView() const = 0; +}; + +} // namespace impeller diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/texture_vk.cc b/engine/src/flutter/impeller/renderer/backend/vulkan/texture_vk.cc index 4faa15f3ea..70c048e1f4 100644 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/texture_vk.cc +++ b/engine/src/flutter/impeller/renderer/backend/vulkan/texture_vk.cc @@ -7,32 +7,24 @@ namespace impeller { TextureVK::TextureVK(TextureDescriptor desc, - ContextVK* context, - std::unique_ptr texture_info) - : Texture(desc), - context_(context), - texture_info_(std::move(texture_info)) {} + std::weak_ptr context, + std::shared_ptr source) + : Texture(desc), context_(std::move(context)), source_(std::move(source)) {} -TextureVK::~TextureVK() { - if (!IsWrapped() && IsValid()) { - const auto& texture = texture_info_->allocated_texture; - vmaDestroyImage(*texture.backing_allocation.allocator, texture.image, - texture.backing_allocation.allocation); - } -} +TextureVK::~TextureVK() = default; void TextureVK::SetLabel(std::string_view label) { - context_->SetDebugName(GetImage(), label); + auto context = context_.lock(); + if (!context) { + // The context may have died. + return; + } + ContextVK::Cast(*context).SetDebugName(GetImage(), label); } bool TextureVK::OnSetContents(const uint8_t* contents, size_t length, size_t slice) { - if (IsWrapped()) { - FML_LOG(ERROR) << "Cannot set contents of a wrapped texture"; - return false; - } - if (!IsValid() || !contents) { return false; } @@ -45,15 +37,7 @@ bool TextureVK::OnSetContents(const uint8_t* contents, return false; } - // currently we are only supporting 2d textures, no cube textures etc. - auto mapping = texture_info_->allocated_texture.staging_buffer.GetMapping(); - - if (mapping) { - memcpy(mapping, contents, length); - return true; - } else { - return false; - } + return source_->SetContents(desc, contents, length, slice); } bool TextureVK::OnSetContents(std::shared_ptr mapping, @@ -64,61 +48,83 @@ bool TextureVK::OnSetContents(std::shared_ptr mapping, } bool TextureVK::IsValid() const { - switch (texture_info_->backing_type) { - case TextureBackingTypeVK::kUnknownType: - return false; - case TextureBackingTypeVK::kAllocatedTexture: - return texture_info_->allocated_texture.image; - case TextureBackingTypeVK::kWrappedTexture: - return texture_info_->wrapped_texture.swapchain_image; - } + return !!source_; } ISize TextureVK::GetSize() const { return GetTextureDescriptor().size; } -TextureInfoVK* TextureVK::GetTextureInfo() const { - return texture_info_.get(); -} - -bool TextureVK::IsWrapped() const { - return texture_info_->backing_type == TextureBackingTypeVK::kWrappedTexture; +vk::Image TextureVK::GetImage() const { + return source_->GetVKImage(); } vk::ImageView TextureVK::GetImageView() const { - switch (texture_info_->backing_type) { - case TextureBackingTypeVK::kUnknownType: - return nullptr; - case TextureBackingTypeVK::kAllocatedTexture: - return vk::ImageView{texture_info_->allocated_texture.image_view}; - case TextureBackingTypeVK::kWrappedTexture: - return texture_info_->wrapped_texture.swapchain_image->GetImageView(); - } + return source_->GetVKImageView(); } -vk::Image TextureVK::GetImage() const { - switch (texture_info_->backing_type) { - case TextureBackingTypeVK::kUnknownType: - FML_CHECK(false) << "Unknown texture backing type"; - case TextureBackingTypeVK::kAllocatedTexture: - return vk::Image{texture_info_->allocated_texture.image}; - case TextureBackingTypeVK::kWrappedTexture: - return texture_info_->wrapped_texture.swapchain_image->GetImage(); +static constexpr vk::ImageAspectFlags ToImageAspectFlags( + vk::ImageLayout layout) { + switch (layout) { + case vk::ImageLayout::eColorAttachmentOptimal: + case vk::ImageLayout::eShaderReadOnlyOptimal: + return vk::ImageAspectFlagBits::eColor; + case vk::ImageLayout::eDepthAttachmentOptimal: + return vk::ImageAspectFlagBits::eDepth; + case vk::ImageLayout::eStencilAttachmentOptimal: + return vk::ImageAspectFlagBits::eStencil; + default: + FML_DLOG(INFO) << "Unknown layout to determine aspect."; + return vk::ImageAspectFlagBits::eNone; } + FML_UNREACHABLE(); } -vk::Buffer TextureVK::GetStagingBuffer() const { - switch (texture_info_->backing_type) { - case TextureBackingTypeVK::kUnknownType: - FML_CHECK(false) << "Unknown texture backing type"; - return nullptr; - case TextureBackingTypeVK::kAllocatedTexture: - return texture_info_->allocated_texture.staging_buffer.GetBufferHandle(); - case TextureBackingTypeVK::kWrappedTexture: - FML_CHECK(false) << "Wrapped textures do not have staging buffers"; - return nullptr; +vk::ImageLayout TextureVK::GetLayout() const { + ReaderLock lock(layout_mutex_); + return layout_; +} + +vk::ImageLayout TextureVK::SetLayoutWithoutEncoding( + vk::ImageLayout layout) const { + WriterLock lock(layout_mutex_); + const auto old_layout = layout_; + layout_ = layout; + return old_layout; +} + +bool TextureVK::SetLayout(vk::ImageLayout new_layout, + const vk::CommandBuffer& buffer) const { + const auto old_layout = SetLayoutWithoutEncoding(new_layout); + if (new_layout == old_layout) { + return true; } + + vk::ImageMemoryBarrier image_barrier; + image_barrier.srcAccessMask = vk::AccessFlagBits::eColorAttachmentWrite | + vk::AccessFlagBits::eTransferWrite; + image_barrier.dstAccessMask = vk::AccessFlagBits::eColorAttachmentRead | + vk::AccessFlagBits::eShaderRead; + image_barrier.oldLayout = old_layout; + image_barrier.newLayout = new_layout; + image_barrier.image = GetImage(); + image_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + image_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + image_barrier.subresourceRange.aspectMask = ToImageAspectFlags(new_layout); + image_barrier.subresourceRange.baseMipLevel = 0u; + image_barrier.subresourceRange.levelCount = GetTextureDescriptor().mip_count; + image_barrier.subresourceRange.baseArrayLayer = 0u; + image_barrier.subresourceRange.layerCount = 1u; + + buffer.pipelineBarrier(vk::PipelineStageFlagBits::eAllGraphics, // src stage + vk::PipelineStageFlagBits::eAllGraphics, // dst stage + {}, // dependency flags + nullptr, // memory barriers + nullptr, // buffer barriers + image_barrier // image barriers + ); + + return true; } } // namespace impeller diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/texture_vk.h b/engine/src/flutter/impeller/renderer/backend/vulkan/texture_vk.h index 08dd3769e2..8ab9a00d27 100644 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/texture_vk.h +++ b/engine/src/flutter/impeller/renderer/backend/vulkan/texture_vk.h @@ -4,64 +4,44 @@ #pragma once +#include + #include "flutter/fml/macros.h" #include "impeller/base/backend_cast.h" +#include "impeller/base/thread.h" #include "impeller/renderer/backend/vulkan/context_vk.h" #include "impeller/renderer/backend/vulkan/device_buffer_vk.h" -#include "impeller/renderer/backend/vulkan/swapchain_vk.h" +#include "impeller/renderer/backend/vulkan/texture_source_vk.h" #include "impeller/renderer/backend/vulkan/vk.h" #include "impeller/renderer/texture.h" namespace impeller { -enum class TextureBackingTypeVK { - kUnknownType, - kAllocatedTexture, - kWrappedTexture, -}; - -struct WrappedTextureInfoVK { - SwapchainImageVK* swapchain_image = nullptr; - uint32_t frame_num = 0; -}; - -struct AllocatedTextureInfoVK { - DeviceBufferAllocationVK staging_buffer = {}; - BackingAllocationVK backing_allocation = {}; - VkImage image = VK_NULL_HANDLE; - VkImageView image_view = VK_NULL_HANDLE; -}; - -struct TextureInfoVK { - TextureBackingTypeVK backing_type; - union { - WrappedTextureInfoVK wrapped_texture; - AllocatedTextureInfoVK allocated_texture; - }; -}; - class TextureVK final : public Texture, public BackendCast { public: TextureVK(TextureDescriptor desc, - ContextVK* context, - std::unique_ptr texture_info); + std::weak_ptr context, + std::shared_ptr source); // |Texture| ~TextureVK() override; - bool IsWrapped() const; - vk::Image GetImage() const; vk::ImageView GetImageView() const; - vk::Buffer GetStagingBuffer() const; + bool SetLayout(vk::ImageLayout layout, const vk::CommandBuffer& buffer) const; - TextureInfoVK* GetTextureInfo() const; + vk::ImageLayout SetLayoutWithoutEncoding(vk::ImageLayout layout) const; + + vk::ImageLayout GetLayout() const; private: - ContextVK* context_; - std::unique_ptr texture_info_; + std::weak_ptr context_; + std::shared_ptr source_; + mutable RWMutex layout_mutex_; + mutable vk::ImageLayout layout_ IPLR_GUARDED_BY(layout_mutex_) = + vk::ImageLayout::eUndefined; // |Texture| void SetLabel(std::string_view label) override; diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/vk.h b/engine/src/flutter/impeller/renderer/backend/vulkan/vk.h index a62d94495c..788b41bb6f 100644 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/vk.h +++ b/engine/src/flutter/impeller/renderer/backend/vulkan/vk.h @@ -4,11 +4,56 @@ #pragma once +#include "flutter/fml/build_config.h" #include "flutter/fml/logging.h" #include "impeller/base/validation.h" #define VK_NO_PROTOTYPES +#if FML_OS_IOS + +// #ifndef VK_USE_PLATFORM_IOS_MVK +// #define VK_USE_PLATFORM_IOS_MVK +// #endif // VK_USE_PLATFORM_IOS_MVK + +#ifndef VK_USE_PLATFORM_METAL_EXT +#define VK_USE_PLATFORM_METAL_EXT +#endif // VK_USE_PLATFORM_METAL_EXT + +#elif FML_OS_MACOSX + +// #ifndef VK_USE_PLATFORM_MACOS_MVK +// #define VK_USE_PLATFORM_MACOS_MVK +// #endif // VK_USE_PLATFORM_MACOS_MVK + +#ifndef VK_USE_PLATFORM_METAL_EXT +#define VK_USE_PLATFORM_METAL_EXT +#endif // VK_USE_PLATFORM_METAL_EXT + +#elif FML_OS_ANDROID + +#ifndef VK_USE_PLATFORM_ANDROID_KHR +#define VK_USE_PLATFORM_ANDROID_KHR +#endif // VK_USE_PLATFORM_ANDROID_KHR + +#elif FML_OS_LINUX + +// Nothing for now. + +#elif FML_OS_WIN + +#ifndef VK_USE_PLATFORM_WIN32_KHR +#define VK_USE_PLATFORM_WIN32_KHR +#endif // VK_USE_PLATFORM_WIN32_KHR + +#elif OS_FUCHSIA + +#ifndef VK_USE_PLATFORM_ANDROID_KHR +#define VK_USE_PLATFORM_ANDROID_KHR +#endif // VK_USE_PLATFORM_ANDROID_KHR + +#endif // FML_OS + #if !defined(NDEBUG) #define VULKAN_HPP_ASSERT FML_CHECK #else @@ -21,15 +66,12 @@ { [[maybe_unused]] auto res = (ignored); } #include "vulkan/vulkan.hpp" -static_assert(VK_HEADER_VERSION >= 215, - "Vulkan headers are must not be too old."); +static_assert(VK_HEADER_VERSION >= 215, "Vulkan headers must not be too old."); #include "flutter/flutter_vma/flutter_vma.h" namespace impeller { -const uint32_t kMaxFramesInFlight = 2; - struct QueueVK { size_t family = 0; size_t index = 0; diff --git a/engine/src/flutter/impeller/renderer/pipeline_descriptor.cc b/engine/src/flutter/impeller/renderer/pipeline_descriptor.cc index 2a79f11f4a..06367a7148 100644 --- a/engine/src/flutter/impeller/renderer/pipeline_descriptor.cc +++ b/engine/src/flutter/impeller/renderer/pipeline_descriptor.cc @@ -95,6 +95,14 @@ PipelineDescriptor& PipelineDescriptor::SetVertexDescriptor( return *this; } +size_t PipelineDescriptor::GetMaxColorAttacmentBindIndex() const { + size_t max = 0; + for (const auto& color : color_attachment_descriptors_) { + max = std::max(color.first, max); + } + return max; +} + PipelineDescriptor& PipelineDescriptor::SetColorAttachmentDescriptor( size_t index, ColorAttachmentDescriptor desc) { diff --git a/engine/src/flutter/impeller/renderer/pipeline_descriptor.h b/engine/src/flutter/impeller/renderer/pipeline_descriptor.h index e80d31fd10..f6d4930d15 100644 --- a/engine/src/flutter/impeller/renderer/pipeline_descriptor.h +++ b/engine/src/flutter/impeller/renderer/pipeline_descriptor.h @@ -55,6 +55,8 @@ class PipelineDescriptor final : public Comparable { const std::shared_ptr& GetVertexDescriptor() const; + size_t GetMaxColorAttacmentBindIndex() const; + PipelineDescriptor& SetColorAttachmentDescriptor( size_t index, ColorAttachmentDescriptor desc); diff --git a/engine/src/flutter/impeller/renderer/render_pass.cc b/engine/src/flutter/impeller/renderer/render_pass.cc index 5ca17a0342..d4e0bde029 100644 --- a/engine/src/flutter/impeller/renderer/render_pass.cc +++ b/engine/src/flutter/impeller/renderer/render_pass.cc @@ -74,4 +74,8 @@ bool RenderPass::EncodeCommands() const { return OnEncodeCommands(*context); } +const std::weak_ptr& RenderPass::GetContext() const { + return context_; +} + } // namespace impeller diff --git a/engine/src/flutter/impeller/renderer/render_pass.h b/engine/src/flutter/impeller/renderer/render_pass.h index 1e7c2c087c..a75b59b279 100644 --- a/engine/src/flutter/impeller/renderer/render_pass.h +++ b/engine/src/flutter/impeller/renderer/render_pass.h @@ -64,6 +64,8 @@ class RenderPass { RenderPass(std::weak_ptr context, const RenderTarget& target); + const std::weak_ptr& GetContext() const; + virtual void OnSetLabel(std::string label) = 0; virtual bool OnEncodeCommands(const Context& context) const = 0; diff --git a/engine/src/flutter/impeller/renderer/render_target.cc b/engine/src/flutter/impeller/renderer/render_target.cc index 24215a5ebb..aba17fd653 100644 --- a/engine/src/flutter/impeller/renderer/render_target.cc +++ b/engine/src/flutter/impeller/renderer/render_target.cc @@ -148,6 +148,14 @@ PixelFormat RenderTarget::GetRenderTargetPixelFormat() const { return PixelFormat::kUnknown; } +size_t RenderTarget::GetMaxColorAttacmentBindIndex() const { + size_t max = 0; + for (const auto& color : colors_) { + max = std::max(color.first, max); + } + return max; +} + RenderTarget& RenderTarget::SetColorAttachment( const ColorAttachment& attachment, size_t index) { @@ -344,4 +352,23 @@ RenderTarget RenderTarget::CreateOffscreenMSAA( return target; } +size_t RenderTarget::GetTotalAttachmentCount() const { + size_t count = 0u; + for (const auto& [_, color] : colors_) { + if (color.texture) { + count++; + } + if (color.resolve_texture) { + count++; + } + } + if (depth_.has_value()) { + count++; + } + if (stencil_.has_value()) { + count++; + } + return count; +} + } // namespace impeller diff --git a/engine/src/flutter/impeller/renderer/render_target.h b/engine/src/flutter/impeller/renderer/render_target.h index 3137ee4975..a03c41d7f2 100644 --- a/engine/src/flutter/impeller/renderer/render_target.h +++ b/engine/src/flutter/impeller/renderer/render_target.h @@ -17,7 +17,7 @@ namespace impeller { class Context; -class RenderTarget { +class RenderTarget final { public: struct AttachmentConfig { StorageMode storage_mode; @@ -91,12 +91,16 @@ class RenderTarget { RenderTarget& SetStencilAttachment( std::optional attachment); + size_t GetMaxColorAttacmentBindIndex() const; + const std::map& GetColorAttachments() const; const std::optional& GetDepthAttachment() const; const std::optional& GetStencilAttachment() const; + size_t GetTotalAttachmentCount() const; + private: std::map colors_; std::optional depth_; diff --git a/engine/src/flutter/shell/gpu/gpu_surface_vulkan_impeller.cc b/engine/src/flutter/shell/gpu/gpu_surface_vulkan_impeller.cc index 8797cdf34c..0e3854900a 100644 --- a/engine/src/flutter/shell/gpu/gpu_surface_vulkan_impeller.cc +++ b/engine/src/flutter/shell/gpu/gpu_surface_vulkan_impeller.cc @@ -56,16 +56,7 @@ std::unique_ptr GPUSurfaceVulkanImpeller::AcquireFrame( } auto& context_vk = impeller::ContextVK::Cast(*impeller_context_); - std::unique_ptr surface = - context_vk.AcquireSurface(frame_num_++); - - auto swap_callback = [weak = weak_factory_.GetWeakPtr()]() -> bool { - if (weak) { - // TODO (kaushikiska@): Invoke the clean-up callback. - // Blocked by - https://github.com/flutter/flutter/issues/112387 - } - return true; - }; + std::unique_ptr surface = context_vk.AcquireNextSurface(); SurfaceFrame::SubmitCallback submit_callback = fml::MakeCopyable([renderer = impeller_renderer_, // diff --git a/engine/src/flutter/shell/gpu/gpu_surface_vulkan_impeller.h b/engine/src/flutter/shell/gpu/gpu_surface_vulkan_impeller.h index def6198620..cf72b2e0e1 100644 --- a/engine/src/flutter/shell/gpu/gpu_surface_vulkan_impeller.h +++ b/engine/src/flutter/shell/gpu/gpu_surface_vulkan_impeller.h @@ -29,7 +29,6 @@ class GPUSurfaceVulkanImpeller final : public Surface { std::shared_ptr impeller_renderer_; std::shared_ptr aiks_context_; bool is_valid_ = false; - uint64_t frame_num_ = 0; fml::WeakPtrFactory weak_factory_; // |Surface| diff --git a/engine/src/flutter/shell/platform/android/android_surface_vulkan_impeller.cc b/engine/src/flutter/shell/platform/android/android_surface_vulkan_impeller.cc index 65a682bb3d..ca2b4f448d 100644 --- a/engine/src/flutter/shell/platform/android/android_surface_vulkan_impeller.cc +++ b/engine/src/flutter/shell/platform/android/android_surface_vulkan_impeller.cc @@ -104,7 +104,6 @@ bool AndroidSurfaceVulkanImpeller::SetNativeWindow( fml::RefPtr window) { native_window_ = std::move(window); bool success = native_window_ && native_window_->IsValid(); - if (success) { auto& context_vk = impeller::ContextVK::Cast(*impeller_context_); auto surface = context_vk.CreateAndroidSurface(native_window_->handle()); @@ -114,8 +113,7 @@ bool AndroidSurfaceVulkanImpeller::SetNativeWindow( return false; } - context_vk.SetupSwapchain(std::move(surface)); - return true; + return context_vk.SetWindowSurface(std::move(surface)); } native_window_ = nullptr; diff --git a/engine/src/flutter/vulkan/procs/vulkan_proc_table.cc b/engine/src/flutter/vulkan/procs/vulkan_proc_table.cc index b4eb57032e..8fa35010a9 100644 --- a/engine/src/flutter/vulkan/procs/vulkan_proc_table.cc +++ b/engine/src/flutter/vulkan/procs/vulkan_proc_table.cc @@ -8,18 +8,15 @@ #include "flutter/fml/logging.h" -#define ACQUIRE_PROC(name, context) \ - if (!(name = AcquireProc("vk" #name, context))) { \ - FML_DLOG(INFO) << "Could not acquire proc: vk" << #name; \ - return false; \ +#define ACQUIRE_PROC(name, context) \ + if (!(name = AcquireProc("vk" #name, context))) { \ + return false; \ } -#define ACQUIRE_PROC_EITHER(name, name2, context) \ - if (!(name = AcquireProc("vk" #name, context)) && \ - !(name2 = AcquireProc("vk" #name2, context))) { \ - FML_DLOG(INFO) << "Could not acquire proc: vk" << #name << ", or proc: vk" \ - << #name2; \ - return false; \ +#define ACQUIRE_PROC_EITHER(name, name2, context) \ + if (!(name = AcquireProc("vk" #name, context)) && \ + !(name2 = AcquireProc("vk" #name2, context))) { \ + return false; \ } namespace vulkan {