diff --git a/engine/src/flutter/lib/ui/painting/image_decoding.cc b/engine/src/flutter/lib/ui/painting/image_decoding.cc index 4ec6e7b421..045ca8dd19 100644 --- a/engine/src/flutter/lib/ui/painting/image_decoding.cc +++ b/engine/src/flutter/lib/ui/painting/image_decoding.cc @@ -46,7 +46,7 @@ sk_sp DecodeImage(std::vector buffer) { if (sk_sp image = flow::TextureImageCreate(context, *generator)) return image; - // The, as a fallback, try to create a regular Skia managed image. These + // Then, as a fallback, try to create a regular Skia managed image. These // don't require a context ready. return flow::BitmapImageCreate(*generator); } diff --git a/engine/src/flutter/shell/common/surface.cc b/engine/src/flutter/shell/common/surface.cc index e75f61e015..0580613642 100644 --- a/engine/src/flutter/shell/common/surface.cc +++ b/engine/src/flutter/shell/common/surface.cc @@ -3,12 +3,23 @@ // found in the LICENSE file. #include "flutter/shell/common/surface.h" +#include "lib/ftl/logging.h" +#include "third_party/skia/include/core/SkSurface.h" namespace shell { -SurfaceFrame::SurfaceFrame() : submitted_(false) {} +SurfaceFrame::SurfaceFrame(sk_sp surface, + SubmitCallback submit_callback) + : submitted_(false), surface_(surface), submit_callback_(submit_callback) { + FTL_DCHECK(submit_callback_); +} -SurfaceFrame::~SurfaceFrame() = default; +SurfaceFrame::~SurfaceFrame() { + if (submit_callback_) { + // Dropping without a Submit. + submit_callback_(nullptr); + } +} bool SurfaceFrame::Submit() { if (submitted_) { @@ -20,7 +31,21 @@ bool SurfaceFrame::Submit() { return submitted_; } -Surface::Surface() = default; +SkCanvas* SurfaceFrame::SkiaCanvas() { + return surface_ != nullptr ? surface_->getCanvas() : nullptr; +} + +bool SurfaceFrame::PerformSubmit() { + if (submit_callback_ == nullptr) { + return false; + } + + if (submit_callback_(SkiaCanvas())) { + return true; + } + + return false; +} Surface::~Surface() = default; diff --git a/engine/src/flutter/shell/common/surface.h b/engine/src/flutter/shell/common/surface.h index 15052911c8..1dcfcb67dd 100644 --- a/engine/src/flutter/shell/common/surface.h +++ b/engine/src/flutter/shell/common/surface.h @@ -13,28 +13,32 @@ namespace shell { +/// Represents a Frame that has been fully configured for the underlying client +/// rendering API. A frame may only be sumitted once. class SurfaceFrame { public: - SurfaceFrame(); + using SubmitCallback = std::function; - virtual ~SurfaceFrame(); + SurfaceFrame(sk_sp surface, SubmitCallback submit_callback); + + ~SurfaceFrame(); bool Submit(); - virtual SkCanvas* SkiaCanvas() = 0; + SkCanvas* SkiaCanvas(); private: bool submitted_; + sk_sp surface_; + SubmitCallback submit_callback_; - virtual bool PerformSubmit() = 0; + bool PerformSubmit(); FTL_DISALLOW_COPY_AND_ASSIGN(SurfaceFrame); }; class Surface { public: - Surface(); - virtual ~Surface(); virtual bool Setup() = 0; @@ -44,9 +48,6 @@ class Surface { virtual std::unique_ptr AcquireFrame(const SkISize& size) = 0; virtual GrContext* GetContext() = 0; - - private: - FTL_DISALLOW_COPY_AND_ASSIGN(Surface); }; } // namespace shell diff --git a/engine/src/flutter/shell/config.gni b/engine/src/flutter/shell/config.gni new file mode 100644 index 0000000000..0c31d3acd3 --- /dev/null +++ b/engine/src/flutter/shell/config.gni @@ -0,0 +1,7 @@ +# Copyright 2015 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +declare_args() { + shell_enable_vulkan = false +} diff --git a/engine/src/flutter/shell/gpu/BUILD.gn b/engine/src/flutter/shell/gpu/BUILD.gn index c93cfa4bba..e3df23e6e8 100644 --- a/engine/src/flutter/shell/gpu/BUILD.gn +++ b/engine/src/flutter/shell/gpu/BUILD.gn @@ -2,16 +2,23 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +import("//flutter/shell/config.gni") + source_set("gpu") { sources = [ "gpu_rasterizer.cc", "gpu_rasterizer.h", "gpu_surface_gl.cc", "gpu_surface_gl.h", - "gpu_surface_vulkan.cc", - "gpu_surface_vulkan.h", ] + if (shell_enable_vulkan) { + sources += [ + "gpu_surface_vulkan.cc", + "gpu_surface_vulkan.h", + ] + } + deps = [ "//flutter/common", "//flutter/flow", @@ -22,4 +29,10 @@ source_set("gpu") { "//third_party/skia", "//third_party/skia:gpu", ] + + if (shell_enable_vulkan) { + deps += [ + "//flutter/vulkan", + ] + } } diff --git a/engine/src/flutter/shell/gpu/gpu_surface_gl.cc b/engine/src/flutter/shell/gpu/gpu_surface_gl.cc index 814b5296fb..d7c7801b4f 100644 --- a/engine/src/flutter/shell/gpu/gpu_surface_gl.cc +++ b/engine/src/flutter/shell/gpu/gpu_surface_gl.cc @@ -22,37 +22,6 @@ static const int kMaxGaneshResourceCacheCount = 2048; // GPU cache. static const size_t kMaxGaneshResourceCacheBytes = 96 * 1024 * 1024; -GPUSurfaceFrameGL::GPUSurfaceFrameGL(sk_sp surface, - SubmitCallback submit_callback) - : surface_(surface), submit_callback_(submit_callback) {} - -GPUSurfaceFrameGL::~GPUSurfaceFrameGL() { - if (submit_callback_) { - // Dropping without a Submit. Callback with nullptr so that the current - // context on the thread is cleared. - submit_callback_(nullptr); - } -} - -SkCanvas* GPUSurfaceFrameGL::SkiaCanvas() { - return surface_->getCanvas(); -} - -bool GPUSurfaceFrameGL::PerformSubmit() { - if (submit_callback_ == nullptr) { - return false; - } - - FLUTTER_THREAD_CHECKER_CHECK(checker_); - - if (submit_callback_(surface_->getCanvas())) { - surface_ = nullptr; - return true; - } - - return false; -} - GPUSurfaceGL::GPUSurfaceGL(GPUSurfaceGLDelegate* delegate) : delegate_(delegate), weak_factory_(this) {} @@ -91,6 +60,8 @@ bool GPUSurfaceGL::Setup() { context_->setResourceCacheLimits(kMaxGaneshResourceCacheCount, kMaxGaneshResourceCacheBytes); + delegate_->GLContextClearCurrent(); + return true; } @@ -103,6 +74,10 @@ std::unique_ptr GPUSurfaceGL::AcquireFrame(const SkISize& size) { return nullptr; } + if (!delegate_->GLContextMakeCurrent()) { + return nullptr; + } + sk_sp surface = AcquireSurface(size); if (surface == nullptr) { @@ -111,13 +86,11 @@ std::unique_ptr GPUSurfaceGL::AcquireFrame(const SkISize& size) { auto weak_this = weak_factory_.GetWeakPtr(); - GPUSurfaceFrameGL::SubmitCallback submit_callback = - [weak_this](SkCanvas* canvas) { - return weak_this ? weak_this->PresentSurface(canvas) : false; - }; + SurfaceFrame::SubmitCallback submit_callback = [weak_this](SkCanvas* canvas) { + return weak_this ? weak_this->PresentSurface(canvas) : false; + }; - return std::unique_ptr( - new GPUSurfaceFrameGL(surface, submit_callback)); + return std::make_unique(surface, submit_callback); } bool GPUSurfaceGL::PresentSurface(SkCanvas* canvas) { diff --git a/engine/src/flutter/shell/gpu/gpu_surface_gl.h b/engine/src/flutter/shell/gpu/gpu_surface_gl.h index a29d0ff487..3835cbcf6b 100644 --- a/engine/src/flutter/shell/gpu/gpu_surface_gl.h +++ b/engine/src/flutter/shell/gpu/gpu_surface_gl.h @@ -54,26 +54,6 @@ class GPUSurfaceGL : public Surface { FTL_DISALLOW_COPY_AND_ASSIGN(GPUSurfaceGL); }; -class GPUSurfaceFrameGL : public SurfaceFrame { - public: - using SubmitCallback = std::function; - - GPUSurfaceFrameGL(sk_sp surface, SubmitCallback submit_callback); - - ~GPUSurfaceFrameGL(); - - SkCanvas* SkiaCanvas() override; - - private: - FLUTTER_THREAD_CHECKER_DECLARE(checker_); - sk_sp surface_; - SubmitCallback submit_callback_; - - bool PerformSubmit() override; - - FTL_DISALLOW_COPY_AND_ASSIGN(GPUSurfaceFrameGL); -}; - } // namespace shell #endif // SHELL_GPU_GPU_SURFACE_GL_H_ diff --git a/engine/src/flutter/shell/gpu/gpu_surface_vulkan.cc b/engine/src/flutter/shell/gpu/gpu_surface_vulkan.cc index 1a295d19b8..9b1932f6e4 100644 --- a/engine/src/flutter/shell/gpu/gpu_surface_vulkan.cc +++ b/engine/src/flutter/shell/gpu/gpu_surface_vulkan.cc @@ -3,9 +3,51 @@ // found in the LICENSE file. #include "flutter/shell/gpu/gpu_surface_vulkan.h" +#include "lib/ftl/logging.h" namespace shell { -// +GPUSurfaceVulkan::GPUSurfaceVulkan( + ftl::RefPtr proc_table, + std::unique_ptr native_surface) + : window_(std::move(proc_table), std::move(native_surface)), + weak_factory_(this) {} + +GPUSurfaceVulkan::~GPUSurfaceVulkan() = default; + +bool GPUSurfaceVulkan::Setup() { + // This backend does not have an explicit setup task post initialization. + return window_.IsValid(); +} + +bool GPUSurfaceVulkan::IsValid() { + return window_.IsValid(); +} + +std::unique_ptr GPUSurfaceVulkan::AcquireFrame( + const SkISize& size) { + auto surface = window_.AcquireSurface(); + + if (surface == nullptr) { + return nullptr; + } + + return std::make_unique( + std::move(surface), + [weak_this = weak_factory_.GetWeakPtr()](SkCanvas * canvas)->bool { + // Frames are only ever acquired on the GPU thread. This is also the + // thread on which the weak pointer factory is collected (as this + // instance is owned by the rasterizer). So this use of weak pointers is + // safe. + if (canvas == nullptr || !weak_this) { + return false; + } + return weak_this->window_.SwapBuffers(); + }); +} + +GrContext* GPUSurfaceVulkan::GetContext() { + return window_.GetSkiaGrContext(); +} } // namespace shell diff --git a/engine/src/flutter/shell/gpu/gpu_surface_vulkan.h b/engine/src/flutter/shell/gpu/gpu_surface_vulkan.h index d7cf57167e..8637e0fe60 100644 --- a/engine/src/flutter/shell/gpu/gpu_surface_vulkan.h +++ b/engine/src/flutter/shell/gpu/gpu_surface_vulkan.h @@ -5,11 +5,36 @@ #ifndef SHELL_GPU_GPU_SURFACE_VULKAN_H_ #define SHELL_GPU_GPU_SURFACE_VULKAN_H_ +#include +#include "flutter/shell/common/surface.h" +#include "flutter/vulkan/vulkan_native_surface.h" +#include "flutter/vulkan/vulkan_window.h" #include "lib/ftl/macros.h" +#include "lib/ftl/memory/weak_ptr.h" namespace shell { -// +class GPUSurfaceVulkan : public Surface { + public: + GPUSurfaceVulkan(ftl::RefPtr proc_table, + std::unique_ptr native_surface); + + ~GPUSurfaceVulkan() override; + + bool Setup() override; + + bool IsValid() override; + + std::unique_ptr AcquireFrame(const SkISize& size) override; + + GrContext* GetContext() override; + + private: + vulkan::VulkanWindow window_; + ftl::WeakPtrFactory weak_factory_; + + FTL_DISALLOW_COPY_AND_ASSIGN(GPUSurfaceVulkan); +}; } // namespace shell diff --git a/engine/src/flutter/shell/platform/android/BUILD.gn b/engine/src/flutter/shell/platform/android/BUILD.gn index bc0ae0708d..aed01d9bbf 100644 --- a/engine/src/flutter/shell/platform/android/BUILD.gn +++ b/engine/src/flutter/shell/platform/android/BUILD.gn @@ -2,6 +2,7 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +import("//flutter/shell/config.gni") import("//build/config/android/config.gni") import("//build/config/android/rules.gni") @@ -26,6 +27,8 @@ shared_library("sky_shell") { "android_environment_gl.h", "android_native_window.cc", "android_native_window.h", + "android_surface.cc", + "android_surface.h", "android_surface_gl.cc", "android_surface_gl.h", "flutter_main.cc", @@ -48,11 +51,23 @@ shared_library("sky_shell") { "//flutter/runtime", "//flutter/shell/common", "//flutter/shell/gpu", - "//flutter/vulkan", "//lib/ftl", "//third_party/skia", ] + defines = [] + + if (shell_enable_vulkan) { + sources += [ + "android_surface_vulkan.cc", + "android_surface_vulkan.h", + ] + + deps += [ "//flutter/vulkan" ] + + defines += [ "SHELL_ENABLE_VULKAN" ] + } + ldflags = [ "-landroid", "-lEGL", diff --git a/engine/src/flutter/shell/platform/android/android_context_gl.cc b/engine/src/flutter/shell/platform/android/android_context_gl.cc index f7364eecc6..9ae9dfb8e2 100644 --- a/engine/src/flutter/shell/platform/android/android_context_gl.cc +++ b/engine/src/flutter/shell/platform/android/android_context_gl.cc @@ -134,20 +134,21 @@ static EGLResult CreatePBufferSurface(EGLDisplay display, return {surface != EGL_NO_SURFACE, surface}; } -static EGLResult CreateSurface(EGLDisplay display, - EGLConfig config, - const AndroidNativeWindow& window) { - return window.IsValid() - ? CreateWindowSurface(display, config, window.handle()) +static EGLResult CreateSurface( + EGLDisplay display, + EGLConfig config, + ftl::RefPtr window) { + return window && window->IsValid() + ? CreateWindowSurface(display, config, window->handle()) : CreatePBufferSurface(display, config); } AndroidContextGL::AndroidContextGL(ftl::RefPtr env, - AndroidNativeWindow window, + ftl::RefPtr window, PlatformView::SurfaceConfig config, const AndroidContextGL* share_context) : environment_(env), - window_(std::move(window)), + window_(window), config_(nullptr), surface_(EGL_NO_SURFACE), context_(EGL_NO_CONTEXT), @@ -199,10 +200,7 @@ AndroidContextGL::AndroidContextGL(ftl::RefPtr env, AndroidContextGL::AndroidContextGL(ftl::RefPtr env, PlatformView::SurfaceConfig config, const AndroidContextGL* share_context) - : AndroidContextGL(env, - AndroidNativeWindow{nullptr}, - config, - share_context) {} + : AndroidContextGL(env, nullptr, config, share_context) {} AndroidContextGL::~AndroidContextGL() { if (!TeardownContext(environment_->Display(), context_)) { diff --git a/engine/src/flutter/shell/platform/android/android_context_gl.h b/engine/src/flutter/shell/platform/android/android_context_gl.h index 5078031ae9..aa2a081a51 100644 --- a/engine/src/flutter/shell/platform/android/android_context_gl.h +++ b/engine/src/flutter/shell/platform/android/android_context_gl.h @@ -16,23 +16,6 @@ namespace shell { class AndroidContextGL : public ftl::RefCountedThreadSafe { - private: - /// Creates a window surface context tied to the window handle for on-screen - /// rendering. - // MakeRefCounted - AndroidContextGL(ftl::RefPtr env, - AndroidNativeWindow window, - PlatformView::SurfaceConfig config, - const AndroidContextGL* share_context = nullptr); - - /// Creates a pbuffer surface context for offscreen rendering. - // MakeRefCounted - AndroidContextGL(ftl::RefPtr env, - PlatformView::SurfaceConfig config, - const AndroidContextGL* share_context = nullptr); - - ~AndroidContextGL(); - public: ftl::RefPtr Environment() const; @@ -50,12 +33,26 @@ class AndroidContextGL : public ftl::RefCountedThreadSafe { private: ftl::RefPtr environment_; - AndroidNativeWindow window_; + ftl::RefPtr window_; EGLConfig config_; EGLSurface surface_; EGLContext context_; bool valid_; + /// Creates a window surface context tied to the window handle for on-screen + /// rendering. + AndroidContextGL(ftl::RefPtr env, + ftl::RefPtr window, + PlatformView::SurfaceConfig config, + const AndroidContextGL* share_context = nullptr); + + /// Creates a pbuffer surface context for offscreen rendering. + AndroidContextGL(ftl::RefPtr env, + PlatformView::SurfaceConfig config, + const AndroidContextGL* share_context = nullptr); + + ~AndroidContextGL(); + FRIEND_MAKE_REF_COUNTED(AndroidContextGL); FRIEND_REF_COUNTED_THREAD_SAFE(AndroidContextGL); FTL_DISALLOW_COPY_AND_ASSIGN(AndroidContextGL); diff --git a/engine/src/flutter/shell/platform/android/android_native_window.cc b/engine/src/flutter/shell/platform/android/android_native_window.cc index 419ae132a2..d84e078857 100644 --- a/engine/src/flutter/shell/platform/android/android_native_window.cc +++ b/engine/src/flutter/shell/platform/android/android_native_window.cc @@ -6,16 +6,7 @@ namespace shell { -AndroidNativeWindow::AndroidNativeWindow(Handle window) : window_(window) { - if (window_ != nullptr) { - ANativeWindow_acquire(window_); - } -} - -AndroidNativeWindow::AndroidNativeWindow(AndroidNativeWindow&& o) - : window_(o.window_) { - o.window_ = nullptr; -} +AndroidNativeWindow::AndroidNativeWindow(Handle window) : window_(window) {} AndroidNativeWindow::~AndroidNativeWindow() { if (window_ != nullptr) { @@ -32,4 +23,10 @@ AndroidNativeWindow::Handle AndroidNativeWindow::handle() const { return window_; } +SkISize AndroidNativeWindow::GetSize() const { + return window_ == nullptr ? SkISize::Make(0, 0) + : SkISize::Make(ANativeWindow_getWidth(window_), + ANativeWindow_getHeight(window_)); +} + } // namespace shell diff --git a/engine/src/flutter/shell/platform/android/android_native_window.h b/engine/src/flutter/shell/platform/android/android_native_window.h index 3023cc7347..8b3b4adf20 100644 --- a/engine/src/flutter/shell/platform/android/android_native_window.h +++ b/engine/src/flutter/shell/platform/android/android_native_window.h @@ -7,26 +7,34 @@ #include #include "lib/ftl/macros.h" +#include "lib/ftl/memory/ref_counted.h" +#include "lib/ftl/memory/ref_ptr.h" +#include "third_party/skia/include/core/SkSize.h" namespace shell { -class AndroidNativeWindow { +class AndroidNativeWindow + : public ftl::RefCountedThreadSafe { public: using Handle = ANativeWindow*; - AndroidNativeWindow(Handle window); - - AndroidNativeWindow(AndroidNativeWindow&& other); - - ~AndroidNativeWindow(); - bool IsValid() const; Handle handle() const; + SkISize GetSize() const; + private: Handle window_; + /// Creates a native window with the given handle. Handle ownership is assumed + /// by this instance of the native window. + explicit AndroidNativeWindow(Handle window); + + ~AndroidNativeWindow(); + + FRIEND_MAKE_REF_COUNTED(AndroidNativeWindow); + FRIEND_REF_COUNTED_THREAD_SAFE(AndroidNativeWindow); FTL_DISALLOW_COPY_AND_ASSIGN(AndroidNativeWindow); }; diff --git a/engine/src/flutter/shell/platform/android/android_surface.cc b/engine/src/flutter/shell/platform/android/android_surface.cc new file mode 100644 index 0000000000..4dd08609da --- /dev/null +++ b/engine/src/flutter/shell/platform/android/android_surface.cc @@ -0,0 +1,11 @@ +// Copyright 2016 The Chromium 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 "flutter/shell/platform/android/android_surface.h" + +namespace shell { + +AndroidSurface::~AndroidSurface() = default; + +} // namespace shell diff --git a/engine/src/flutter/shell/platform/android/android_surface.h b/engine/src/flutter/shell/platform/android/android_surface.h new file mode 100644 index 0000000000..770a22a327 --- /dev/null +++ b/engine/src/flutter/shell/platform/android/android_surface.h @@ -0,0 +1,39 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_SURFACE_H_ +#define FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_SURFACE_H_ + +#include +#include "flutter/shell/common/platform_view.h" +#include "flutter/shell/common/surface.h" +#include "flutter/shell/platform/android/android_native_window.h" +#include "lib/ftl/macros.h" +#include "third_party/skia/include/core/SkSize.h" + +namespace shell { + +class AndroidSurface { + public: + virtual ~AndroidSurface(); + + virtual bool IsValid() const = 0; + + virtual void TeardownOnScreenContext() = 0; + + virtual std::unique_ptr CreateGPUSurface() = 0; + + virtual SkISize OnScreenSurfaceSize() const = 0; + + virtual bool OnScreenSurfaceResize(const SkISize& size) const = 0; + + virtual bool ResourceContextMakeCurrent() = 0; + + virtual bool SetNativeWindow(ftl::RefPtr window, + PlatformView::SurfaceConfig config = {}) = 0; +}; + +} // namespace shell + +#endif // FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_SURFACE_H_ diff --git a/engine/src/flutter/shell/platform/android/android_surface_gl.cc b/engine/src/flutter/shell/platform/android/android_surface_gl.cc index b5a7677b33..0df1516852 100644 --- a/engine/src/flutter/shell/platform/android/android_surface_gl.cc +++ b/engine/src/flutter/shell/platform/android/android_surface_gl.cc @@ -3,7 +3,10 @@ // found in the LICENSE file. #include "flutter/shell/platform/android/android_surface_gl.h" + #include + +#include "flutter/common/threads.h" #include "lib/ftl/logging.h" #include "lib/ftl/memory/ref_ptr.h" @@ -46,40 +49,25 @@ AndroidSurfaceGL::AndroidSurfaceGL( offscreen_context_ = GlobalResourceLoadingContext(offscreen_config); if (!offscreen_context_ || !offscreen_context_->IsValid()) { - FTL_LOG(ERROR) << "Unable to create an offscreen EGL context"; - FTL_LOG(ERROR) << "If you are running in an Android emulator, make sure that OpenGL is enabled"; offscreen_context_ = nullptr; } } AndroidSurfaceGL::~AndroidSurfaceGL() = default; -bool AndroidSurfaceGL::SetNativeWindowForOnScreenContext( - AndroidNativeWindow window, - PlatformView::SurfaceConfig onscreen_config) { - // In any case, we want to get rid of our current onscreen context. - onscreen_context_ = nullptr; - - // If the offscreen context has not been setup, we dont have the sharegroup. - // So bail. - if (!offscreen_context_ || !offscreen_context_->IsValid()) { - return false; - } - - // Create the onscreen context. - onscreen_context_ = ftl::MakeRefCounted( - offscreen_context_->Environment(), std::move(window), onscreen_config, - offscreen_context_.get() /* sharegroup */); - - if (!onscreen_context_->IsValid()) { - onscreen_context_ = nullptr; - return false; - } - - return true; +bool AndroidSurfaceGL::IsOffscreenContextValid() const { + return offscreen_context_ && offscreen_context_->IsValid(); } void AndroidSurfaceGL::TeardownOnScreenContext() { + ftl::AutoResetWaitableEvent latch; + blink::Threads::Gpu()->PostTask([this, &latch]() { + if (IsValid()) { + GLContextClearCurrent(); + } + latch.Signal(); + }); + latch.Wait(); onscreen_context_ = nullptr; } @@ -91,6 +79,16 @@ bool AndroidSurfaceGL::IsValid() const { return onscreen_context_->IsValid() && offscreen_context_->IsValid(); } +std::unique_ptr AndroidSurfaceGL::CreateGPUSurface() { + auto surface = std::make_unique(this); + + if (!surface->Setup()) { + return nullptr; + } + + return surface; +} + SkISize AndroidSurfaceGL::OnScreenSurfaceSize() const { FTL_DCHECK(onscreen_context_ && onscreen_context_->IsValid()); return onscreen_context_->GetSize(); @@ -101,11 +99,35 @@ bool AndroidSurfaceGL::OnScreenSurfaceResize(const SkISize& size) const { return onscreen_context_->Resize(size); } -bool AndroidSurfaceGL::GLOffscreenContextMakeCurrent() { +bool AndroidSurfaceGL::ResourceContextMakeCurrent() { FTL_DCHECK(offscreen_context_ && offscreen_context_->IsValid()); return offscreen_context_->MakeCurrent(); } +bool AndroidSurfaceGL::SetNativeWindow(ftl::RefPtr window, + PlatformView::SurfaceConfig config) { + // In any case, we want to get rid of our current onscreen context. + onscreen_context_ = nullptr; + + // If the offscreen context has not been setup, we dont have the sharegroup. + // So bail. + if (!offscreen_context_ || !offscreen_context_->IsValid()) { + return false; + } + + // Create the onscreen context. + onscreen_context_ = ftl::MakeRefCounted( + offscreen_context_->Environment(), std::move(window), config, + offscreen_context_.get() /* sharegroup */); + + if (!onscreen_context_->IsValid()) { + onscreen_context_ = nullptr; + return false; + } + + return true; +} + bool AndroidSurfaceGL::GLContextMakeCurrent() { FTL_DCHECK(onscreen_context_ && onscreen_context_->IsValid()); return onscreen_context_->MakeCurrent(); diff --git a/engine/src/flutter/shell/platform/android/android_surface_gl.h b/engine/src/flutter/shell/platform/android/android_surface_gl.h index c349582462..9dd1e174b4 100644 --- a/engine/src/flutter/shell/platform/android/android_surface_gl.h +++ b/engine/src/flutter/shell/platform/android/android_surface_gl.h @@ -6,33 +6,37 @@ #define FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_SURFACE_GL_H_ #include + #include "flutter/shell/gpu/gpu_surface_gl.h" #include "flutter/shell/platform/android/android_context_gl.h" #include "flutter/shell/platform/android/android_environment_gl.h" -#include "flutter/shell/platform/android/android_native_window.h" +#include "flutter/shell/platform/android/android_surface.h" #include "lib/ftl/macros.h" namespace shell { -class AndroidSurfaceGL : public GPUSurfaceGLDelegate { +class AndroidSurfaceGL : public GPUSurfaceGLDelegate, public AndroidSurface { public: explicit AndroidSurfaceGL(PlatformView::SurfaceConfig offscreen_config); - ~AndroidSurfaceGL(); - - bool SetNativeWindowForOnScreenContext( - AndroidNativeWindow window, - PlatformView::SurfaceConfig onscreen_config); - - void TeardownOnScreenContext(); + ~AndroidSurfaceGL() override; bool IsValid() const; - SkISize OnScreenSurfaceSize() const; + bool IsOffscreenContextValid() const; - bool OnScreenSurfaceResize(const SkISize& size) const; + std::unique_ptr CreateGPUSurface() override; - bool GLOffscreenContextMakeCurrent(); + void TeardownOnScreenContext() override; + + SkISize OnScreenSurfaceSize() const override; + + bool OnScreenSurfaceResize(const SkISize& size) const override; + + bool ResourceContextMakeCurrent() override; + + bool SetNativeWindow(ftl::RefPtr window, + PlatformView::SurfaceConfig config) override; bool GLContextMakeCurrent() override; diff --git a/engine/src/flutter/shell/platform/android/android_surface_vulkan.cc b/engine/src/flutter/shell/platform/android/android_surface_vulkan.cc new file mode 100644 index 0000000000..ad2b297c3a --- /dev/null +++ b/engine/src/flutter/shell/platform/android/android_surface_vulkan.cc @@ -0,0 +1,78 @@ +// Copyright 2016 The Chromium 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 "flutter/shell/platform/android/android_surface_vulkan.h" + +#include + +#include "flutter/shell/gpu/gpu_surface_vulkan.h" +#include "flutter/vulkan/vulkan_native_surface_android.h" +#include "lib/ftl/logging.h" + +namespace shell { + +AndroidSurfaceVulkan::AndroidSurfaceVulkan() + : proc_table_(ftl::MakeRefCounted()) {} + +AndroidSurfaceVulkan::~AndroidSurfaceVulkan() = default; + +bool AndroidSurfaceVulkan::IsValid() const { + return proc_table_->HasAcquiredMandatoryProcAddresses(); +} + +void AndroidSurfaceVulkan::TeardownOnScreenContext() { + // +} + +std::unique_ptr AndroidSurfaceVulkan::CreateGPUSurface() { + if (!IsValid()) { + return nullptr; + } + + if (!native_window_ || !native_window_->IsValid()) { + return nullptr; + } + + auto vulkan_surface_android = + std::make_unique( + native_window_->handle()); + + if (!vulkan_surface_android->IsValid()) { + return nullptr; + } + + auto gpu_surface = std::make_unique( + proc_table_, std::move(vulkan_surface_android)); + + if (!gpu_surface->IsValid()) { + return nullptr; + } + + if (!gpu_surface->Setup()) { + return nullptr; + } + + return gpu_surface; +} + +SkISize AndroidSurfaceVulkan::OnScreenSurfaceSize() const { + return native_window_ ? native_window_->GetSize() : SkISize::Make(0, 0); +} + +bool AndroidSurfaceVulkan::OnScreenSurfaceResize(const SkISize& size) const { + return true; +} + +bool AndroidSurfaceVulkan::ResourceContextMakeCurrent() { + return false; +} + +bool AndroidSurfaceVulkan::SetNativeWindow( + ftl::RefPtr window, + PlatformView::SurfaceConfig config) { + native_window_ = std::move(window); + return native_window_ && native_window_->IsValid(); +} + +} // namespace shell diff --git a/engine/src/flutter/shell/platform/android/android_surface_vulkan.h b/engine/src/flutter/shell/platform/android/android_surface_vulkan.h new file mode 100644 index 0000000000..c041b63485 --- /dev/null +++ b/engine/src/flutter/shell/platform/android/android_surface_vulkan.h @@ -0,0 +1,46 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_SURFACE_VULKAN_H_ +#define FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_SURFACE_VULKAN_H_ + +#include +#include "flutter/shell/platform/android/android_native_window.h" +#include "flutter/shell/platform/android/android_surface.h" +#include "flutter/vulkan/vulkan_window.h" +#include "lib/ftl/macros.h" + +namespace shell { + +class AndroidSurfaceVulkan : public AndroidSurface { + public: + AndroidSurfaceVulkan(); + + ~AndroidSurfaceVulkan() override; + + bool IsValid() const override; + + void TeardownOnScreenContext() override; + + std::unique_ptr CreateGPUSurface() override; + + SkISize OnScreenSurfaceSize() const override; + + bool OnScreenSurfaceResize(const SkISize& size) const override; + + bool ResourceContextMakeCurrent() override; + + bool SetNativeWindow(ftl::RefPtr window, + PlatformView::SurfaceConfig config) override; + + private: + ftl::RefPtr proc_table_; + ftl::RefPtr native_window_; + + FTL_DISALLOW_COPY_AND_ASSIGN(AndroidSurfaceVulkan); +}; + +} // namespace shell + +#endif // FLUTTER_SHELL_PLATFORM_ANDROID_ANDROID_SURFACE_VULKAN_H_ diff --git a/engine/src/flutter/shell/platform/android/platform_view_android.cc b/engine/src/flutter/shell/platform/android/platform_view_android.cc index 120421bd45..00bcdbd29f 100644 --- a/engine/src/flutter/shell/platform/android/platform_view_android.cc +++ b/engine/src/flutter/shell/platform/android/platform_view_android.cc @@ -4,33 +4,28 @@ #include "flutter/shell/platform/android/platform_view_android.h" -#include #include #include #include #include -#include -#include + #include -#include "base/android/jni_android.h" + #include "base/android/jni_array.h" #include "base/android/jni_string.h" -#include "base/bind.h" -#include "base/location.h" -#include "base/trace_event/trace_event.h" #include "flutter/common/threads.h" -#include "flutter/flow/compositor_context.h" #include "flutter/runtime/dart_service_isolate.h" -#include "flutter/shell/common/engine.h" -#include "flutter/shell/common/shell.h" #include "flutter/shell/gpu/gpu_rasterizer.h" +#include "flutter/shell/platform/android/android_surface_gl.h" #include "flutter/shell/platform/android/vsync_waiter_android.h" #include "jni/FlutterView_jni.h" #include "lib/ftl/functional/make_copyable.h" -#include "third_party/skia/include/core/SkSurface.h" + +#if SHELL_ENABLE_VULKAN +#include "flutter/shell/platform/android/android_surface_vulkan.h" +#endif // SHELL_ENABLE_VULKAN namespace shell { -namespace { class PlatformMessageResponseAndroid : public blink::PlatformMessageResponse { FRIEND_MAKE_REF_COUNTED(PlatformMessageResponseAndroid); @@ -59,18 +54,56 @@ class PlatformMessageResponseAndroid : public blink::PlatformMessageResponse { ftl::WeakPtr view_; }; -} // namespace +static std::unique_ptr InitializePlatformSurfaceGL() { + const PlatformView::SurfaceConfig offscreen_config = { + .red_bits = 8, + .green_bits = 8, + .blue_bits = 8, + .alpha_bits = 8, + .depth_bits = 0, + .stencil_bits = 0, + }; + auto surface = std::make_unique(offscreen_config); + return surface->IsOffscreenContextValid() ? std::move(surface) : nullptr; +} + +static std::unique_ptr InitializePlatformSurfaceVulkan() { +#if SHELL_ENABLE_VULKAN + auto surface = std::make_unique(); + return surface->IsValid() ? std::move(surface) : nullptr; +#else // SHELL_ENABLE_VULKAN + return nullptr; +#endif // SHELL_ENABLE_VULKAN +} + +static std::unique_ptr InitializePlatformSurface() { + if (auto surface = InitializePlatformSurfaceVulkan()) { + FTL_DLOG(INFO) << "Vulkan surface initialized."; + return surface; + } + + FTL_DLOG(INFO) + << "Could not initialize Vulkan surface. Falling back to OpenGL."; + + if (auto surface = InitializePlatformSurfaceGL()) { + FTL_DLOG(INFO) << "GL surface initialized."; + return surface; + } + + FTL_CHECK(false) << "Could not initialize either the Vulkan or OpenGL " + "surface backends. Flutter requires a GPU to render."; + return nullptr; +} PlatformViewAndroid::PlatformViewAndroid() - : PlatformView(std::make_unique(nullptr)) { + : PlatformView(std::make_unique(nullptr)), + android_surface_(InitializePlatformSurface()) { CreateEngine(); - // Create the GL surface so that we can setup the resource context. - PlatformView::SurfaceConfig offscreen_config; - offscreen_config.stencil_bits = 0; - surface_gl_ = std::make_unique(offscreen_config); - + // Eagerly setup the IO thread context. We have already setup the surface. SetupResourceContextOnIOThread(); + + UpdateThreadPriorities(); } PlatformViewAndroid::~PlatformViewAndroid() = default; @@ -88,43 +121,37 @@ void PlatformViewAndroid::SurfaceCreated(JNIEnv* env, // ANativeWindow_fromSurface are released immediately. This is needed as a // workaround for https://code.google.com/p/android/issues/detail?id=68174 base::android::ScopedJavaLocalFrame scoped_local_reference_frame(env); - ANativeWindow* window = ANativeWindow_fromSurface(env, jsurface); - // Use the default onscreen configuration. - PlatformView::SurfaceConfig onscreen_config; + auto native_window = ftl::MakeRefCounted( + ANativeWindow_fromSurface(env, jsurface)); - if (!surface_gl_->SetNativeWindowForOnScreenContext(window, - onscreen_config)) { - LOG(INFO) << "Could not create the OpenGL Android Surface."; - } - - ANativeWindow_release(window); - - if (!surface_gl_->IsValid()) { + if (!native_window->IsValid()) { return; } - NotifyCreated( - std::make_unique(surface_gl_.get()), // GPU surface - [this, backgroundColor] { - if (surface_gl_) - rasterizer().Clear(backgroundColor, - surface_gl_->OnScreenSurfaceSize()); - }); + if (!android_surface_->SetNativeWindow(native_window)) { + return; + } - UpdateThreadPriorities(); + std::unique_ptr gpu_surface = android_surface_->CreateGPUSurface(); + + if (gpu_surface == nullptr || !gpu_surface->IsValid()) { + return; + } + + NotifyCreated(std::move(gpu_surface), [ + this, backgroundColor, native_window_size = native_window->GetSize() + ] { rasterizer().Clear(backgroundColor, native_window_size); }); } void PlatformViewAndroid::SurfaceChanged(JNIEnv* env, jobject obj, jint width, jint height) { - if (!surface_gl_) { - return; - } - blink::Threads::Gpu()->PostTask([this, width, height]() { - surface_gl_->OnScreenSurfaceResize(SkISize::Make(width, height)); + if (android_surface_) { + android_surface_->OnScreenSurfaceResize(SkISize::Make(width, height)); + } }); } @@ -319,16 +346,7 @@ void PlatformViewAndroid::SetSemanticsEnabled(JNIEnv* env, void PlatformViewAndroid::ReleaseSurface() { NotifyDestroyed(); - - ftl::AutoResetWaitableEvent latch; - blink::Threads::Gpu()->PostTask([this, &latch]() { - if (surface_gl_->IsValid()) - surface_gl_->GLContextClearCurrent(); - latch.Signal(); - }); - latch.Wait(); - - surface_gl_->TeardownOnScreenContext(); + android_surface_->TeardownOnScreenContext(); } VsyncWaiter* PlatformViewAndroid::GetVsyncWaiter() { @@ -338,7 +356,7 @@ VsyncWaiter* PlatformViewAndroid::GetVsyncWaiter() { } bool PlatformViewAndroid::ResourceContextMakeCurrent() { - return surface_gl_ ? surface_gl_->GLOffscreenContextMakeCurrent() : false; + return android_surface_->ResourceContextMakeCurrent(); } void PlatformViewAndroid::UpdateSemantics( diff --git a/engine/src/flutter/shell/platform/android/platform_view_android.h b/engine/src/flutter/shell/platform/android/platform_view_android.h index e7aa202d80..03b7f1c274 100644 --- a/engine/src/flutter/shell/platform/android/platform_view_android.h +++ b/engine/src/flutter/shell/platform/android/platform_view_android.h @@ -8,12 +8,14 @@ #include #include #include +#include #include "base/android/jni_android.h" #include "base/android/jni_weak_ref.h" #include "flutter/lib/ui/window/platform_message.h" #include "flutter/shell/common/platform_view.h" -#include "flutter/shell/platform/android/android_surface_gl.h" +#include "flutter/shell/platform/android/android_native_window.h" +#include "flutter/shell/platform/android/android_surface.h" #include "lib/ftl/memory/weak_ptr.h" namespace shell { @@ -102,9 +104,8 @@ class PlatformViewAndroid : public PlatformView { } private: - std::unique_ptr surface_gl_; + const std::unique_ptr android_surface_; JavaObjectWeakGlobalRef flutter_view_; - // We use id 0 to mean that no response is expected. int next_response_id_ = 1; std::unordered_map> diff --git a/engine/src/flutter/sky/packages/sky_engine/LICENSE b/engine/src/flutter/sky/packages/sky_engine/LICENSE index 0caf98bd75..e7e582d7b5 100644 --- a/engine/src/flutter/sky/packages/sky_engine/LICENSE +++ b/engine/src/flutter/sky/packages/sky_engine/LICENSE @@ -1019,193 +1019,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -------------------------------------------------------------------------------- boringssl -BoringSSL is a fork of OpenSSL. As such, large parts of it fall under OpenSSL -licensing. Files that are completely new have a Google copyright and an ISC -license. This license is reproduced at the bottom of this file. - -Contributors to BoringSSL are required to follow the CLA rules for Chromium: -https://cla.developers.google.com/clas - -Some files from Intel are under yet another license, which is also included -underneath. - -The OpenSSL toolkit stays under a dual license, i.e. both the conditions of the -OpenSSL License and the original SSLeay license apply to the toolkit. See below -for the actual license texts. Actually both licenses are BSD-style Open Source -licenses. In case of any license issues related to OpenSSL please contact -openssl-core@openssl.org. - -The following are Google-internal bug numbers where explicit permission from -some authors is recorded for use of their work. (This is purely for our own -record keeping.) - 27287199 - 27287880 - 27287883 - - OpenSSL License - -/* ==================================================================== - * Copyright (c) 1998-2011 The OpenSSL Project. All rights reserved. - - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - - * 3. All advertising materials mentioning features or use of this - * software must display the following acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" - - * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to - * endorse or promote products derived from this software without - * prior written permission. For written permission, please contact - * openssl-core@openssl.org. - - * 5. Products derived from this software may not be called "OpenSSL" - * nor may "OpenSSL" appear in their names without prior written - * permission of the OpenSSL Project. - - * 6. Redistributions of any form whatsoever must retain the following - * acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit (http://www.openssl.org/)" - - * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY - * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR - * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, - * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED - * OF THE POSSIBILITY OF SUCH DAMAGE. - * ==================================================================== - - * This product includes cryptographic software written by Eric Young - * (eay@cryptsoft.com). This product includes software written by Tim - * Hudson (tjh@cryptsoft.com). - - Original SSLeay License - -/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) - * All rights reserved. - - * This package is an SSL implementation written - * by Eric Young (eay@cryptsoft.com). - * The implementation was written so as to conform with Netscapes SSL. - - * This library is free for commercial and non-commercial use as long as - * the following conditions are aheared to. The following conditions - * apply to all code found in this distribution, be it the RC4, RSA, - * lhash, DES, etc., code; not just the SSL code. The SSL documentation - * included with this distribution is covered by the same copyright terms - * except that the holder is Tim Hudson (tjh@cryptsoft.com). - - * Copyright remains Eric Young's, and as such any Copyright notices in - * the code are not to be removed. - * If this package is used in a product, Eric Young should be given attribution - * as the author of the parts of the library used. - * This can be in the form of a textual message at program startup or - * in documentation (online or textual) provided with the package. - - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * "This product includes cryptographic software written by - * Eric Young (eay@cryptsoft.com)" - * The word 'cryptographic' can be left out if the rouines from the library - * being used are not cryptographic related :-). - * 4. If you include any Windows specific code (or a derivative thereof) from - * the apps directory (application code) you must include an acknowledgement: - * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" - - * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - - * The licence and distribution terms for any publically available version or - * derivative of this code cannot be changed. i.e. this code cannot simply be - * copied and put under another distribution licence - * [including the GNU Public Licence.] - -ISC license used for completely new code in BoringSSL: - -/* Copyright (c) 2015, Google Inc. - - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -Some files from Intel carry the following license: - -# Copyright (c) 2012, Intel Corporation - -# All rights reserved. - -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: - -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. - -# * Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the -# distribution. - -# * Neither the name of the Intel Corporation nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. - -# THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION ""AS IS"" AND ANY -# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL INTEL CORPORATION OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------------- -boringssl - Copyright (C) 1995-1997 Eric Young (eay@cryptsoft.com) All rights reserved. @@ -3357,6 +3170,170 @@ SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR OTHERWISE. -------------------------------------------------------------------------------- +boringssl + +OpenSSL License + + ==================================================================== + Copyright (c) 1998-2011 The OpenSSL Project. All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + + 3. All advertising materials mentioning features or use of this + software must display the following acknowledgment: + "This product includes software developed by the OpenSSL Project + for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + + 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + endorse or promote products derived from this software without + prior written permission. For written permission, please contact + openssl-core@openssl.org. + + 5. Products derived from this software may not be called "OpenSSL" + nor may "OpenSSL" appear in their names without prior written + permission of the OpenSSL Project. + + 6. Redistributions of any form whatsoever must retain the following + acknowledgment: + "This product includes software developed by the OpenSSL Project + for use in the OpenSSL Toolkit (http://www.openssl.org/)" + + THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + OF THE POSSIBILITY OF SUCH DAMAGE. + ==================================================================== + + This product includes cryptographic software written by Eric Young + (eay@cryptsoft.com). This product includes software written by Tim + Hudson (tjh@cryptsoft.com). + +Original SSLeay License + +* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) +* All rights reserved. + +* This package is an SSL implementation written +* by Eric Young (eay@cryptsoft.com). +* The implementation was written so as to conform with Netscapes SSL. + +* This library is free for commercial and non-commercial use as long as +* the following conditions are aheared to. The following conditions +* apply to all code found in this distribution, be it the RC4, RSA, +* lhash, DES, etc., code; not just the SSL code. The SSL documentation +* included with this distribution is covered by the same copyright terms +* except that the holder is Tim Hudson (tjh@cryptsoft.com). + +* Copyright remains Eric Young's, and as such any Copyright notices in +* the code are not to be removed. +* If this package is used in a product, Eric Young should be given attribution +* as the author of the parts of the library used. +* This can be in the form of a textual message at program startup or +* in documentation (online or textual) provided with the package. + +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions +* are met: +* 1. Redistributions of source code must retain the copyright +* notice, this list of conditions and the following disclaimer. +* 2. Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* 3. All advertising materials mentioning features or use of this software +* must display the following acknowledgement: +* "This product includes cryptographic software written by +* Eric Young (eay@cryptsoft.com)" +* The word 'cryptographic' can be left out if the rouines from the library +* being used are not cryptographic related :-). +* 4. If you include any Windows specific code (or a derivative thereof) from +* the apps directory (application code) you must include an acknowledgement: +* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + +* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND +* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE +* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +* SUCH DAMAGE. + +* The licence and distribution terms for any publically available version or +* derivative of this code cannot be changed. i.e. this code cannot simply be +* copied and put under another distribution licence +* [including the GNU Public Licence.] + +ISC license used for completely new code in BoringSSL: + +/* Copyright (c) 2015, Google Inc. + + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY + * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION + * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +Some files from Intel carry the following license: + +# Copyright (c) 2012, Intel Corporation + +# All rights reserved. + +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: + +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. + +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the +# distribution. + +# * Neither the name of the Intel Corporation nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. + +# THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION ""AS IS"" AND ANY +# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL INTEL CORPORATION OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +-------------------------------------------------------------------------------- colorama Copyright (c) 2010 Jonathan Hartley @@ -9042,6 +9019,36 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -------------------------------------------------------------------------------- engine +Copyright 2017 The Chromium Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +-------------------------------------------------------------------------------- +engine + GNU LIBRARY GENERAL PUBLIC LICENSE Version 2, June 1991 diff --git a/engine/src/flutter/tools/gn b/engine/src/flutter/tools/gn index c3503c3e30..1fabaadbee 100755 --- a/engine/src/flutter/tools/gn +++ b/engine/src/flutter/tools/gn @@ -44,6 +44,9 @@ def to_gn_args(args): if args.runtime_mode != 'debug': raise Exception('iOS simulator only supports the debug runtime mode') + if args.target_os != 'android' and args.enable_vulkan: + raise Exception('--enable-vulkan is only supported on Android') + gn_args = {} # Skia GN args. @@ -66,7 +69,6 @@ def to_gn_args(args): gn_args['ios_deployment_target'] = '7.0' gn_args['use_ios_simulator'] = args.simulator if not args.simulator: - # Always use AOT on iOS devices until the interpreter stabilizes aot = True else: gn_args['use_system_harfbuzz'] = False @@ -117,6 +119,14 @@ def to_gn_args(args): gn_args['use_glfw'] = args.use_glfw + if args.enable_vulkan: + # Enable vulkan in the Flutter shell. + gn_args['shell_enable_vulkan'] = True + # Configure Skia for Vulkan support. + gn_args['skia_use_vulkan'] = True + gn_args['skia_link_with_vulkan'] = False + gn_args['skia_vulkan_headers_path'] = '//third_party/vulkan/src' + return gn_args def parse_args(args): @@ -143,6 +153,7 @@ def parse_args(args): parser.add_argument('--toolchain-prefix', type=str) parser.add_argument('--use-glfw', action='store_true', default=False) + parser.add_argument('--enable-vulkan', action='store_true', default=False) return parser.parse_args(args) diff --git a/engine/src/flutter/tools/licenses/.gitignore b/engine/src/flutter/tools/licenses/.gitignore new file mode 100644 index 0000000000..0eb63bff4c --- /dev/null +++ b/engine/src/flutter/tools/licenses/.gitignore @@ -0,0 +1,2 @@ +.packages + diff --git a/engine/src/flutter/tools/licenses/pubspec.lock b/engine/src/flutter/tools/licenses/pubspec.lock index 185267cfe1..68ed0b1b45 100644 --- a/engine/src/flutter/tools/licenses/pubspec.lock +++ b/engine/src/flutter/tools/licenses/pubspec.lock @@ -7,6 +7,12 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "1.0.27" + args: + description: + name: args + url: "https://pub.dartlang.org" + source: hosted + version: "0.13.7" charcode: description: name: charcode diff --git a/engine/src/flutter/tools/licenses/pubspec.yaml b/engine/src/flutter/tools/licenses/pubspec.yaml index b5d898b5cd..03abd4078f 100644 --- a/engine/src/flutter/tools/licenses/pubspec.yaml +++ b/engine/src/flutter/tools/licenses/pubspec.yaml @@ -2,3 +2,5 @@ name: licenses dependencies: path: ^1.3.0 archive: ^1.0.24 + args: 0.13.7 + diff --git a/engine/src/flutter/vulkan/BUILD.gn b/engine/src/flutter/vulkan/BUILD.gn index f5c184caa9..6992a362ac 100644 --- a/engine/src/flutter/vulkan/BUILD.gn +++ b/engine/src/flutter/vulkan/BUILD.gn @@ -2,24 +2,66 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +config("vulkan_config") { + if (is_fuchsia) { + include_dirs = + [ "//third_party/vulkan_loader_and_validation_layers/include" ] + } else { + include_dirs = [ "//third_party/vulkan/src" ] + } +} + source_set("vulkan") { sources = [ + "vulkan_application.cc", + "vulkan_application.h", "vulkan_backbuffer.cc", "vulkan_backbuffer.h", + "vulkan_command_buffer.cc", + "vulkan_command_buffer.h", + "vulkan_debug_report.cc", + "vulkan_debug_report.h", + "vulkan_device.cc", + "vulkan_device.h", "vulkan_handle.cc", "vulkan_handle.h", + "vulkan_image.cc", + "vulkan_image.h", + "vulkan_interface.cc", "vulkan_interface.h", + "vulkan_native_surface.cc", + "vulkan_native_surface.h", "vulkan_proc_table.cc", "vulkan_proc_table.h", "vulkan_surface.cc", "vulkan_surface.h", - "vulkan_surface_android.cc", - "vulkan_surface_android.h", + "vulkan_swapchain.cc", + "vulkan_swapchain.h", + "vulkan_utilities.cc", + "vulkan_utilities.h", "vulkan_window.cc", "vulkan_window.h", ] + if (is_android) { + sources += [ + "vulkan_native_surface_android.cc", + "vulkan_native_surface_android.h", + ] + } + + if (is_fuchsia) { + sources += [ + "vulkan_native_surface_magma.cc", + "vulkan_native_surface_magma.h", + ] + } + deps = [ "//lib/ftl", + "//third_party/skia", + "//third_party/skia:gpu", ] + + public_configs = [ ":vulkan_config" ] } diff --git a/engine/src/flutter/vulkan/vulkan_application.cc b/engine/src/flutter/vulkan/vulkan_application.cc new file mode 100644 index 0000000000..287794a1d9 --- /dev/null +++ b/engine/src/flutter/vulkan/vulkan_application.cc @@ -0,0 +1,165 @@ +// Copyright 2016 The Chromium 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 "flutter/vulkan/vulkan_application.h" + +#include +#include + +#include "flutter/vulkan/vulkan_device.h" +#include "flutter/vulkan/vulkan_proc_table.h" +#include "flutter/vulkan/vulkan_utilities.h" + +namespace vulkan { + +VulkanApplication::VulkanApplication( + VulkanProcTable& p_vk, + const std::string& application_name, + std::vector enabled_extensions, + uint32_t application_version, + uint32_t api_version) + : vk(p_vk), api_version_(api_version), valid_(false) { + // Check if we want to enable debugging. + + bool enable_instance_debugging = + IsDebuggingEnabled() && VulkanDebugReport::DebugExtensionSupported(vk); + + // Configure extensions. + + if (enable_instance_debugging) { + enabled_extensions.emplace_back(VulkanDebugReport::DebugExtensionName()); + } + + const char* extensions[enabled_extensions.size()]; + + for (size_t i = 0; i < enabled_extensions.size(); i++) { + extensions[i] = enabled_extensions[i].c_str(); + } + + // Configure layers. + + const std::vector enabled_layers = InstanceLayersToEnable(vk); + + const char* layers[enabled_layers.size()]; + + for (size_t i = 0; i < enabled_layers.size(); i++) { + layers[i] = enabled_layers[i].c_str(); + } + + // Configure init structs. + + const VkApplicationInfo info = { + .sType = VK_STRUCTURE_TYPE_APPLICATION_INFO, + .pNext = nullptr, + .pApplicationName = application_name.c_str(), + .applicationVersion = application_version, + .pEngineName = "FlutterEngine", + .engineVersion = VK_MAKE_VERSION(1, 0, 0), + .apiVersion = api_version_, + }; + + const VkInstanceCreateInfo create_info = { + .sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, + .pNext = nullptr, + .flags = 0, + .pApplicationInfo = &info, + .enabledLayerCount = static_cast(enabled_layers.size()), + .ppEnabledLayerNames = layers, + .enabledExtensionCount = static_cast(enabled_extensions.size()), + .ppEnabledExtensionNames = extensions, + }; + + // Perform initialization. + + VkInstance instance = VK_NULL_HANDLE; + + if (VK_CALL_LOG_ERROR(vk.CreateInstance(&create_info, nullptr, &instance)) != + VK_SUCCESS) { + FTL_DLOG(INFO) << "Could not create application instance."; + return; + } + + // Now that we have an instance, setup instance proc table entries. + if (!vk.SetupInstanceProcAddresses(instance)) { + FTL_DLOG(INFO) << "Could not setup instance proc addresses."; + return; + } + + instance_ = {instance, [this](VkInstance i) { + FTL_LOG(INFO) << "Destroying Vulkan instance"; + vk.DestroyInstance(i, nullptr); + }}; + + if (enable_instance_debugging) { + auto debug_report = std::make_unique(vk, instance_); + if (!debug_report->IsValid()) { + FTL_LOG(INFO) << "Vulkan debugging was enabled but could not be setup " + "for this instance."; + } else { + debug_report_ = std::move(debug_report); + FTL_DLOG(INFO) << "Debug reporting is enabled."; + } + } + + valid_ = true; +} + +VulkanApplication::~VulkanApplication() = default; + +bool VulkanApplication::IsValid() const { + return valid_; +} + +uint32_t VulkanApplication::GetAPIVersion() const { + return api_version_; +} + +const VulkanHandle& VulkanApplication::GetInstance() { + return instance_; +} + +std::vector VulkanApplication::GetPhysicalDevices() const { + if (!IsValid()) { + return {}; + } + + uint32_t device_count = 0; + if (VK_CALL_LOG_ERROR(vk.EnumeratePhysicalDevices(instance_, &device_count, + nullptr)) != VK_SUCCESS) { + FTL_DLOG(INFO) << "Could not enumerate physical device."; + return {}; + } + + if (device_count == 0) { + // No available devices. + FTL_DLOG(INFO) << "No physical devices found."; + return {}; + } + + std::vector physical_devices; + + physical_devices.resize(device_count); + + if (VK_CALL_LOG_ERROR(vk.EnumeratePhysicalDevices( + instance_, &device_count, physical_devices.data())) != VK_SUCCESS) { + FTL_DLOG(INFO) << "Could not enumerate physical device."; + return {}; + } + + return physical_devices; +} + +std::unique_ptr +VulkanApplication::AcquireFirstCompatibleLogicalDevice() const { + for (auto device_handle : GetPhysicalDevices()) { + auto logical_device = std::make_unique(vk, device_handle); + if (logical_device->IsValid()) { + return logical_device; + } + } + FTL_DLOG(INFO) << "Could not acquire compatible logical device."; + return nullptr; +} + +} // namespace vulkan diff --git a/engine/src/flutter/vulkan/vulkan_application.h b/engine/src/flutter/vulkan/vulkan_application.h new file mode 100644 index 0000000000..a10fe59f99 --- /dev/null +++ b/engine/src/flutter/vulkan/vulkan_application.h @@ -0,0 +1,54 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_VULKAN_VULKAN_APPLICATION_H_ +#define FLUTTER_VULKAN_VULKAN_APPLICATION_H_ + +#include +#include +#include +#include "flutter/vulkan/vulkan_debug_report.h" +#include "flutter/vulkan/vulkan_handle.h" +#include "lib/ftl/macros.h" + +namespace vulkan { + +class VulkanDevice; +class VulkanProcTable; + +/// Applications using Vulkan acquire a VulkanApplication that attempts to +/// create a VkInstance (with debug reporting optionally enabled). +class VulkanApplication { + public: + VulkanApplication(VulkanProcTable& vk, + const std::string& application_name, + std::vector enabled_extensions, + uint32_t application_version = VK_MAKE_VERSION(1, 0, 0), + uint32_t api_version = VK_MAKE_VERSION(1, 0, 0)); + + ~VulkanApplication(); + + bool IsValid() const; + + uint32_t GetAPIVersion() const; + + const VulkanHandle& GetInstance(); + + std::unique_ptr AcquireFirstCompatibleLogicalDevice() const; + + private: + VulkanProcTable& vk; + VulkanHandle instance_; + uint32_t api_version_; + std::unique_ptr debug_report_; + bool valid_; + + std::vector GetPhysicalDevices() const; + + FTL_DISALLOW_COPY_AND_ASSIGN(VulkanApplication); +}; + +} // namespace vulkan + +#endif // FLUTTER_VULKAN_VULKAN_APPLICATION_H_ diff --git a/engine/src/flutter/vulkan/vulkan_backbuffer.cc b/engine/src/flutter/vulkan/vulkan_backbuffer.cc index e28a1f20bb..86450f406c 100644 --- a/engine/src/flutter/vulkan/vulkan_backbuffer.cc +++ b/engine/src/flutter/vulkan/vulkan_backbuffer.cc @@ -2,34 +2,36 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "vulkan_backbuffer.h" +#include "flutter/vulkan/vulkan_backbuffer.h" #include +#include "flutter/vulkan/vulkan_proc_table.h" +#include "third_party/skia/include/gpu/vk/GrVkTypes.h" +#include "third_party/skia/src/gpu/vk/GrVkUtil.h" + namespace vulkan { -VulkanBackbuffer::VulkanBackbuffer(VulkanProcTable& p_vk, - VulkanHandle& device, - VulkanHandle& pool, - VulkanHandle image) +VulkanBackbuffer::VulkanBackbuffer(const VulkanProcTable& p_vk, + const VulkanHandle& device, + const VulkanHandle& pool) : vk(p_vk), device_(device), - pool_(pool), - image_(std::move(image)), + usage_command_buffer_(p_vk, device, pool), + render_command_buffer_(p_vk, device, pool), valid_(false) { - if (!device_ || !pool_ || !image_) { + if (!usage_command_buffer_.IsValid() || !render_command_buffer_.IsValid()) { + FTL_DLOG(INFO) << "Command buffers were not valid."; return; } if (!CreateSemaphores()) { - return; - } - - if (!CreateTransitionBuffers()) { + FTL_DLOG(INFO) << "Could not create semaphores."; return; } if (!CreateFences()) { + FTL_DLOG(INFO) << "Could not create fences."; return; } @@ -37,7 +39,7 @@ VulkanBackbuffer::VulkanBackbuffer(VulkanProcTable& p_vk, } VulkanBackbuffer::~VulkanBackbuffer() { - WaitFences(); + FTL_ALLOW_UNUSED_LOCAL(WaitFences()); } bool VulkanBackbuffer::IsValid() const { @@ -52,14 +54,14 @@ bool VulkanBackbuffer::CreateSemaphores() { }; auto semaphore_collect = [this](VkSemaphore semaphore) { - vk.destroySemaphore(device_, semaphore, nullptr); + vk.DestroySemaphore(device_, semaphore, nullptr); }; for (size_t i = 0; i < semaphores_.size(); i++) { VkSemaphore semaphore = VK_NULL_HANDLE; - if (vk.createSemaphore(device_, &create_info, nullptr, &semaphore) != - VK_SUCCESS) { + if (VK_CALL_LOG_ERROR(vk.CreateSemaphore(device_, &create_info, nullptr, + &semaphore)) != VK_SUCCESS) { return false; } @@ -69,33 +71,6 @@ bool VulkanBackbuffer::CreateSemaphores() { return true; } -bool VulkanBackbuffer::CreateTransitionBuffers() { - const VkCommandBufferAllocateInfo allocate_info = { - .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, - .pNext = nullptr, - .commandPool = pool_, - .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY, - .commandBufferCount = 1, - }; - - auto buffer_collect = [this](VkCommandBuffer buffer) { - vk.freeCommandBuffers(device_, pool_, 1, &buffer); - }; - - for (size_t i = 0; i < transition_buffers_.size(); i++) { - VkCommandBuffer buffer = VK_NULL_HANDLE; - - if (vk.allocateCommandBuffers(device_, &allocate_info, &buffer) != - VK_SUCCESS) { - return false; - } - - transition_buffers_[i] = {buffer, buffer_collect}; - } - - return true; -} - bool VulkanBackbuffer::CreateFences() { const VkFenceCreateInfo create_info = { .sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, @@ -104,13 +79,14 @@ bool VulkanBackbuffer::CreateFences() { }; auto fence_collect = [this](VkFence fence) { - vk.destroyFence(device_, fence, nullptr); + vk.DestroyFence(device_, fence, nullptr); }; for (size_t i = 0; i < use_fences_.size(); i++) { VkFence fence = VK_NULL_HANDLE; - if (vk.createFence(device_, &create_info, nullptr, &fence) != VK_SUCCESS) { + if (VK_CALL_LOG_ERROR(vk.CreateFence(device_, &create_info, nullptr, + &fence)) != VK_SUCCESS) { return false; } @@ -120,15 +96,52 @@ bool VulkanBackbuffer::CreateFences() { return true; } -void VulkanBackbuffer::WaitFences() { +bool VulkanBackbuffer::WaitFences() { VkFence fences[use_fences_.size()]; for (size_t i = 0; i < use_fences_.size(); i++) { fences[i] = use_fences_[i]; } - vk.waitForFences(device_, static_cast(use_fences_.size()), fences, - true, std::numeric_limits::max()); + return VK_CALL_LOG_ERROR(vk.WaitForFences( + device_, static_cast(use_fences_.size()), fences, true, + std::numeric_limits::max())) == VK_SUCCESS; +} + +bool VulkanBackbuffer::ResetFences() { + VkFence fences[use_fences_.size()]; + + for (size_t i = 0; i < use_fences_.size(); i++) { + fences[i] = use_fences_[i]; + } + + return VK_CALL_LOG_ERROR(vk.ResetFences( + device_, static_cast(use_fences_.size()), fences)) == + VK_SUCCESS; +} + +const VulkanHandle& VulkanBackbuffer::GetUsageFence() const { + return use_fences_[0]; +} + +const VulkanHandle& VulkanBackbuffer::GetRenderFence() const { + return use_fences_[1]; +} + +const VulkanHandle& VulkanBackbuffer::GetUsageSemaphore() const { + return semaphores_[0]; +} + +const VulkanHandle& VulkanBackbuffer::GetRenderSemaphore() const { + return semaphores_[1]; +} + +VulkanCommandBuffer& VulkanBackbuffer::GetUsageCommandBuffer() { + return usage_command_buffer_; +} + +VulkanCommandBuffer& VulkanBackbuffer::GetRenderCommandBuffer() { + return render_command_buffer_; } } // namespace vulkan diff --git a/engine/src/flutter/vulkan/vulkan_backbuffer.h b/engine/src/flutter/vulkan/vulkan_backbuffer.h index e8e8778882..ff752b8516 100644 --- a/engine/src/flutter/vulkan/vulkan_backbuffer.h +++ b/engine/src/flutter/vulkan/vulkan_backbuffer.h @@ -7,43 +7,56 @@ #include +#include "flutter/vulkan/vulkan_command_buffer.h" +#include "flutter/vulkan/vulkan_handle.h" +#include "lib/ftl/compiler_specific.h" #include "lib/ftl/macros.h" -#include "vulkan_proc_table.h" -#include "vulkan_handle.h" +#include "third_party/skia/include/core/SkSize.h" +#include "third_party/skia/include/core/SkSurface.h" namespace vulkan { class VulkanBackbuffer { public: - VulkanBackbuffer(VulkanProcTable& vk, - VulkanHandle& device, - VulkanHandle& pool, - VulkanHandle image); + VulkanBackbuffer(const VulkanProcTable& vk, + const VulkanHandle& device, + const VulkanHandle& pool); ~VulkanBackbuffer(); bool IsValid() const; + FTL_WARN_UNUSED_RESULT + bool WaitFences(); + + FTL_WARN_UNUSED_RESULT + bool ResetFences(); + + const VulkanHandle& GetUsageFence() const; + + const VulkanHandle& GetRenderFence() const; + + const VulkanHandle& GetUsageSemaphore() const; + + const VulkanHandle& GetRenderSemaphore() const; + + VulkanCommandBuffer& GetUsageCommandBuffer(); + + VulkanCommandBuffer& GetRenderCommandBuffer(); + private: - VulkanProcTable& vk; - VulkanHandle& device_; - VulkanHandle& pool_; - VulkanHandle image_; - - bool valid_; - + const VulkanProcTable& vk; + const VulkanHandle& device_; std::array, 2> semaphores_; - std::array, 2> transition_buffers_; std::array, 2> use_fences_; + VulkanCommandBuffer usage_command_buffer_; + VulkanCommandBuffer render_command_buffer_; + bool valid_; bool CreateSemaphores(); - bool CreateTransitionBuffers(); - bool CreateFences(); - void WaitFences(); - FTL_DISALLOW_COPY_AND_ASSIGN(VulkanBackbuffer); }; diff --git a/engine/src/flutter/vulkan/vulkan_command_buffer.cc b/engine/src/flutter/vulkan/vulkan_command_buffer.cc new file mode 100644 index 0000000000..e36b400577 --- /dev/null +++ b/engine/src/flutter/vulkan/vulkan_command_buffer.cc @@ -0,0 +1,83 @@ +// Copyright 2016 The Chromium 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 "flutter/vulkan/vulkan_command_buffer.h" + +#include "flutter/vulkan/vulkan_proc_table.h" + +namespace vulkan { + +VulkanCommandBuffer::VulkanCommandBuffer( + const VulkanProcTable& p_vk, + const VulkanHandle& device, + const VulkanHandle& pool) + : vk(p_vk), device_(device), pool_(pool), valid_(false) { + const VkCommandBufferAllocateInfo allocate_info = { + .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, + .pNext = nullptr, + .commandPool = pool_, + .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY, + .commandBufferCount = 1, + }; + + VkCommandBuffer buffer = VK_NULL_HANDLE; + + if (VK_CALL_LOG_ERROR(vk.AllocateCommandBuffers(device_, &allocate_info, + &buffer)) != VK_SUCCESS) { + FTL_DLOG(INFO) << "Could not allocate command buffers."; + return; + } + + auto buffer_collect = [this](VkCommandBuffer buffer) { + vk.FreeCommandBuffers(device_, pool_, 1, &buffer); + }; + + handle_ = {buffer, buffer_collect}; + + valid_ = true; +} + +VulkanCommandBuffer::~VulkanCommandBuffer() = default; + +bool VulkanCommandBuffer::IsValid() const { + return valid_; +} + +VkCommandBuffer VulkanCommandBuffer::Handle() const { + return handle_; +} + +bool VulkanCommandBuffer::Begin() const { + const VkCommandBufferBeginInfo info{ + .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, + .pNext = nullptr, + .flags = 0, + .pInheritanceInfo = nullptr, + }; + + return VK_CALL_LOG_ERROR(vk.BeginCommandBuffer(handle_, &info)) == VK_SUCCESS; +} + +bool VulkanCommandBuffer::End() const { + return VK_CALL_LOG_ERROR(vk.EndCommandBuffer(handle_)) == VK_SUCCESS; +} + +bool VulkanCommandBuffer::InsertPipelineBarrier( + VkPipelineStageFlagBits src_stage_flags, + VkPipelineStageFlagBits dest_stage_flags, + uint32_t /* mask of VkDependencyFlagBits */ dependency_flags, + uint32_t memory_barrier_count, + const VkMemoryBarrier* memory_barriers, + uint32_t buffer_memory_barrier_count, + const VkBufferMemoryBarrier* buffer_memory_barriers, + uint32_t image_memory_barrier_count, + const VkImageMemoryBarrier* image_memory_barriers) const { + vk.CmdPipelineBarrier(handle_, src_stage_flags, dest_stage_flags, + dependency_flags, memory_barrier_count, memory_barriers, + buffer_memory_barrier_count, buffer_memory_barriers, + image_memory_barrier_count, image_memory_barriers); + return true; +} + +} // namespace vulkan diff --git a/engine/src/flutter/vulkan/vulkan_command_buffer.h b/engine/src/flutter/vulkan/vulkan_command_buffer.h new file mode 100644 index 0000000000..2c337bf8bc --- /dev/null +++ b/engine/src/flutter/vulkan/vulkan_command_buffer.h @@ -0,0 +1,58 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_VULKAN_VULKAN_COMMAND_BUFFER_H_ +#define FLUTTER_VULKAN_VULKAN_COMMAND_BUFFER_H_ + +#include "flutter/vulkan/vulkan_handle.h" +#include "lib/ftl/compiler_specific.h" +#include "lib/ftl/macros.h" + +namespace vulkan { + +class VulkanProcTable; + +class VulkanCommandBuffer { + public: + VulkanCommandBuffer(const VulkanProcTable& vk, + const VulkanHandle& device, + const VulkanHandle& pool); + + ~VulkanCommandBuffer(); + + bool IsValid() const; + + VkCommandBuffer Handle() const; + + FTL_WARN_UNUSED_RESULT + bool Begin() const; + + FTL_WARN_UNUSED_RESULT + bool End() const; + + FTL_WARN_UNUSED_RESULT + bool InsertPipelineBarrier( + VkPipelineStageFlagBits src_stage_flags, + VkPipelineStageFlagBits dest_stage_flags, + uint32_t /* mask of VkDependencyFlagBits */ dependency_flags, + uint32_t memory_barrier_count, + const VkMemoryBarrier* memory_barriers, + uint32_t buffer_memory_barrier_count, + const VkBufferMemoryBarrier* buffer_memory_barriers, + uint32_t image_memory_barrier_count, + const VkImageMemoryBarrier* image_memory_barriers) const; + + private: + const VulkanProcTable& vk; + const VulkanHandle& device_; + const VulkanHandle& pool_; + VulkanHandle handle_; + bool valid_; + + FTL_DISALLOW_COPY_AND_ASSIGN(VulkanCommandBuffer); +}; + +} // namespace vulkan + +#endif // FLUTTER_VULKAN_VULKAN_COMMAND_BUFFER_H_ diff --git a/engine/src/flutter/vulkan/vulkan_debug_report.cc b/engine/src/flutter/vulkan/vulkan_debug_report.cc new file mode 100644 index 0000000000..d2240f81e5 --- /dev/null +++ b/engine/src/flutter/vulkan/vulkan_debug_report.cc @@ -0,0 +1,254 @@ +// Copyright 2016 The Chromium 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 "flutter/vulkan/vulkan_debug_report.h" + +#include +#include + +#include "flutter/vulkan/vulkan_utilities.h" + +namespace vulkan { + +static const VkDebugReportFlagsEXT kVulkanErrorFlags FTL_ALLOW_UNUSED_TYPE = + VK_DEBUG_REPORT_WARNING_BIT_EXT | + VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT | VK_DEBUG_REPORT_ERROR_BIT_EXT; + +static const VkDebugReportFlagsEXT kVulkanInfoFlags FTL_ALLOW_UNUSED_TYPE = + VK_DEBUG_REPORT_INFORMATION_BIT_EXT | VK_DEBUG_REPORT_DEBUG_BIT_EXT; + +std::string VulkanDebugReport::DebugExtensionName() { + return VK_EXT_DEBUG_REPORT_EXTENSION_NAME; +} + +bool VulkanDebugReport::DebugExtensionSupported(const VulkanProcTable& vk) { + if (!IsDebuggingEnabled()) { + return false; + } + + if (!vk.EnumerateInstanceExtensionProperties) { + return false; + } + + uint32_t count = 0; + if (VK_CALL_LOG_ERROR(vk.EnumerateInstanceExtensionProperties( + nullptr, &count, nullptr)) != VK_SUCCESS) { + return false; + } + + if (count == 0) { + return false; + } + + std::vector properties; + properties.resize(count); + if (VK_CALL_LOG_ERROR(vk.EnumerateInstanceExtensionProperties( + nullptr, &count, properties.data())) != VK_SUCCESS) { + return false; + } + + auto debug_extension_name = DebugExtensionName(); + + for (size_t i = 0; i < count; i++) { + if (strncmp(properties[i].extensionName, debug_extension_name.c_str(), + debug_extension_name.size()) == 0) { + return true; + } + } + + return false; +} + +static const char* VkDebugReportFlagsEXTToString(VkDebugReportFlagsEXT flags) { + if (flags & VK_DEBUG_REPORT_INFORMATION_BIT_EXT) { + return "Information"; + } else if (flags & VK_DEBUG_REPORT_WARNING_BIT_EXT) { + return "Warning"; + } else if (flags & VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT) { + return "Performance Warning"; + } else if (flags & VK_DEBUG_REPORT_ERROR_BIT_EXT) { + return "Error"; + } else if (flags & VK_DEBUG_REPORT_DEBUG_BIT_EXT) { + return "Debug"; + } + return "UNKNOWN"; +} + +static const char* VkDebugReportObjectTypeEXTToString( + VkDebugReportObjectTypeEXT type) { + switch (type) { + case VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT: + return "Unknown"; + case VK_DEBUG_REPORT_OBJECT_TYPE_INSTANCE_EXT: + return "Instance"; + case VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT: + return "Physical Device"; + case VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT: + return "Device"; + case VK_DEBUG_REPORT_OBJECT_TYPE_QUEUE_EXT: + return "Queue"; + case VK_DEBUG_REPORT_OBJECT_TYPE_SEMAPHORE_EXT: + return "Semaphore"; + case VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT: + return "Command Buffer"; + case VK_DEBUG_REPORT_OBJECT_TYPE_FENCE_EXT: + return "Fence"; + case VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT: + return "Device Memory"; + case VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT: + return "Buffer"; + case VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT: + return "Image"; + case VK_DEBUG_REPORT_OBJECT_TYPE_EVENT_EXT: + return "Event"; + case VK_DEBUG_REPORT_OBJECT_TYPE_QUERY_POOL_EXT: + return "Query Pool"; + case VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_VIEW_EXT: + return "Buffer View"; + case VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_VIEW_EXT: + return "Image_view"; + case VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT: + return "Shader Module"; + case VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_CACHE_EXT: + return "Pipeline Cache"; + case VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_LAYOUT_EXT: + return "Pipeline Layout"; + case VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT: + return "Render Pass"; + case VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT: + return "Pipeline"; + case VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT_EXT: + return "Descriptor Set Layout"; + case VK_DEBUG_REPORT_OBJECT_TYPE_SAMPLER_EXT: + return "Sampler"; + case VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_POOL_EXT: + return "Descriptor Pool"; + case VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT: + return "Descriptor Set"; + case VK_DEBUG_REPORT_OBJECT_TYPE_FRAMEBUFFER_EXT: + return "Framebuffer"; + case VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_POOL_EXT: + return "Command Pool"; + case VK_DEBUG_REPORT_OBJECT_TYPE_SURFACE_KHR_EXT: + return "Surface"; + case VK_DEBUG_REPORT_OBJECT_TYPE_SWAPCHAIN_KHR_EXT: + return "Swapchain"; + case VK_DEBUG_REPORT_OBJECT_TYPE_DEBUG_REPORT_EXT: + return "Debug"; + default: + break; + } + + return "Unknown"; +} + +static VKAPI_ATTR VkBool32 +OnVulkanDebugReportCallback(VkDebugReportFlagsEXT flags, + VkDebugReportObjectTypeEXT object_type, + uint64_t object, + size_t location, + int32_t message_code, + const char* layer_prefix, + const char* message, + void* user_data) { + std::vector> items; + + items.emplace_back("Severity", VkDebugReportFlagsEXTToString(flags)); + + items.emplace_back("Object Type", + VkDebugReportObjectTypeEXTToString(object_type)); + + items.emplace_back("Object Handle", std::to_string(object)); + + if (location != 0) { + items.emplace_back("Location", std::to_string(location)); + } + + if (message_code != 0) { + items.emplace_back("Message Code", std::to_string(message_code)); + } + + if (layer_prefix != nullptr) { + items.emplace_back("Layer", layer_prefix); + } + + if (message != nullptr) { + items.emplace_back("Message", message); + } + + size_t padding = 0; + + for (const auto& item : items) { + padding = std::max(padding, item.first.size()); + } + + padding += 1; + + std::stringstream stream; + + stream << std::endl; + + stream << "--- Vulkan Debug Report ----------------------------------------"; + + stream << std::endl; + + for (const auto& item : items) { + stream << "| " << std::setw(static_cast(padding)) << item.first + << std::setw(0) << ": " << item.second << std::endl; + } + + stream << "-----------------------------------------------------------------"; + + if (flags & kVulkanErrorFlags) { + FTL_DCHECK(false) << stream.str(); + } else { + FTL_LOG(INFO) << stream.str(); + } + + // Returning false tells the layer not to stop when the event occurs, so + // they see the same behavior with and without validation layers enabled. + return VK_FALSE; +} + +VulkanDebugReport::VulkanDebugReport( + const VulkanProcTable& p_vk, + const VulkanHandle& application) + : vk(p_vk), application_(application), valid_(false) { + if (!IsDebuggingEnabled() || !vk.CreateDebugReportCallbackEXT || + !vk.DestroyDebugReportCallbackEXT) { + return; + } + + if (!application_) { + return; + } + + const VkDebugReportCallbackCreateInfoEXT create_info = { + .sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT, + .pNext = nullptr, + .flags = kVulkanErrorFlags | kVulkanInfoFlags, + .pfnCallback = &vulkan::OnVulkanDebugReportCallback, + .pUserData = nullptr, + }; + + VkDebugReportCallbackEXT handle = VK_NULL_HANDLE; + if (VK_CALL_LOG_ERROR(vk.CreateDebugReportCallbackEXT( + application_, &create_info, nullptr, &handle)) != VK_SUCCESS) { + return; + } + + handle_ = {handle, [this](VkDebugReportCallbackEXT handle) { + vk.DestroyDebugReportCallbackEXT(application_, handle, nullptr); + }}; + + valid_ = true; +} + +VulkanDebugReport::~VulkanDebugReport() = default; + +bool VulkanDebugReport::IsValid() const { + return valid_; +} + +} // namespace vulkan diff --git a/engine/src/flutter/vulkan/vulkan_debug_report.h b/engine/src/flutter/vulkan/vulkan_debug_report.h new file mode 100644 index 0000000000..112a87d082 --- /dev/null +++ b/engine/src/flutter/vulkan/vulkan_debug_report.h @@ -0,0 +1,39 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_VULKAN_VULKAN_DEBUG_REPORT_H_ +#define FLUTTER_VULKAN_VULKAN_DEBUG_REPORT_H_ + +#include "flutter/vulkan/vulkan_handle.h" +#include "flutter/vulkan/vulkan_interface.h" +#include "flutter/vulkan/vulkan_proc_table.h" +#include "lib/ftl/macros.h" + +namespace vulkan { + +class VulkanDebugReport { + public: + static bool DebugExtensionSupported(const VulkanProcTable& vk); + + static std::string DebugExtensionName(); + + VulkanDebugReport(const VulkanProcTable& vk, + const VulkanHandle& application); + + ~VulkanDebugReport(); + + bool IsValid() const; + + private: + const VulkanProcTable& vk; + const VulkanHandle& application_; + VulkanHandle handle_; + bool valid_; + + FTL_DISALLOW_COPY_AND_ASSIGN(VulkanDebugReport); +}; + +} // namespace vulkan + +#endif // FLUTTER_VULKAN_VULKAN_DEBUG_REPORT_H_ diff --git a/engine/src/flutter/vulkan/vulkan_device.cc b/engine/src/flutter/vulkan/vulkan_device.cc new file mode 100644 index 0000000000..0e6b0cd644 --- /dev/null +++ b/engine/src/flutter/vulkan/vulkan_device.cc @@ -0,0 +1,313 @@ +// Copyright 2016 The Chromium 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 "flutter/vulkan/vulkan_device.h" + +#include +#include + +#include "flutter/vulkan/vulkan_proc_table.h" +#include "flutter/vulkan/vulkan_surface.h" +#include "flutter/vulkan/vulkan_utilities.h" +#include "third_party/skia/include/gpu/vk/GrVkBackendContext.h" +#include "third_party/skia/src/gpu/vk/GrVkUtil.h" + +namespace vulkan { + +constexpr auto kVulkanInvalidGraphicsQueueIndex = + std::numeric_limits::max(); + +static uint32_t FindGraphicsQueueIndex( + const std::vector& properties) { + for (uint32_t i = 0, count = static_cast(properties.size()); + i < count; i++) { + if (properties[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) { + return i; + } + } + return kVulkanInvalidGraphicsQueueIndex; +} + +VulkanDevice::VulkanDevice(VulkanProcTable& p_vk, + VulkanHandle physical_device) + : vk(p_vk), + physical_device_(std::move(physical_device)), + graphics_queue_index_(std::numeric_limits::max()), + valid_(false) { + if (!physical_device_ || !vk.AreInstanceProcsSetup()) { + return; + } + + graphics_queue_index_ = FindGraphicsQueueIndex(GetQueueFamilyProperties()); + + if (graphics_queue_index_ == kVulkanInvalidGraphicsQueueIndex) { + FTL_DLOG(INFO) << "Could not find the graphics queue index."; + return; + } + + const float priorities[1] = {1.0f}; + + const VkDeviceQueueCreateInfo queue_create = { + .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, + .pNext = nullptr, + .flags = 0, + .queueFamilyIndex = graphics_queue_index_, + .queueCount = 1, + .pQueuePriorities = priorities, + }; + + const char* extensions[] = { + VK_KHR_SWAPCHAIN_EXTENSION_NAME, + }; + + auto enabled_layers = DeviceLayersToEnable(vk, physical_device_); + + const char* layers[enabled_layers.size()]; + + for (size_t i = 0; i < enabled_layers.size(); i++) { + layers[i] = enabled_layers[i].c_str(); + } + + const VkDeviceCreateInfo create_info = { + .sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, + .pNext = nullptr, + .flags = 0, + .queueCreateInfoCount = 1, + .pQueueCreateInfos = &queue_create, + .enabledLayerCount = static_cast(enabled_layers.size()), + .ppEnabledLayerNames = layers, + .enabledExtensionCount = sizeof(extensions) / sizeof(const char*), + .ppEnabledExtensionNames = extensions, + .pEnabledFeatures = nullptr, + }; + + VkDevice device = VK_NULL_HANDLE; + + if (VK_CALL_LOG_ERROR(vk.CreateDevice(physical_device_, &create_info, nullptr, + &device)) != VK_SUCCESS) { + FTL_DLOG(INFO) << "Could not create device."; + return; + } + + device_ = {device, + [this](VkDevice device) { vk.DestroyDevice(device, nullptr); }}; + + if (!vk.SetupDeviceProcAddresses(device_)) { + FTL_DLOG(INFO) << "Could not setup device proc addresses."; + return; + } + + VkQueue queue = VK_NULL_HANDLE; + + vk.GetDeviceQueue(device_, graphics_queue_index_, 0, &queue); + + if (queue == VK_NULL_HANDLE) { + FTL_DLOG(INFO) << "Could not get the device queue handle."; + return; + } + + queue_ = queue; + + const VkCommandPoolCreateInfo command_pool_create_info = { + .sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, + .pNext = nullptr, + .flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, + .queueFamilyIndex = 0, + }; + + VkCommandPool command_pool = VK_NULL_HANDLE; + if (VK_CALL_LOG_ERROR(vk.CreateCommandPool(device_, &command_pool_create_info, + nullptr, &command_pool)) != + VK_SUCCESS) { + FTL_DLOG(INFO) << "Could not create the command pool."; + return; + } + + command_pool_ = {command_pool, [this](VkCommandPool pool) { + vk.DestroyCommandPool(device_, pool, nullptr); + }}; + + valid_ = true; +} + +VulkanDevice::~VulkanDevice() { + FTL_ALLOW_UNUSED_LOCAL(WaitIdle()); +} + +bool VulkanDevice::IsValid() const { + return valid_; +} + +bool VulkanDevice::WaitIdle() const { + return VK_CALL_LOG_ERROR(vk.DeviceWaitIdle(device_)) == VK_SUCCESS; +} + +const VulkanHandle& VulkanDevice::GetHandle() const { + return device_; +} + +const VulkanHandle& VulkanDevice::GetPhysicalDeviceHandle() + const { + return physical_device_; +} + +const VulkanHandle& VulkanDevice::GetQueueHandle() const { + return queue_; +} + +const VulkanHandle& VulkanDevice::GetCommandPool() const { + return command_pool_; +} + +uint32_t VulkanDevice::GetGraphicsQueueIndex() const { + return graphics_queue_index_; +} + +bool VulkanDevice::GetSurfaceCapabilities( + const VulkanSurface& surface, + VkSurfaceCapabilitiesKHR* capabilities) const { + if (!surface.IsValid()) { + return false; + } + + return VK_CALL_LOG_ERROR(vk.GetPhysicalDeviceSurfaceCapabilitiesKHR( + physical_device_, surface.Handle(), capabilities)) == VK_SUCCESS; +} + +bool VulkanDevice::GetPhysicalDeviceFeatures( + VkPhysicalDeviceFeatures* features) const { + if (features == nullptr || !physical_device_) { + return false; + } + vk.GetPhysicalDeviceFeatures(physical_device_, features); + return true; +} + +bool VulkanDevice::GetPhysicalDeviceFeaturesSkia(uint32_t* sk_features) const { + if (sk_features == nullptr) { + return false; + } + + VkPhysicalDeviceFeatures features; + + if (!GetPhysicalDeviceFeatures(&features)) { + return false; + } + + uint32_t flags = 0; + + if (features.geometryShader) { + flags |= kGeometryShader_GrVkFeatureFlag; + } + if (features.dualSrcBlend) { + flags |= kDualSrcBlend_GrVkFeatureFlag; + } + if (features.sampleRateShading) { + flags |= kSampleRateShading_GrVkFeatureFlag; + } + + *sk_features = flags; + return true; +} + +std::vector VulkanDevice::GetQueueFamilyProperties() + const { + uint32_t count = 0; + + vk.GetPhysicalDeviceQueueFamilyProperties(physical_device_, &count, nullptr); + + std::vector properties; + properties.resize(count, {}); + + vk.GetPhysicalDeviceQueueFamilyProperties(physical_device_, &count, + properties.data()); + + return properties; +} + +bool VulkanDevice::ChooseSurfaceFormat(const VulkanSurface& surface, + VkSurfaceFormatKHR* format) const { + if (!surface.IsValid() || format == nullptr) { + return false; + } + + uint32_t format_count = 0; + if (VK_CALL_LOG_ERROR(vk.GetPhysicalDeviceSurfaceFormatsKHR( + physical_device_, surface.Handle(), &format_count, nullptr)) != + VK_SUCCESS) { + return false; + } + + if (format_count == 0) { + return false; + } + + VkSurfaceFormatKHR formats[format_count]; + if (VK_CALL_LOG_ERROR(vk.GetPhysicalDeviceSurfaceFormatsKHR( + physical_device_, surface.Handle(), &format_count, formats)) != + VK_SUCCESS) { + return false; + } + + for (uint32_t i = 0; i < format_count; i++) { + if (GrVkFormatToPixelConfig(formats[i].format, nullptr /* dont care */)) { + *format = formats[i]; + return true; + } + } + + return false; +} + +bool VulkanDevice::ChoosePresentMode(const VulkanSurface& surface, + VkPresentModeKHR* present_mode) const { + if (!surface.IsValid() || present_mode == nullptr) { + return false; + } + + // https://github.com/LunarG/VulkanSamples/issues/98 indicates that + // VK_PRESENT_MODE_FIFO_KHR is preferable on mobile platforms. The problems + // mentioned in the ticket w.r.t the application being faster that the refresh + // rate of the screen should not be faced by any Flutter platforms as they are + // powered by Vsync pulses instead of depending the the submit to block. + // However, for platforms that don't have VSync providers setup, it is better + // to fall back to FIFO. For platforms that do have VSync providers, there + // should be little difference. In case there is a need for a mode other than + // FIFO, availability checks must be performed here before returning the + // result. FIFO is always present. + *present_mode = VK_PRESENT_MODE_FIFO_KHR; + return true; +} + +bool VulkanDevice::QueueSubmit( + std::vector wait_dest_pipeline_stages, + const std::vector& wait_semaphores, + const std::vector& signal_semaphores, + const std::vector& command_buffers, + const VulkanHandle& fence) const { + if (wait_semaphores.size() != wait_dest_pipeline_stages.size()) { + return false; + } + + const VkSubmitInfo submit_info = { + .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, + .pNext = nullptr, + .waitSemaphoreCount = static_cast(wait_semaphores.size()), + .pWaitSemaphores = wait_semaphores.data(), + .pWaitDstStageMask = wait_dest_pipeline_stages.data(), + .commandBufferCount = static_cast(command_buffers.size()), + .pCommandBuffers = command_buffers.data(), + .signalSemaphoreCount = static_cast(signal_semaphores.size()), + .pSignalSemaphores = signal_semaphores.data(), + }; + + if (VK_CALL_LOG_ERROR(vk.QueueSubmit(queue_, 1, &submit_info, fence)) != + VK_SUCCESS) { + return false; + } + + return true; +} + +} // namespace vulkan diff --git a/engine/src/flutter/vulkan/vulkan_device.h b/engine/src/flutter/vulkan/vulkan_device.h new file mode 100644 index 0000000000..8136c81128 --- /dev/null +++ b/engine/src/flutter/vulkan/vulkan_device.h @@ -0,0 +1,83 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_VULKAN_VULKAN_DEVICE_H_ +#define FLUTTER_VULKAN_VULKAN_DEVICE_H_ + +#include + +#include "flutter/vulkan/vulkan_handle.h" +#include "lib/ftl/compiler_specific.h" +#include "lib/ftl/macros.h" + +namespace vulkan { + +class VulkanProcTable; +class VulkanSurface; + +class VulkanDevice { + public: + VulkanDevice(VulkanProcTable& vk, + VulkanHandle physical_device); + + ~VulkanDevice(); + + bool IsValid() const; + + const VulkanHandle& GetHandle() const; + + const VulkanHandle& GetPhysicalDeviceHandle() const; + + const VulkanHandle& GetQueueHandle() const; + + const VulkanHandle& GetCommandPool() const; + + uint32_t GetGraphicsQueueIndex() const; + + FTL_WARN_UNUSED_RESULT + bool GetSurfaceCapabilities(const VulkanSurface& surface, + VkSurfaceCapabilitiesKHR* capabilities) const; + + FTL_WARN_UNUSED_RESULT + bool GetPhysicalDeviceFeatures(VkPhysicalDeviceFeatures* features) const; + + FTL_WARN_UNUSED_RESULT + bool GetPhysicalDeviceFeaturesSkia( + uint32_t* /* mask of GrVkFeatureFlags */ features) const; + + FTL_WARN_UNUSED_RESULT + bool ChooseSurfaceFormat(const VulkanSurface& surface, + VkSurfaceFormatKHR* format) const; + + FTL_WARN_UNUSED_RESULT + bool ChoosePresentMode(const VulkanSurface& surface, + VkPresentModeKHR* present_mode) const; + + FTL_WARN_UNUSED_RESULT + bool QueueSubmit(std::vector wait_dest_pipeline_stages, + const std::vector& wait_semaphores, + const std::vector& signal_semaphores, + const std::vector& command_buffers, + const VulkanHandle& fence) const; + + FTL_WARN_UNUSED_RESULT + bool WaitIdle() const; + + private: + VulkanProcTable& vk; + VulkanHandle physical_device_; + VulkanHandle device_; + VulkanHandle queue_; + VulkanHandle command_pool_; + uint32_t graphics_queue_index_; + bool valid_; + + std::vector GetQueueFamilyProperties() const; + + FTL_DISALLOW_COPY_AND_ASSIGN(VulkanDevice); +}; + +} // namespace vulkan + +#endif // FLUTTER_VULKAN_VULKAN_DEVICE_H_ diff --git a/engine/src/flutter/vulkan/vulkan_handle.h b/engine/src/flutter/vulkan/vulkan_handle.h index cf97ab9e15..1627356ff4 100644 --- a/engine/src/flutter/vulkan/vulkan_handle.h +++ b/engine/src/flutter/vulkan/vulkan_handle.h @@ -7,9 +7,9 @@ #include +#include "lib/ftl/logging.h" #include "lib/ftl/macros.h" #include "vulkan_interface.h" -#include "lib/ftl/logging.h" namespace vulkan { @@ -21,7 +21,7 @@ class VulkanHandle { VulkanHandle() : handle_(VK_NULL_HANDLE) {} - VulkanHandle(Handle handle, Disposer disposer) + VulkanHandle(Handle handle, Disposer disposer = nullptr) : handle_(handle), disposer_(disposer) {} VulkanHandle(VulkanHandle&& other) @@ -58,7 +58,9 @@ class VulkanHandle { if (handle_ == VK_NULL_HANDLE) { return; } - disposer_(handle_); + if (disposer_) { + disposer_(handle_); + } handle_ = VK_NULL_HANDLE; disposer_ = nullptr; } diff --git a/engine/src/flutter/vulkan/vulkan_image.cc b/engine/src/flutter/vulkan/vulkan_image.cc new file mode 100644 index 0000000000..239defb9b9 --- /dev/null +++ b/engine/src/flutter/vulkan/vulkan_image.cc @@ -0,0 +1,69 @@ +// Copyright 2016 The Chromium 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 "flutter/vulkan/vulkan_image.h" + +#include "flutter/vulkan/vulkan_command_buffer.h" +#include "flutter/vulkan/vulkan_proc_table.h" + +namespace vulkan { + +VulkanImage::VulkanImage(VulkanHandle image) + : handle_(std::move(image)), + layout_(VK_IMAGE_LAYOUT_UNDEFINED), + access_flags_(0), + valid_(false) { + if (!handle_) { + return; + } + + valid_ = true; +} + +VulkanImage::~VulkanImage() = default; + +bool VulkanImage::IsValid() const { + return valid_; +} + +bool VulkanImage::InsertImageMemoryBarrier( + const VulkanCommandBuffer& command_buffer, + VkPipelineStageFlagBits src_pipline_bits, + VkPipelineStageFlagBits dest_pipline_bits, + VkAccessFlagBits dest_access_flags, + VkImageLayout dest_layout) { + const VkImageMemoryBarrier image_memory_barrier = { + .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, + .pNext = nullptr, + .srcAccessMask = access_flags_, + .dstAccessMask = dest_access_flags, + .oldLayout = layout_, + .newLayout = dest_layout, + .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .image = handle_, + .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}, + }; + + bool success = command_buffer.InsertPipelineBarrier( + src_pipline_bits, // src_stage_flags + dest_pipline_bits, // dest_stage_flags + 0, // dependency_flags + 0, // memory_barrier_count + nullptr, // memory_barriers + 0, // buffer_memory_barrier_count + nullptr, // buffer_memory_barriers + 1, // image_memory_barrier_count + &image_memory_barrier // image_memory_barriers + ); + + if (success) { + access_flags_ = dest_access_flags; + layout_ = dest_layout; + } + + return success; +} + +} // namespace vulkan diff --git a/engine/src/flutter/vulkan/vulkan_image.h b/engine/src/flutter/vulkan/vulkan_image.h new file mode 100644 index 0000000000..386dd2ef26 --- /dev/null +++ b/engine/src/flutter/vulkan/vulkan_image.h @@ -0,0 +1,43 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_VULKAN_VULKAN_IMAGE_H_ +#define FLUTTER_VULKAN_VULKAN_IMAGE_H_ + +#include "flutter/vulkan/vulkan_handle.h" +#include "lib/ftl/compiler_specific.h" +#include "lib/ftl/macros.h" + +namespace vulkan { + +class VulkanProcTable; +class VulkanCommandBuffer; + +class VulkanImage { + public: + VulkanImage(VulkanHandle image); + + ~VulkanImage(); + + bool IsValid() const; + + FTL_WARN_UNUSED_RESULT + bool InsertImageMemoryBarrier(const VulkanCommandBuffer& command_buffer, + VkPipelineStageFlagBits src_pipline_bits, + VkPipelineStageFlagBits dest_pipline_bits, + VkAccessFlagBits dest_access_flags, + VkImageLayout dest_layout); + + private: + VulkanHandle handle_; + VkImageLayout layout_; + uint32_t /* mask of VkAccessFlagBits */ access_flags_; + bool valid_; + + FTL_DISALLOW_COPY_AND_ASSIGN(VulkanImage); +}; + +} // namespace vulkan + +#endif // FLUTTER_VULKAN_VULKAN_IMAGE_H_ diff --git a/engine/src/flutter/vulkan/vulkan_interface.cc b/engine/src/flutter/vulkan/vulkan_interface.cc new file mode 100644 index 0000000000..13a4a421af --- /dev/null +++ b/engine/src/flutter/vulkan/vulkan_interface.cc @@ -0,0 +1,69 @@ +// Copyright 2016 The Chromium 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 "flutter/vulkan/vulkan_interface.h" + +namespace vulkan { + +std::string VulkanResultToString(VkResult result) { + switch (result) { + case VK_SUCCESS: + return "VK_SUCCESS"; + case VK_NOT_READY: + return "VK_NOT_READY"; + case VK_TIMEOUT: + return "VK_TIMEOUT"; + case VK_EVENT_SET: + return "VK_EVENT_SET"; + case VK_EVENT_RESET: + return "VK_EVENT_RESET"; + case VK_INCOMPLETE: + return "VK_INCOMPLETE"; + case VK_ERROR_OUT_OF_HOST_MEMORY: + return "VK_ERROR_OUT_OF_HOST_MEMORY"; + case VK_ERROR_OUT_OF_DEVICE_MEMORY: + return "VK_ERROR_OUT_OF_DEVICE_MEMORY"; + case VK_ERROR_INITIALIZATION_FAILED: + return "VK_ERROR_INITIALIZATION_FAILED"; + case VK_ERROR_DEVICE_LOST: + return "VK_ERROR_DEVICE_LOST"; + case VK_ERROR_MEMORY_MAP_FAILED: + return "VK_ERROR_MEMORY_MAP_FAILED"; + case VK_ERROR_LAYER_NOT_PRESENT: + return "VK_ERROR_LAYER_NOT_PRESENT"; + case VK_ERROR_EXTENSION_NOT_PRESENT: + return "VK_ERROR_EXTENSION_NOT_PRESENT"; + case VK_ERROR_FEATURE_NOT_PRESENT: + return "VK_ERROR_FEATURE_NOT_PRESENT"; + case VK_ERROR_INCOMPATIBLE_DRIVER: + return "VK_ERROR_INCOMPATIBLE_DRIVER"; + case VK_ERROR_TOO_MANY_OBJECTS: + return "VK_ERROR_TOO_MANY_OBJECTS"; + case VK_ERROR_FORMAT_NOT_SUPPORTED: + return "VK_ERROR_FORMAT_NOT_SUPPORTED"; + case VK_ERROR_FRAGMENTED_POOL: + return "VK_ERROR_FRAGMENTED_POOL"; + case VK_ERROR_SURFACE_LOST_KHR: + return "VK_ERROR_SURFACE_LOST_KHR"; + case VK_ERROR_NATIVE_WINDOW_IN_USE_KHR: + return "VK_ERROR_NATIVE_WINDOW_IN_USE_KHR"; + case VK_SUBOPTIMAL_KHR: + return "VK_SUBOPTIMAL_KHR"; + case VK_ERROR_OUT_OF_DATE_KHR: + return "VK_ERROR_OUT_OF_DATE_KHR"; + case VK_ERROR_INCOMPATIBLE_DISPLAY_KHR: + return "VK_ERROR_INCOMPATIBLE_DISPLAY_KHR"; + case VK_ERROR_VALIDATION_FAILED_EXT: + return "VK_ERROR_VALIDATION_FAILED_EXT"; + case VK_ERROR_INVALID_SHADER_NV: + return "VK_ERROR_INVALID_SHADER_NV"; + case VK_RESULT_RANGE_SIZE: + return "VK_RESULT_RANGE_SIZE"; + case VK_RESULT_MAX_ENUM: + return "VK_RESULT_MAX_ENUM"; + } + return "Unknown Error"; +} + +} // namespace vulkan diff --git a/engine/src/flutter/vulkan/vulkan_interface.h b/engine/src/flutter/vulkan/vulkan_interface.h index e0ffa9436c..92d83e7164 100644 --- a/engine/src/flutter/vulkan/vulkan_interface.h +++ b/engine/src/flutter/vulkan/vulkan_interface.h @@ -5,14 +5,54 @@ #ifndef FLUTTER_VULKAN_VULKAN_INTERFACE_H_ #define FLUTTER_VULKAN_VULKAN_INTERFACE_H_ -#define VK_NO_PROTOTYPES 1 +#include #include "lib/ftl/build_config.h" +#include "lib/ftl/logging.h" + +#define VULKAN_LINK_STATICALLY OS_FUCHSIA #if OS_ANDROID +#ifndef VK_USE_PLATFORM_ANDROID_KHR #define VK_USE_PLATFORM_ANDROID_KHR 1 +#endif // VK_USE_PLATFORM_ANDROID_KHR #endif // OS_ANDROID -#include "third_party/vulkan/src/vulkan/vulkan.h" +#if OS_FUCHSIA +#ifndef VK_USE_PLATFORM_MAGMA_KHR +#define VK_USE_PLATFORM_MAGMA_KHR 1 +#endif // VK_USE_PLATFORM_MAGMA_KHR +#endif // OS_FUCHSIA + +#if !VULKAN_LINK_STATICALLY +#define VK_NO_PROTOTYPES 1 +#endif // !VULKAN_LINK_STATICALLY + +#include + +#ifndef NDEBUG + +#define VK_CALL_LOG_ERROR(expression) \ + ({ \ + __typeof__(expression) _rc = (expression); \ + if (_rc != VK_SUCCESS) { \ + FTL_DLOG(INFO) << "Vulkan call '" << #expression \ + << "' failed with error " \ + << vulkan::VulkanResultToString(_rc); \ + } \ + _rc; \ + }) + +#else // NDEBUG + +#define VK_CALL_LOG_ERROR(expression) (expression) + +#endif // NDEBUG + +namespace vulkan { + +std::string VulkanResultToString(VkResult result); + +} // namespace vulkan #endif // FLUTTER_VULKAN_VULKAN_INTERFACE_H_ diff --git a/engine/src/flutter/vulkan/vulkan_native_surface.cc b/engine/src/flutter/vulkan/vulkan_native_surface.cc new file mode 100644 index 0000000000..e05cfb1fc1 --- /dev/null +++ b/engine/src/flutter/vulkan/vulkan_native_surface.cc @@ -0,0 +1,11 @@ +// Copyright 2016 The Chromium 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 "flutter/vulkan/vulkan_native_surface.h" + +namespace vulkan { + +// + +} // namespace vulkan diff --git a/engine/src/flutter/vulkan/vulkan_native_surface.h b/engine/src/flutter/vulkan/vulkan_native_surface.h new file mode 100644 index 0000000000..a1142ddc8f --- /dev/null +++ b/engine/src/flutter/vulkan/vulkan_native_surface.h @@ -0,0 +1,32 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_VULKAN_VULKAN_NATIVE_SURFACE_H_ +#define FLUTTER_VULKAN_VULKAN_NATIVE_SURFACE_H_ + +#include "lib/ftl/macros.h" +#include "third_party/skia/include/core/SkSize.h" +#include "vulkan_handle.h" +#include "vulkan_proc_table.h" + +namespace vulkan { + +class VulkanNativeSurface { + public: + virtual const char* GetExtensionName() const = 0; + + virtual uint32_t GetSkiaExtensionName() const = 0; + + virtual VkSurfaceKHR CreateSurfaceHandle( + VulkanProcTable& vk, + const VulkanHandle& instance) const = 0; + + virtual bool IsValid() const = 0; + + virtual SkISize GetSize() const = 0; +}; + +} // namespace vulkan + +#endif // FLUTTER_VULKAN_VULKAN_NATIVE_SURFACE_H_ diff --git a/engine/src/flutter/vulkan/vulkan_native_surface_android.cc b/engine/src/flutter/vulkan/vulkan_native_surface_android.cc new file mode 100644 index 0000000000..f635f60b7d --- /dev/null +++ b/engine/src/flutter/vulkan/vulkan_native_surface_android.cc @@ -0,0 +1,70 @@ +// Copyright 2016 The Chromium 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 "flutter/vulkan/vulkan_native_surface_android.h" + +#include "third_party/skia/include/gpu/vk/GrVkBackendContext.h" + +namespace vulkan { + +VulkanNativeSurfaceAndroid::VulkanNativeSurfaceAndroid( + ANativeWindow* native_window) + : native_window_(native_window) { + if (native_window_ == nullptr) { + return; + } + ANativeWindow_acquire(native_window_); +} + +VulkanNativeSurfaceAndroid::~VulkanNativeSurfaceAndroid() { + if (native_window_ == nullptr) { + return; + } + ANativeWindow_release(native_window_); +} + +const char* VulkanNativeSurfaceAndroid::GetExtensionName() const { + return VK_KHR_ANDROID_SURFACE_EXTENSION_NAME; +} + +uint32_t VulkanNativeSurfaceAndroid::GetSkiaExtensionName() const { + return kKHR_android_surface_GrVkExtensionFlag; +} + +VkSurfaceKHR VulkanNativeSurfaceAndroid::CreateSurfaceHandle( + VulkanProcTable& vk, + const VulkanHandle& instance) const { + if (!vk.IsValid() || !instance) { + return VK_NULL_HANDLE; + } + + const VkAndroidSurfaceCreateInfoKHR create_info = { + .sType = VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR, + .pNext = nullptr, + .flags = 0, + .window = native_window_, + }; + + VkSurfaceKHR surface = VK_NULL_HANDLE; + + if (VK_CALL_LOG_ERROR(vk.CreateAndroidSurfaceKHR( + instance, &create_info, nullptr, &surface)) != VK_SUCCESS) { + return VK_NULL_HANDLE; + } + + return surface; +} + +bool VulkanNativeSurfaceAndroid::IsValid() const { + return native_window_ != nullptr; +} + +SkISize VulkanNativeSurfaceAndroid::GetSize() const { + return native_window_ == nullptr + ? SkISize::Make(0, 0) + : SkISize::Make(ANativeWindow_getWidth(native_window_), + ANativeWindow_getHeight(native_window_)); +} + +} // namespace vulkan diff --git a/engine/src/flutter/vulkan/vulkan_native_surface_android.h b/engine/src/flutter/vulkan/vulkan_native_surface_android.h new file mode 100644 index 0000000000..260dadea62 --- /dev/null +++ b/engine/src/flutter/vulkan/vulkan_native_surface_android.h @@ -0,0 +1,44 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_VULKAN_VULKAN_NATIVE_SURFACE_ANDROID_H_ +#define FLUTTER_VULKAN_VULKAN_NATIVE_SURFACE_ANDROID_H_ + +#include "flutter/vulkan/vulkan_native_surface.h" +#include "lib/ftl/macros.h" + +struct ANativeWindow; +typedef struct ANativeWindow ANativeWindow; + +namespace vulkan { + +class VulkanNativeSurfaceAndroid : public VulkanNativeSurface { + public: + /// Create a native surface from the valid ANativeWindow reference. Ownership + /// of the ANativeWindow is assumed by this instance. + VulkanNativeSurfaceAndroid(ANativeWindow* native_window); + + ~VulkanNativeSurfaceAndroid(); + + const char* GetExtensionName() const override; + + uint32_t GetSkiaExtensionName() const override; + + VkSurfaceKHR CreateSurfaceHandle( + VulkanProcTable& vk, + const VulkanHandle& instance) const override; + + bool IsValid() const override; + + SkISize GetSize() const override; + + private: + ANativeWindow* native_window_; + + FTL_DISALLOW_COPY_AND_ASSIGN(VulkanNativeSurfaceAndroid); +}; + +} // namespace vulkan + +#endif // FLUTTER_VULKAN_VULKAN_NATIVE_SURFACE_ANDROID_H_ diff --git a/engine/src/flutter/vulkan/vulkan_native_surface_magma.cc b/engine/src/flutter/vulkan/vulkan_native_surface_magma.cc new file mode 100644 index 0000000000..8637f232eb --- /dev/null +++ b/engine/src/flutter/vulkan/vulkan_native_surface_magma.cc @@ -0,0 +1,57 @@ +// Copyright 2017 The Chromium 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 "flutter/vulkan/vulkan_native_surface_magma.h" + +namespace vulkan { + +VulkanNativeSurfaceMagma::VulkanNativeSurfaceMagma() = default; + +VulkanNativeSurfaceMagma::~VulkanNativeSurfaceMagma() = default; + +const char* VulkanNativeSurfaceMagma::GetExtensionName() const { + return VK_KHR_MAGMA_SURFACE_EXTENSION_NAME; +} + +uint32_t VulkanNativeSurfaceMagma::GetSkiaExtensionName() const { + // There is no counterpart in Skia that recognizes the Magma extension name. + // However, Flutter handles all setup anyway, so this is unnecessary. + return 0; +} + +VkSurfaceKHR VulkanNativeSurfaceMagma::CreateSurfaceHandle( + vulkan::VulkanProcTable& vk, + const vulkan::VulkanHandle& instance) const { + if (!vk.IsValid() || !instance) { + return VK_NULL_HANDLE; + } + + const VkMagmaSurfaceCreateInfoKHR create_info = { + .sType = VK_STRUCTURE_TYPE_MAGMA_SURFACE_CREATE_INFO_KHR, + .pNext = nullptr, + }; + + VkSurfaceKHR surface = VK_NULL_HANDLE; + + if (VK_CALL_LOG_ERROR(vk.CreateMagmaSurfaceKHR( + instance, &create_info, nullptr /* allocator */, &surface)) != + VK_SUCCESS) { + return VK_NULL_HANDLE; + } + + return surface; +} + +bool VulkanNativeSurfaceMagma::IsValid() const { + // vkCreateMagmaSurfaceKHR doesn't actually take a native handle. So there is + // nothing to check the validity of. + return true; +} + +SkISize VulkanNativeSurfaceMagma::GetSize() const { + // See comment in VulkanWindow::AcquireSurface. + return SkISize::Make(0, 0); +} + +} // namespace vulkan diff --git a/engine/src/flutter/vulkan/vulkan_native_surface_magma.h b/engine/src/flutter/vulkan/vulkan_native_surface_magma.h new file mode 100644 index 0000000000..43cb1587b9 --- /dev/null +++ b/engine/src/flutter/vulkan/vulkan_native_surface_magma.h @@ -0,0 +1,37 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_VULKAN_VULKAN_NATIVE_SURFACE_MAGMA_H_ +#define FLUTTER_VULKAN_VULKAN_NATIVE_SURFACE_MAGMA_H_ + +#include "flutter/vulkan/vulkan_native_surface.h" +#include "lib/ftl/macros.h" + +namespace vulkan { + +class VulkanNativeSurfaceMagma : public vulkan::VulkanNativeSurface { + public: + VulkanNativeSurfaceMagma(); + + ~VulkanNativeSurfaceMagma(); + + const char* GetExtensionName() const override; + + uint32_t GetSkiaExtensionName() const override; + + VkSurfaceKHR CreateSurfaceHandle( + vulkan::VulkanProcTable& vk, + const vulkan::VulkanHandle& instance) const override; + + bool IsValid() const override; + + SkISize GetSize() const override; + + private: + FTL_DISALLOW_COPY_AND_ASSIGN(VulkanNativeSurfaceMagma); +}; + +} // namespace vulkan + +#endif // FLUTTER_VULKAN_VULKAN_NATIVE_SURFACE_MAGMA_H_ diff --git a/engine/src/flutter/vulkan/vulkan_proc_table.cc b/engine/src/flutter/vulkan/vulkan_proc_table.cc index ac7db27e81..5b6a3edc7f 100644 --- a/engine/src/flutter/vulkan/vulkan_proc_table.cc +++ b/engine/src/flutter/vulkan/vulkan_proc_table.cc @@ -2,44 +2,163 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "vulkan_proc_table.h" -#include "lib/ftl/logging.h" +#include "flutter/vulkan/vulkan_proc_table.h" #include +#include "lib/ftl/logging.h" + +#define ACQUIRE_PROC(name, context) \ + if (!(name = AcquireProc("vk" #name, context))) { \ + FTL_DLOG(INFO) << "Could not acquire proc: vk" << #name; \ + return false; \ + } + namespace vulkan { -VulkanProcTable::VulkanProcTable() : valid_(false), handle_(nullptr) { - if (!OpenLibraryHandle()) { - return; - } - - if (!AcquireProcs()) { - return; - } - - valid_ = true; +VulkanProcTable::VulkanProcTable() + : handle_(nullptr), acquired_mandatory_proc_addresses_(false) { + acquired_mandatory_proc_addresses_ = + OpenLibraryHandle() && SetupLoaderProcAddresses(); } VulkanProcTable::~VulkanProcTable() { CloseLibraryHandle(); } +bool VulkanProcTable::HasAcquiredMandatoryProcAddresses() const { + return acquired_mandatory_proc_addresses_; +} + bool VulkanProcTable::IsValid() const { - return valid_; + return instance_ && device_; +} + +bool VulkanProcTable::AreInstanceProcsSetup() const { + return instance_; +} + +bool VulkanProcTable::AreDeviceProcsSetup() const { + return device_; +} + +bool VulkanProcTable::SetupLoaderProcAddresses() { + if (handle_ == nullptr) { + return true; + } + + GetInstanceProcAddr = +#if VULKAN_LINK_STATICALLY + GetInstanceProcAddr = &vkGetInstanceProcAddr; +#else // VULKAN_LINK_STATICALLY + reinterpret_cast( + dlsym(handle_, "vkGetInstanceProcAddr")); +#endif // VULKAN_LINK_STATICALLY + + if (!GetInstanceProcAddr) { + FTL_DLOG(WARNING) << "Could not acquire vkGetInstanceProcAddr."; + return false; + } + + VulkanHandle null_instance(VK_NULL_HANDLE, nullptr); + + ACQUIRE_PROC(CreateInstance, null_instance); + ACQUIRE_PROC(EnumerateInstanceExtensionProperties, null_instance); + ACQUIRE_PROC(EnumerateInstanceLayerProperties, null_instance); + + return true; +} + +bool VulkanProcTable::SetupInstanceProcAddresses( + const VulkanHandle& handle) { + ACQUIRE_PROC(CreateDevice, handle); + ACQUIRE_PROC(DestroyDevice, handle); + ACQUIRE_PROC(DestroyInstance, handle); + ACQUIRE_PROC(EnumerateDeviceLayerProperties, handle); + ACQUIRE_PROC(EnumeratePhysicalDevices, handle); + ACQUIRE_PROC(GetPhysicalDeviceFeatures, handle); + ACQUIRE_PROC(GetPhysicalDeviceQueueFamilyProperties, handle); + ACQUIRE_PROC(GetPhysicalDeviceSurfaceCapabilitiesKHR, handle); + ACQUIRE_PROC(GetPhysicalDeviceSurfaceFormatsKHR, handle); + ACQUIRE_PROC(GetPhysicalDeviceSurfacePresentModesKHR, handle); + ACQUIRE_PROC(GetPhysicalDeviceSurfaceSupportKHR, handle); + ACQUIRE_PROC(GetDeviceProcAddr, handle); + ACQUIRE_PROC(DestroySurfaceKHR, handle); + +#if OS_ANDROID + ACQUIRE_PROC(CreateAndroidSurfaceKHR, handle); +#endif // OS_ANDROID + +#if OS_FUCHSIA + ACQUIRE_PROC(CreateMagmaSurfaceKHR, handle); + ACQUIRE_PROC(GetPhysicalDeviceMagmaPresentationSupportKHR, handle); +#endif // OS_FUCHSIA + + // The debug report functions are optional. We don't want proc acquisition to + // fail here because the optional methods were not present (since ACQUIRE_PROC + // returns false on failure). Wrap the optional proc acquisitions in an + // anonymous lambda and invoke it. We don't really care about the result since + // users of Debug reporting functions check for their presence explicitly. + [this, &handle]() -> bool { + ACQUIRE_PROC(CreateDebugReportCallbackEXT, handle); + ACQUIRE_PROC(DestroyDebugReportCallbackEXT, handle); + return true; + }(); + + instance_ = {handle, nullptr}; + return true; +} + +bool VulkanProcTable::SetupDeviceProcAddresses( + const VulkanHandle& handle) { + ACQUIRE_PROC(AcquireNextImageKHR, handle); + ACQUIRE_PROC(CreateSwapchainKHR, handle); + ACQUIRE_PROC(DestroySwapchainKHR, handle); + ACQUIRE_PROC(GetSwapchainImagesKHR, handle); + ACQUIRE_PROC(QueuePresentKHR, handle); + ACQUIRE_PROC(AllocateCommandBuffers, handle); + ACQUIRE_PROC(BeginCommandBuffer, handle); + ACQUIRE_PROC(CmdPipelineBarrier, handle); + ACQUIRE_PROC(CreateCommandPool, handle); + ACQUIRE_PROC(CreateFence, handle); + ACQUIRE_PROC(CreateSemaphore, handle); + ACQUIRE_PROC(DestroyCommandPool, handle); + ACQUIRE_PROC(DestroyFence, handle); + ACQUIRE_PROC(DestroySemaphore, handle); + ACQUIRE_PROC(DeviceWaitIdle, handle); + ACQUIRE_PROC(EndCommandBuffer, handle); + ACQUIRE_PROC(FreeCommandBuffers, handle); + ACQUIRE_PROC(GetDeviceQueue, handle); + ACQUIRE_PROC(QueueSubmit, handle); + ACQUIRE_PROC(ResetCommandBuffer, handle); + ACQUIRE_PROC(ResetFences, handle); + ACQUIRE_PROC(WaitForFences, handle); + + device_ = {handle, nullptr}; + return true; } bool VulkanProcTable::OpenLibraryHandle() { +#if VULKAN_LINK_STATICALLY + static char kDummyLibraryHandle = '\0'; + handle_ = reinterpret_cast(&kDummyLibraryHandle); + return true; +#else // VULKAN_LINK_STATICALLY dlerror(); // clear existing errors on thread. - handle_ = dlopen("libvulkan.so", RTLD_NOW); + handle_ = dlopen("libvulkan.so", RTLD_NOW | RTLD_LOCAL); if (handle_ == nullptr) { FTL_DLOG(WARNING) << "Could not open the vulkan library: " << dlerror(); return false; } return true; +#endif // VULKAN_LINK_STATICALLY } bool VulkanProcTable::CloseLibraryHandle() { +#if VULKAN_LINK_STATICALLY + handle_ = nullptr; + return true; +#else if (handle_ != nullptr) { dlerror(); // clear existing errors on thread. if (dlclose(handle_) != 0) { @@ -49,54 +168,50 @@ bool VulkanProcTable::CloseLibraryHandle() { } handle_ = nullptr; } - return handle_ == nullptr; +#endif } -bool VulkanProcTable::AcquireProcs() { - if (handle_ == nullptr) { - return false; +PFN_vkVoidFunction VulkanProcTable::AcquireProc( + const char* proc_name, + const VulkanHandle& instance) const { + if (proc_name == nullptr || !GetInstanceProcAddr) { + return nullptr; } -#define ACQUIRE_PROC(symbol, name) \ - if (!(symbol = reinterpret_cast( \ - dlsym(handle_, name)))) { \ - FTL_DLOG(WARNING) << "Could not acquire proc for function " << name; \ - return false; \ + // A VK_NULL_HANDLE as the instance is an acceptable parameter. + return GetInstanceProcAddr(instance, proc_name); +} + +PFN_vkVoidFunction VulkanProcTable::AcquireProc( + const char* proc_name, + const VulkanHandle& device) const { + if (proc_name == nullptr || !device || !GetDeviceProcAddr) { + return nullptr; } - ACQUIRE_PROC(createInstance, "vkCreateInstance"); - ACQUIRE_PROC(destroyInstance, "vkDestroyInstance"); - ACQUIRE_PROC(enumeratePhysicalDevices, "vkEnumeratePhysicalDevices"); - ACQUIRE_PROC(createDevice, "vkCreateDevice"); - ACQUIRE_PROC(destroyDevice, "vkDestroyDevice"); - ACQUIRE_PROC(getDeviceQueue, "vkGetDeviceQueue"); - ACQUIRE_PROC(getPhysicalDeviceSurfaceCapabilitiesKHR, - "vkGetPhysicalDeviceSurfaceCapabilitiesKHR"); - ACQUIRE_PROC(getPhysicalDeviceSurfaceFormatsKHR, - "vkGetPhysicalDeviceSurfaceFormatsKHR"); - ACQUIRE_PROC(createSwapchainKHR, "vkCreateSwapchainKHR"); - ACQUIRE_PROC(getSwapchainImagesKHR, "vkGetSwapchainImagesKHR"); - ACQUIRE_PROC(getPhysicalDeviceSurfacePresentModesKHR, - "vkGetPhysicalDeviceSurfacePresentModesKHR"); - ACQUIRE_PROC(destroySurfaceKHR, "vkDestroySurfaceKHR"); - ACQUIRE_PROC(createCommandPool, "vkCreateCommandPool"); - ACQUIRE_PROC(destroyCommandPool, "vkDestroyCommandPool"); - ACQUIRE_PROC(createSemaphore, "vkCreateSemaphore"); - ACQUIRE_PROC(destroySemaphore, "vkDestroySemaphore"); - ACQUIRE_PROC(allocateCommandBuffers, "vkAllocateCommandBuffers"); - ACQUIRE_PROC(freeCommandBuffers, "vkFreeCommandBuffers"); - ACQUIRE_PROC(createFence, "vkCreateFence"); - ACQUIRE_PROC(destroyFence, "vkDestroyFence"); - ACQUIRE_PROC(waitForFences, "vkWaitForFences"); + return GetDeviceProcAddr(device, proc_name); +} -#if OS_ANDROID - ACQUIRE_PROC(createAndroidSurfaceKHR, "vkCreateAndroidSurfaceKHR"); -#endif // OS_ANDROID +sk_sp VulkanProcTable::CreateSkiaInterface() const { + if (!IsValid()) { + return nullptr; + } -#undef ACQUIRE_PROC + GrVkInterface::GetProc proc = [this](const char* proc_name, + VkInstance instance, VkDevice device) { + if (device != VK_NULL_HANDLE) { + auto result = AcquireProc(proc_name, {device, nullptr}); + if (result != nullptr) { + return result; + } + } - return true; + return AcquireProc(proc_name, {instance, nullptr}); + }; + + return sk_make_sp(proc, instance_, device_, + 0 /* extensions */); } } // namespace vulkan diff --git a/engine/src/flutter/vulkan/vulkan_proc_table.h b/engine/src/flutter/vulkan/vulkan_proc_table.h index 0e5d8078fe..039929880e 100644 --- a/engine/src/flutter/vulkan/vulkan_proc_table.h +++ b/engine/src/flutter/vulkan/vulkan_proc_table.h @@ -5,12 +5,20 @@ #ifndef FLUTTER_VULKAN_VULKAN_PROC_TABLE_H_ #define FLUTTER_VULKAN_VULKAN_PROC_TABLE_H_ +#include "flutter/vulkan/vulkan_handle.h" +#include "flutter/vulkan/vulkan_interface.h" #include "lib/ftl/macros.h" -#include "vulkan_interface.h" +#include "lib/ftl/memory/ref_counted.h" +#include "lib/ftl/memory/ref_ptr.h" +#include "third_party/skia/include/core/SkRefCnt.h" +#include "third_party/skia/include/gpu/vk/GrVkInterface.h" namespace vulkan { -class VulkanProcTable { +class VulkanProcTable : public ftl::RefCountedThreadSafe { + FRIEND_REF_COUNTED_THREAD_SAFE(VulkanProcTable); + FRIEND_MAKE_REF_COUNTED(VulkanProcTable); + public: template class Proc { @@ -26,6 +34,11 @@ class VulkanProcTable { return *this; } + Proc operator=(PFN_vkVoidFunction proc) { + proc_ = reinterpret_cast(proc); + return *this; + } + operator bool() const { return proc_ != nullptr; } operator T() const { return proc_; } @@ -34,49 +47,89 @@ class VulkanProcTable { T proc_; }; - VulkanProcTable(); - - ~VulkanProcTable(); + bool HasAcquiredMandatoryProcAddresses() const; bool IsValid() const; - Proc createInstance; - Proc destroyInstance; - Proc enumeratePhysicalDevices; - Proc createDevice; - Proc destroyDevice; - Proc getDeviceQueue; - Proc - getPhysicalDeviceSurfaceCapabilitiesKHR; - Proc - getPhysicalDeviceSurfaceFormatsKHR; - Proc createSwapchainKHR; - Proc getSwapchainImagesKHR; - Proc - getPhysicalDeviceSurfacePresentModesKHR; - Proc destroySurfaceKHR; - Proc destroySwapchainKHR; - Proc createCommandPool; - Proc destroyCommandPool; - Proc createSemaphore; - Proc destroySemaphore; - Proc allocateCommandBuffers; - Proc freeCommandBuffers; - Proc createFence; - Proc destroyFence; - Proc waitForFences; + bool AreInstanceProcsSetup() const; + bool AreDeviceProcsSetup() const; + + bool SetupInstanceProcAddresses(const VulkanHandle& instance); + + bool SetupDeviceProcAddresses(const VulkanHandle& device); + + sk_sp CreateSkiaInterface() const; + +#define DEFINE_PROC(name) Proc name; + + DEFINE_PROC(AcquireNextImageKHR); + DEFINE_PROC(AllocateCommandBuffers); + DEFINE_PROC(BeginCommandBuffer); + DEFINE_PROC(CmdPipelineBarrier); + DEFINE_PROC(CreateCommandPool); + DEFINE_PROC(CreateDebugReportCallbackEXT); + DEFINE_PROC(CreateDevice); + DEFINE_PROC(CreateFence); + DEFINE_PROC(CreateInstance); + DEFINE_PROC(CreateSemaphore); + DEFINE_PROC(CreateSwapchainKHR); + DEFINE_PROC(DestroyCommandPool); + DEFINE_PROC(DestroyDebugReportCallbackEXT); + DEFINE_PROC(DestroyDevice); + DEFINE_PROC(DestroyFence); + DEFINE_PROC(DestroyInstance); + DEFINE_PROC(DestroySemaphore); + DEFINE_PROC(DestroySurfaceKHR); + DEFINE_PROC(DestroySwapchainKHR); + DEFINE_PROC(DeviceWaitIdle); + DEFINE_PROC(EndCommandBuffer); + DEFINE_PROC(EnumerateDeviceLayerProperties); + DEFINE_PROC(EnumerateInstanceExtensionProperties); + DEFINE_PROC(EnumerateInstanceLayerProperties); + DEFINE_PROC(EnumeratePhysicalDevices); + DEFINE_PROC(FreeCommandBuffers); + DEFINE_PROC(GetDeviceProcAddr); + DEFINE_PROC(GetDeviceQueue); + DEFINE_PROC(GetInstanceProcAddr); + DEFINE_PROC(GetPhysicalDeviceFeatures); + DEFINE_PROC(GetPhysicalDeviceQueueFamilyProperties); + DEFINE_PROC(GetPhysicalDeviceSurfaceCapabilitiesKHR); + DEFINE_PROC(GetPhysicalDeviceSurfaceFormatsKHR); + DEFINE_PROC(GetPhysicalDeviceSurfacePresentModesKHR); + DEFINE_PROC(GetSwapchainImagesKHR); + DEFINE_PROC(QueuePresentKHR); + DEFINE_PROC(QueueSubmit); + DEFINE_PROC(ResetCommandBuffer); + DEFINE_PROC(ResetFences); + DEFINE_PROC(WaitForFences); + DEFINE_PROC(GetPhysicalDeviceSurfaceSupportKHR); #if OS_ANDROID - Proc createAndroidSurfaceKHR; + DEFINE_PROC(CreateAndroidSurfaceKHR); #endif // OS_ANDROID +#if OS_FUCHSIA + DEFINE_PROC(CreateMagmaSurfaceKHR); + DEFINE_PROC(GetPhysicalDeviceMagmaPresentationSupportKHR); +#endif // OS_FUCHSIA + +#undef DEFINE_PROC private: - bool valid_; void* handle_; + bool acquired_mandatory_proc_addresses_; + VulkanHandle instance_; + VulkanHandle device_; + VulkanProcTable(); + ~VulkanProcTable(); bool OpenLibraryHandle(); + bool SetupLoaderProcAddresses(); bool CloseLibraryHandle(); - bool AcquireProcs(); + PFN_vkVoidFunction AcquireProc( + const char* proc_name, + const VulkanHandle& instance) const; + PFN_vkVoidFunction AcquireProc(const char* proc_name, + const VulkanHandle& device) const; FTL_DISALLOW_COPY_AND_ASSIGN(VulkanProcTable); }; diff --git a/engine/src/flutter/vulkan/vulkan_surface.cc b/engine/src/flutter/vulkan/vulkan_surface.cc index 6979620d42..a7af646cf0 100644 --- a/engine/src/flutter/vulkan/vulkan_surface.cc +++ b/engine/src/flutter/vulkan/vulkan_surface.cc @@ -2,12 +2,58 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "vulkan_surface.h" +#include "flutter/vulkan/vulkan_surface.h" + +#include "flutter/vulkan/vulkan_application.h" +#include "flutter/vulkan/vulkan_native_surface.h" namespace vulkan { -VulkanSurface::VulkanSurface() = default; +VulkanSurface::VulkanSurface( + VulkanProcTable& p_vk, + VulkanApplication& application, + std::unique_ptr native_surface) + : vk(p_vk), + application_(application), + native_surface_(std::move(native_surface)), + valid_(false) { + if (native_surface_ == nullptr || !native_surface_->IsValid()) { + FTL_DLOG(INFO) << "Native surface was invalid."; + return; + } + + VkSurfaceKHR surface = + native_surface_->CreateSurfaceHandle(vk, application.GetInstance()); + + if (surface == VK_NULL_HANDLE) { + FTL_DLOG(INFO) << "Could not create the surface handle."; + return; + } + + surface_ = {surface, [this](VkSurfaceKHR surface) { + vk.DestroySurfaceKHR(application_.GetInstance(), surface, + nullptr); + }}; + + valid_ = true; +} VulkanSurface::~VulkanSurface() = default; +bool VulkanSurface::IsValid() const { + return valid_; +} + +const VulkanHandle& VulkanSurface::Handle() const { + return surface_; +} + +const VulkanNativeSurface& VulkanSurface::GetNativeSurface() const { + return *native_surface_; +} + +SkISize VulkanSurface::GetSize() const { + return valid_ ? native_surface_->GetSize() : SkISize::Make(0, 0); +} + } // namespace vulkan diff --git a/engine/src/flutter/vulkan/vulkan_surface.h b/engine/src/flutter/vulkan/vulkan_surface.h index 9999ca4796..de6ed193ac 100644 --- a/engine/src/flutter/vulkan/vulkan_surface.h +++ b/engine/src/flutter/vulkan/vulkan_surface.h @@ -5,27 +5,40 @@ #ifndef FLUTTER_VULKAN_VULKAN_SURFACE_H_ #define FLUTTER_VULKAN_VULKAN_SURFACE_H_ +#include "flutter/vulkan/vulkan_handle.h" #include "lib/ftl/macros.h" -#include "vulkan_handle.h" -#include "vulkan_proc_table.h" +#include "third_party/skia/include/core/SkSize.h" namespace vulkan { +class VulkanProcTable; +class VulkanApplication; +class VulkanNativeSurface; + class VulkanSurface { public: - VulkanSurface(); + VulkanSurface(VulkanProcTable& vk, + VulkanApplication& application, + std::unique_ptr native_surface); - virtual ~VulkanSurface(); + ~VulkanSurface(); - virtual const char* ExtensionName() = 0; + bool IsValid() const; - virtual VkSurfaceKHR CreateSurfaceHandle( - VulkanProcTable& vk, - VulkanHandle& instance) = 0; + /// Returns the current size of the surface or (0, 0) if invalid. + SkISize GetSize() const; - virtual bool IsValid() const = 0; + const VulkanHandle& Handle() const; + + const VulkanNativeSurface& GetNativeSurface() const; private: + VulkanProcTable& vk; + VulkanApplication& application_; + std::unique_ptr native_surface_; + VulkanHandle surface_; + bool valid_; + FTL_DISALLOW_COPY_AND_ASSIGN(VulkanSurface); }; diff --git a/engine/src/flutter/vulkan/vulkan_surface_android.cc b/engine/src/flutter/vulkan/vulkan_surface_android.cc deleted file mode 100644 index 2a7c4e6c2f..0000000000 --- a/engine/src/flutter/vulkan/vulkan_surface_android.cc +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2016 The Chromium 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 "vulkan_surface_android.h" - -namespace vulkan { - -VulkanSurfaceAndroid::VulkanSurfaceAndroid(ANativeWindow* native_window) - : native_window_(native_window) { - if (native_window_ == nullptr) { - return; - } - ANativeWindow_acquire(native_window_); -} - -VulkanSurfaceAndroid::~VulkanSurfaceAndroid() { - if (native_window_ == nullptr) { - return; - } - ANativeWindow_release(native_window_); -} - -const char* VulkanSurfaceAndroid::ExtensionName() { - return VK_KHR_ANDROID_SURFACE_EXTENSION_NAME; -} - -VkSurfaceKHR VulkanSurfaceAndroid::CreateSurfaceHandle( - VulkanProcTable& vk, - VulkanHandle& instance) { - if (!vk.IsValid() || !instance) { - return VK_NULL_HANDLE; - } - - const VkAndroidSurfaceCreateInfoKHR create_info = { - .sType = VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR, - .pNext = nullptr, - .flags = 0, - .window = native_window_, - }; - - VkSurfaceKHR surface = VK_NULL_HANDLE; - - if (vk.createAndroidSurfaceKHR(instance, &create_info, nullptr, &surface) != - VK_SUCCESS) { - return VK_NULL_HANDLE; - } - - return surface; -} - -bool VulkanSurfaceAndroid::IsValid() const { - return native_window_ != nullptr; -} - -} // namespace vulkan diff --git a/engine/src/flutter/vulkan/vulkan_surface_android.h b/engine/src/flutter/vulkan/vulkan_surface_android.h deleted file mode 100644 index 9370f31df8..0000000000 --- a/engine/src/flutter/vulkan/vulkan_surface_android.h +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef FLUTTER_VULKAN_VULKAN_SURFACE_ANDROID_H_ -#define FLUTTER_VULKAN_VULKAN_SURFACE_ANDROID_H_ - -#include "lib/ftl/macros.h" -#include "vulkan_surface.h" - -struct ANativeWindow; -typedef struct ANativeWindow ANativeWindow; - -namespace vulkan { - -class VulkanSurfaceAndroid : public VulkanSurface { - public: - VulkanSurfaceAndroid(ANativeWindow* native_window); - - ~VulkanSurfaceAndroid() override; - - const char* ExtensionName() override; - - VkSurfaceKHR CreateSurfaceHandle(VulkanProcTable& vk, - VulkanHandle& instance) override; - - bool IsValid() const override; - - private: - ANativeWindow* native_window_; - - FTL_DISALLOW_COPY_AND_ASSIGN(VulkanSurfaceAndroid); -}; - -} // namespace vulkan - -#endif // FLUTTER_VULKAN_VULKAN_SURFACE_ANDROID_H_ diff --git a/engine/src/flutter/vulkan/vulkan_swapchain.cc b/engine/src/flutter/vulkan/vulkan_swapchain.cc new file mode 100644 index 0000000000..a42d3fe2e4 --- /dev/null +++ b/engine/src/flutter/vulkan/vulkan_swapchain.cc @@ -0,0 +1,549 @@ +// Copyright 2016 The Chromium 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 "flutter/vulkan/vulkan_swapchain.h" + +#include "flutter/vulkan/vulkan_backbuffer.h" +#include "flutter/vulkan/vulkan_device.h" +#include "flutter/vulkan/vulkan_image.h" +#include "flutter/vulkan/vulkan_proc_table.h" +#include "flutter/vulkan/vulkan_surface.h" +#include "third_party/skia/include/gpu/vk/GrVkTypes.h" +#include "third_party/skia/src/gpu/vk/GrVkUtil.h" + +namespace vulkan { + +VulkanSwapchain::VulkanSwapchain(const VulkanProcTable& p_vk, + const VulkanDevice& device, + const VulkanSurface& surface, + GrContext* skia_context, + std::unique_ptr old_swapchain, + uint32_t queue_family_index) + : vk(p_vk), + device_(device), + capabilities_(), + surface_format_(), + current_pipeline_stage_(VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT), + current_backbuffer_index_(0), + current_image_index_(0), + valid_(false) { + if (!device_.IsValid() || !surface.IsValid() || skia_context == nullptr) { + FTL_DLOG(INFO) << "Device or surface is invalid."; + return; + } + + if (!device_.GetSurfaceCapabilities(surface, &capabilities_)) { + FTL_DLOG(INFO) << "Could not find surface capabilities."; + return; + } + + if (!device_.ChooseSurfaceFormat(surface, &surface_format_)) { + FTL_DLOG(INFO) << "Could not choose surface format."; + return; + } + + VkPresentModeKHR present_mode = VK_PRESENT_MODE_FIFO_KHR; + if (!device_.ChoosePresentMode(surface, &present_mode)) { + FTL_DLOG(INFO) << "Could not choose present mode."; + return; + } + + // Check if the surface can present. + + VkBool32 supported = VK_FALSE; + if (VK_CALL_LOG_ERROR(vk.GetPhysicalDeviceSurfaceSupportKHR( + device_.GetPhysicalDeviceHandle(), // physical device + queue_family_index, // queue family + surface.Handle(), // surface to test + &supported)) != VK_SUCCESS) { + FTL_DLOG(INFO) << "Could not get physical device surface support."; + return; + } + + if (supported != VK_TRUE) { + FTL_DLOG(INFO) << "Surface was not supported by the physical device."; + return; + } + + // Construct the Swapchain + + VkSwapchainKHR old_swapchain_handle = VK_NULL_HANDLE; + + if (old_swapchain != nullptr && old_swapchain->IsValid()) { + old_swapchain_handle = old_swapchain->swapchain_; + // The unique pointer to the swapchain will go out of scope here + // and its handle collected after the appropriate device wait. + } + + VkSurfaceKHR surface_handle = surface.Handle(); + + const VkSwapchainCreateInfoKHR create_info = { + .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR, + .pNext = nullptr, + .flags = 0, + .surface = surface_handle, + .minImageCount = capabilities_.minImageCount, + .imageFormat = surface_format_.format, + .imageColorSpace = surface_format_.colorSpace, + .imageExtent = capabilities_.currentExtent, + .imageArrayLayers = 1, + .imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, + .imageSharingMode = VK_SHARING_MODE_EXCLUSIVE, + .queueFamilyIndexCount = 0, // Because of the exclusive sharing mode. + .pQueueFamilyIndices = nullptr, + .preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR, + .compositeAlpha = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR, + .presentMode = present_mode, + .clipped = VK_FALSE, + .oldSwapchain = old_swapchain_handle, + }; + + VkSwapchainKHR swapchain = VK_NULL_HANDLE; + + if (VK_CALL_LOG_ERROR(vk.CreateSwapchainKHR(device_.GetHandle(), &create_info, + nullptr, &swapchain)) != + VK_SUCCESS) { + FTL_DLOG(INFO) << "Could not create the swapchain."; + return; + } + + swapchain_ = {swapchain, [this](VkSwapchainKHR swapchain) { + FTL_ALLOW_UNUSED_LOCAL(device_.WaitIdle()); + vk.DestroySwapchainKHR(device_.GetHandle(), swapchain, + nullptr); + }}; + + if (!CreateSwapchainImages(skia_context)) { + FTL_DLOG(INFO) << "Could not create swapchain images."; + return; + } + + valid_ = true; +} + +VulkanSwapchain::~VulkanSwapchain() = default; + +bool VulkanSwapchain::IsValid() const { + return valid_; +} + +std::vector VulkanSwapchain::GetImages() const { + uint32_t count = 0; + if (VK_CALL_LOG_ERROR(vk.GetSwapchainImagesKHR( + device_.GetHandle(), swapchain_, &count, nullptr)) != VK_SUCCESS) { + return {}; + } + + if (count == 0) { + return {}; + } + + std::vector images; + + images.resize(count); + + if (VK_CALL_LOG_ERROR(vk.GetSwapchainImagesKHR( + device_.GetHandle(), swapchain_, &count, images.data())) != + VK_SUCCESS) { + return {}; + } + + return images; +} + +SkISize VulkanSwapchain::GetSize() const { + VkExtent2D extents = capabilities_.currentExtent; + + if (extents.width < capabilities_.minImageExtent.width) { + extents.width = capabilities_.minImageExtent.width; + } else if (extents.width > capabilities_.maxImageExtent.width) { + extents.width = capabilities_.maxImageExtent.width; + } + + if (extents.height < capabilities_.minImageExtent.height) { + extents.height = capabilities_.minImageExtent.height; + } else if (extents.height > capabilities_.maxImageExtent.height) { + extents.height = capabilities_.maxImageExtent.height; + } + + return SkISize::Make(extents.width, extents.height); +} + +sk_sp VulkanSwapchain::CreateSkiaSurface(GrContext* gr_context, + VkImage image, + const SkISize& size) const { + if (gr_context == nullptr) { + return nullptr; + } + + GrPixelConfig pixel_config = kUnknown_GrPixelConfig; + + if (!GrVkFormatToPixelConfig(surface_format_.format, &pixel_config)) { + // Vulkan format unsupported by Skia. + return nullptr; + } + + const GrVkImageInfo image_info = { + .fImage = image, + .fAlloc = {VK_NULL_HANDLE, 0, 0, 0}, + .fImageTiling = VK_IMAGE_TILING_OPTIMAL, + .fImageLayout = VK_IMAGE_LAYOUT_UNDEFINED, + .fFormat = surface_format_.format, + .fLevelCount = 1, + }; + + GrBackendRenderTargetDesc desc; + desc.fWidth = size.fWidth; + desc.fHeight = size.fHeight; + desc.fConfig = pixel_config; + desc.fOrigin = kTopLeft_GrSurfaceOrigin; + + // TODO(chinmaygarde): Setup the stencil buffer and the sampleCnt. + desc.fSampleCnt = 0; + desc.fStencilBits = 0; + + desc.fRenderTargetHandle = reinterpret_cast(&image_info); + + SkSurfaceProps props(SkSurfaceProps::InitType::kLegacyFontHost_InitType); + + return SkSurface::MakeFromBackendRenderTarget(gr_context, desc, &props); +} + +bool VulkanSwapchain::CreateSwapchainImages(GrContext* skia_context) { + std::vector images = GetImages(); + + if (images.size() == 0) { + return false; + } + + const SkISize surface_size = GetSize(); + + for (const VkImage& image : images) { + // Populate the backbuffer. + auto backbuffer = std::make_unique( + vk, device_.GetHandle(), device_.GetCommandPool()); + + if (!backbuffer->IsValid()) { + return false; + } + + backbuffers_.emplace_back(std::move(backbuffer)); + + // Populate the image. + auto vulkan_image = std::make_unique(image); + + if (!vulkan_image->IsValid()) { + return false; + } + + images_.emplace_back(std::move(vulkan_image)); + + // Populate the surface. + auto surface = CreateSkiaSurface(skia_context, image, surface_size); + + if (surface == nullptr) { + return false; + } + + surfaces_.emplace_back(std::move(surface)); + } + + FTL_DCHECK(backbuffers_.size() == images_.size()); + FTL_DCHECK(images_.size() == surfaces_.size()); + + return true; +} + +VulkanBackbuffer* VulkanSwapchain::GetNextBackbuffer() { + auto available_backbuffers = backbuffers_.size(); + + if (available_backbuffers == 0) { + return nullptr; + } + + auto next_backbuffer_index = + (current_backbuffer_index_ + 1) % backbuffers_.size(); + + auto& backbuffer = backbuffers_[next_backbuffer_index]; + + if (!backbuffer->IsValid()) { + return nullptr; + } + + current_backbuffer_index_ = next_backbuffer_index; + return backbuffer.get(); +} + +VulkanSwapchain::AcquireResult VulkanSwapchain::AcquireSurface() { + AcquireResult error = {AcquireStatus::ErrorSurfaceLost, nullptr}; + + if (!IsValid()) { + FTL_DLOG(INFO) << "Swapchain was invalid."; + return error; + } + + // --------------------------------------------------------------------------- + // Step 0: + // Acquire the next available backbuffer. + // --------------------------------------------------------------------------- + auto backbuffer = GetNextBackbuffer(); + + if (backbuffer == nullptr) { + FTL_DLOG(INFO) << "Could not get the next backbuffer."; + return error; + } + + // --------------------------------------------------------------------------- + // Step 1: + // Wait for use readiness. + // --------------------------------------------------------------------------- + if (!backbuffer->WaitFences()) { + FTL_DLOG(INFO) << "Failed waiting on fences."; + return error; + } + + // --------------------------------------------------------------------------- + // Step 2: + // Put semaphores in unsignaled state. + // --------------------------------------------------------------------------- + if (!backbuffer->ResetFences()) { + FTL_DLOG(INFO) << "Could not reset fences."; + return error; + } + + // --------------------------------------------------------------------------- + // Step 3: + // Acquire the next image index. + // --------------------------------------------------------------------------- + uint32_t next_image_index = 0; + + VkResult acquire_result = VK_CALL_LOG_ERROR( + vk.AcquireNextImageKHR(device_.GetHandle(), // + swapchain_, // + std::numeric_limits::max(), // + backbuffer->GetUsageSemaphore(), // + VK_NULL_HANDLE, // + &next_image_index)); + + switch (acquire_result) { + case VK_SUCCESS: + break; + case VK_ERROR_OUT_OF_DATE_KHR: + return {AcquireStatus::ErrorSurfaceOutOfDate, nullptr}; + case VK_ERROR_SURFACE_LOST_KHR: + return {AcquireStatus::ErrorSurfaceLost, nullptr}; + default: + FTL_LOG(INFO) << "Unexpected result from AcquireNextImageKHR: " + << acquire_result; + return {AcquireStatus::ErrorSurfaceLost, nullptr}; + } + + // Simple sanity checking of image index. + if (next_image_index >= images_.size()) { + FTL_DLOG(INFO) << "Image index returned was out-of-bounds."; + return error; + } + + auto& image = images_[next_image_index]; + if (!image->IsValid()) { + FTL_DLOG(INFO) << "Image at index was invalid."; + return error; + } + + // --------------------------------------------------------------------------- + // Step 4: + // Start recording to the command buffer. + // --------------------------------------------------------------------------- + if (!backbuffer->GetUsageCommandBuffer().Begin()) { + FTL_DLOG(INFO) << "Could not begin recording to the command buffer."; + return error; + } + + // --------------------------------------------------------------------------- + // Step 5: + // Set image layout to color attachment mode. + // --------------------------------------------------------------------------- + VkPipelineStageFlagBits destination_pipeline_stage = + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; + VkImageLayout destination_image_layout = + VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + + if (!image->InsertImageMemoryBarrier( + backbuffer->GetUsageCommandBuffer(), // command buffer + current_pipeline_stage_, // src_pipeline_bits + destination_pipeline_stage, // dest_pipeline_bits + VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, // dest_access_flags + destination_image_layout // dest_layout + )) { + FTL_DLOG(INFO) << "Could not insert image memory barrier."; + return error; + } else { + current_pipeline_stage_ = destination_pipeline_stage; + } + + // --------------------------------------------------------------------------- + // Step 6: + // End recording to the command buffer. + // --------------------------------------------------------------------------- + if (!backbuffer->GetUsageCommandBuffer().End()) { + FTL_DLOG(INFO) << "Could not end recording to the command buffer."; + return error; + } + + // --------------------------------------------------------------------------- + // Step 7: + // Submit the command buffer to the device queue. + // --------------------------------------------------------------------------- + std::vector wait_semaphores = {backbuffer->GetUsageSemaphore()}; + std::vector signal_semaphores = {}; + std::vector command_buffers = { + backbuffer->GetUsageCommandBuffer().Handle()}; + + if (!device_.QueueSubmit( + {destination_pipeline_stage}, // wait_dest_pipeline_stages + wait_semaphores, // wait_semaphores + signal_semaphores, // signal_semaphores + command_buffers, // command_buffers + backbuffer->GetUsageFence() // fence + )) { + FTL_DLOG(INFO) << "Could not submit to the device queue."; + return error; + } + + // --------------------------------------------------------------------------- + // Step 8: + // Tell Skia about the updated image layout. + // --------------------------------------------------------------------------- + sk_sp surface = surfaces_[next_image_index]; + + if (surface == nullptr) { + FTL_DLOG(INFO) << "Could not access surface at the image index."; + return error; + } + + GrVkImageInfo* image_info = nullptr; + if (!surface->getRenderTargetHandle( + reinterpret_cast(&image_info), + SkSurface::kFlushRead_BackendHandleAccess)) { + FTL_DLOG(INFO) << "Could not get render target handle."; + return error; + } + + image_info->updateImageLayout(destination_image_layout); + current_image_index_ = next_image_index; + + return {AcquireStatus::Success, surface}; +} + +bool VulkanSwapchain::Submit() { + if (!IsValid()) { + FTL_DLOG(INFO) << "Swapchain was invalid."; + return false; + } + + sk_sp surface = surfaces_[current_image_index_]; + const std::unique_ptr& image = images_[current_image_index_]; + auto backbuffer = backbuffers_[current_backbuffer_index_].get(); + + // --------------------------------------------------------------------------- + // Step 0: + // Notify to Skia that we will read from its backend object. + // --------------------------------------------------------------------------- + GrVkImageInfo* image_info = nullptr; + if (!surface->getRenderTargetHandle( + reinterpret_cast(&image_info), + SkSurface::kFlushRead_BackendHandleAccess)) { + FTL_DLOG(INFO) << "Could not get render target handle."; + return false; + } + + // --------------------------------------------------------------------------- + // Step 1: + // Start recording to the command buffer. + // --------------------------------------------------------------------------- + if (!backbuffer->GetRenderCommandBuffer().Begin()) { + FTL_DLOG(INFO) << "Could not start recording to the command buffer."; + return false; + } + + // --------------------------------------------------------------------------- + // Step 2: + // Set image layout to present mode. + // --------------------------------------------------------------------------- + VkPipelineStageFlagBits destination_pipeline_stage = + VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; + VkImageLayout destination_image_layout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; + + if (!image->InsertImageMemoryBarrier( + backbuffer->GetRenderCommandBuffer(), // command buffer + current_pipeline_stage_, // src_pipeline_bits + destination_pipeline_stage, // dest_pipeline_bits + VK_ACCESS_MEMORY_READ_BIT, // dest_access_flags + destination_image_layout // dest_layout + )) { + FTL_DLOG(INFO) << "Could not insert memory barrier."; + return false; + } else { + current_pipeline_stage_ = destination_pipeline_stage; + } + + // --------------------------------------------------------------------------- + // Step 3: + // End recording to the command buffer. + // --------------------------------------------------------------------------- + if (!backbuffer->GetRenderCommandBuffer().End()) { + FTL_DLOG(INFO) << "Could not end recording to the command buffer."; + return false; + } + + // --------------------------------------------------------------------------- + // Step 4: + // Submit the command buffer to the device queue. Tell it to signal the render + // semaphore. + // --------------------------------------------------------------------------- + std::vector wait_semaphores = {}; + std::vector queue_signal_semaphores = { + backbuffer->GetRenderSemaphore()}; + std::vector command_buffers = { + backbuffer->GetRenderCommandBuffer().Handle()}; + + if (!device_.QueueSubmit( + {/* Empty. No wait semaphores. */}, // wait_dest_pipeline_stages + wait_semaphores, // wait_semaphores + queue_signal_semaphores, // signal_semaphores + command_buffers, // command_buffers + backbuffer->GetRenderFence() // fence + )) { + FTL_DLOG(INFO) << "Could not submit to the device queue."; + return false; + } + + // --------------------------------------------------------------------------- + // Step 5: + // Submit the present operation and wait on the render semaphore. + // --------------------------------------------------------------------------- + VkSwapchainKHR swapchain = swapchain_; + uint32_t present_image_index = static_cast(current_image_index_); + const VkPresentInfoKHR present_info = { + .sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR, + .pNext = nullptr, + .waitSemaphoreCount = + static_cast(queue_signal_semaphores.size()), + .pWaitSemaphores = queue_signal_semaphores.data(), + .swapchainCount = 1, + .pSwapchains = &swapchain, + .pImageIndices = &present_image_index, + .pResults = nullptr, + }; + + if (VK_CALL_LOG_ERROR(vk.QueuePresentKHR(device_.GetQueueHandle(), + &present_info)) != VK_SUCCESS) { + FTL_DLOG(INFO) << "Could not submit the present operation."; + return false; + } + + return true; +} + +} // namespace vulkan diff --git a/engine/src/flutter/vulkan/vulkan_swapchain.h b/engine/src/flutter/vulkan/vulkan_swapchain.h new file mode 100644 index 0000000000..6cc2922ebd --- /dev/null +++ b/engine/src/flutter/vulkan/vulkan_swapchain.h @@ -0,0 +1,93 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_VULKAN_VULKAN_SWAPCHAIN_H_ +#define FLUTTER_VULKAN_VULKAN_SWAPCHAIN_H_ + +#include +#include +#include + +#include "flutter/vulkan/vulkan_handle.h" +#include "lib/ftl/compiler_specific.h" +#include "lib/ftl/macros.h" +#include "third_party/skia/include/core/SkSize.h" +#include "third_party/skia/include/core/SkSurface.h" + +namespace vulkan { + +class VulkanProcTable; +class VulkanDevice; +class VulkanSurface; +class VulkanBackbuffer; +class VulkanImage; + +class VulkanSwapchain { + public: + VulkanSwapchain(const VulkanProcTable& vk, + const VulkanDevice& device, + const VulkanSurface& surface, + GrContext* skia_context, + std::unique_ptr old_swapchain, + uint32_t queue_family_index); + + ~VulkanSwapchain(); + + bool IsValid() const; + + enum class AcquireStatus { + /// A valid SkSurface was acquired successfully from the swapchain. + Success, + /// The underlying surface of the swapchain was permanently lost. This is an + /// unrecoverable error. The entire surface must be recreated along with the + /// swapchain. + ErrorSurfaceLost, + /// The swapchain surface is out-of-date with the underlying surface. The + /// swapchain must be recreated. + ErrorSurfaceOutOfDate, + }; + using AcquireResult = std::pair>; + + /// Acquire an SkSurface from the swapchain for the caller to render into for + /// later submission via |Submit|. There must not be consecutive calls to + /// |AcquireFrame| without and interleaving |Submit|. + AcquireResult AcquireSurface(); + + /// Submit a previously acquired. There must not be consecutive calls to + /// |Submit| without and interleaving |AcquireFrame|. + FTL_WARN_UNUSED_RESULT + bool Submit(); + + SkISize GetSize() const; + + private: + const VulkanProcTable& vk; + const VulkanDevice& device_; + VkSurfaceCapabilitiesKHR capabilities_; + VkSurfaceFormatKHR surface_format_; + VulkanHandle swapchain_; + std::vector> backbuffers_; + std::vector> images_; + std::vector> surfaces_; + VkPipelineStageFlagBits current_pipeline_stage_; + size_t current_backbuffer_index_; + size_t current_image_index_; + bool valid_; + + std::vector GetImages() const; + + bool CreateSwapchainImages(GrContext* skia_context); + + sk_sp CreateSkiaSurface(GrContext* skia_context, + VkImage image, + const SkISize& size) const; + + VulkanBackbuffer* GetNextBackbuffer(); + + FTL_DISALLOW_COPY_AND_ASSIGN(VulkanSwapchain); +}; + +} // namespace vulkan + +#endif // FLUTTER_VULKAN_VULKAN_SWAPCHAIN_H_ diff --git a/engine/src/flutter/vulkan/vulkan_utilities.cc b/engine/src/flutter/vulkan/vulkan_utilities.cc new file mode 100644 index 0000000000..eedda2af03 --- /dev/null +++ b/engine/src/flutter/vulkan/vulkan_utilities.cc @@ -0,0 +1,100 @@ +// Copyright 2016 The Chromium 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 "flutter/vulkan/vulkan_utilities.h" + +#include +#include + +namespace vulkan { + +bool IsDebuggingEnabled() { +#if OS_FUCHSIA + return false; +#endif + +#ifndef NDEBUG + return true; +#else + return false; +#endif +} + +static std::vector InstanceOrDeviceLayersToEnable( + const VulkanProcTable& vk, + VkPhysicalDevice physical_device) { + if (!IsDebuggingEnabled()) { + return {}; + } + + // NOTE: The loader is sensitive to the ordering here. Please do not rearrange + // this list. + const std::vector candidates = { + "VK_LAYER_GOOGLE_threading", "VK_LAYER_LUNARG_parameter_validation", + "VK_LAYER_LUNARG_object_tracker", "VK_LAYER_LUNARG_core_validation", + "VK_LAYER_LUNARG_device_limits", "VK_LAYER_LUNARG_image", + "VK_LAYER_LUNARG_swapchain", "VK_LAYER_GOOGLE_unique_objects"}; + + uint32_t count = 0; + + if (physical_device == VK_NULL_HANDLE) { + if (VK_CALL_LOG_ERROR(vk.EnumerateInstanceLayerProperties( + &count, nullptr)) != VK_SUCCESS) { + return {}; + } + } else { + if (VK_CALL_LOG_ERROR(vk.EnumerateDeviceLayerProperties( + physical_device, &count, nullptr)) != VK_SUCCESS) { + return {}; + } + } + + std::vector properties; + properties.resize(count); + + if (physical_device == VK_NULL_HANDLE) { + if (VK_CALL_LOG_ERROR(vk.EnumerateInstanceLayerProperties( + &count, properties.data())) != VK_SUCCESS) { + return {}; + } + } else { + if (VK_CALL_LOG_ERROR(vk.EnumerateDeviceLayerProperties( + physical_device, &count, properties.data())) != VK_SUCCESS) { + return {}; + } + } + + std::unordered_set available_extensions; + + for (size_t i = 0; i < count; i++) { + available_extensions.emplace(properties[i].layerName); + } + + std::vector available_candidates; + + for (const auto& candidate : candidates) { + auto found = available_extensions.find(candidate); + if (found != available_extensions.end()) { + available_candidates.emplace_back(candidate); + } + } + + return available_candidates; +} + +std::vector InstanceLayersToEnable(const VulkanProcTable& vk) { + return InstanceOrDeviceLayersToEnable(vk, VK_NULL_HANDLE); +} + +std::vector DeviceLayersToEnable( + const VulkanProcTable& vk, + const VulkanHandle& physical_device) { + if (!physical_device) { + return {}; + } + + return InstanceOrDeviceLayersToEnable(vk, physical_device); +} + +} // namespace vulkan diff --git a/engine/src/flutter/vulkan/vulkan_utilities.h b/engine/src/flutter/vulkan/vulkan_utilities.h new file mode 100644 index 0000000000..cbd445202b --- /dev/null +++ b/engine/src/flutter/vulkan/vulkan_utilities.h @@ -0,0 +1,27 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_VULKAN_VULKAN_UTILITIES_H_ +#define FLUTTER_VULKAN_VULKAN_UTILITIES_H_ + +#include +#include + +#include "flutter/vulkan/vulkan_handle.h" +#include "flutter/vulkan/vulkan_proc_table.h" +#include "lib/ftl/macros.h" + +namespace vulkan { + +bool IsDebuggingEnabled(); + +std::vector InstanceLayersToEnable(const VulkanProcTable& vk); + +std::vector DeviceLayersToEnable( + const VulkanProcTable& vk, + const VulkanHandle& physical_device); + +} // namespace vulkan + +#endif // FLUTTER_VULKAN_VULKAN_UTILITIES_H_ diff --git a/engine/src/flutter/vulkan/vulkan_window.cc b/engine/src/flutter/vulkan/vulkan_window.cc index d2648592a2..141848d207 100644 --- a/engine/src/flutter/vulkan/vulkan_window.cc +++ b/engine/src/flutter/vulkan/vulkan_window.cc @@ -2,49 +2,84 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "vulkan_window.h" +#include "flutter/vulkan/vulkan_window.h" + +#include +#include + +#include "flutter/vulkan/vulkan_application.h" +#include "flutter/vulkan/vulkan_device.h" +#include "flutter/vulkan/vulkan_native_surface.h" +#include "flutter/vulkan/vulkan_surface.h" +#include "flutter/vulkan/vulkan_swapchain.h" +#include "third_party/skia/include/gpu/GrContext.h" +#include "third_party/skia/include/gpu/vk/GrVkInterface.h" namespace vulkan { -VulkanWindow::VulkanWindow(std::unique_ptr platform_surface) - : valid_(false), platform_surface_(std::move(platform_surface)) { - if (platform_surface_ == nullptr || !platform_surface_->IsValid()) { +VulkanWindow::VulkanWindow(ftl::RefPtr proc_table, + std::unique_ptr native_surface) + : valid_(false), vk(std::move(proc_table)) { + if (!vk || !vk->HasAcquiredMandatoryProcAddresses()) { + FTL_DLOG(INFO) << "Proc table has not acquired mandatory proc addresses."; return; } - if (!vk.IsValid()) { + if (native_surface == nullptr || !native_surface->IsValid()) { + FTL_DLOG(INFO) << "Native surface is invalid."; return; } - if (!CreateInstance()) { + // Create the application instance. + + std::vector extensions = { + VK_KHR_SURFACE_EXTENSION_NAME, // parent extension + native_surface->GetExtensionName() // child extension + }; + + application_ = std::make_unique(*vk, "Flutter", + std::move(extensions)); + + if (!application_->IsValid() || !vk->AreInstanceProcsSetup()) { + // Make certain the application instance was created and it setup the + // instance proc table entries. + FTL_DLOG(INFO) << "Instance proc addresses have not been setup."; return; } - if (!CreateSurface()) { + // Create the device. + + logical_device_ = application_->AcquireFirstCompatibleLogicalDevice(); + + if (logical_device_ == nullptr || !logical_device_->IsValid() || + !vk->AreDeviceProcsSetup()) { + // Make certain the device was created and it setup the device proc table + // entries. + FTL_DLOG(INFO) << "Device proc addresses have not been setup."; return; } - if (!SelectPhysicalDevice()) { + // Create the logical surface from the native platform surface. + + surface_ = std::make_unique(*vk, *application_, + std::move(native_surface)); + + if (!surface_->IsValid()) { + FTL_DLOG(INFO) << "Vulkan surface is invalid."; return; } - if (!CreateLogicalDevice()) { + // Create the Skia GrContext. + + if (!CreateSkiaGrContext()) { + FTL_DLOG(INFO) << "Could not create Skia context."; return; } - if (!CreateSwapChain()) { - return; - } + // Create the swapchain. - if (!AcquireDeviceQueue()) { - return; - } - - if (!CreateCommandPool()) { - return; - } - - if (!SetupBuffers()) { + if (!RecreateSwapchain()) { + FTL_DLOG(INFO) << "Could not setup the swapchain initially."; return; } @@ -57,352 +92,162 @@ bool VulkanWindow::IsValid() const { return valid_; } -bool VulkanWindow::CreateInstance() { - const VkApplicationInfo info = { - .sType = VK_STRUCTURE_TYPE_APPLICATION_INFO, - .pNext = nullptr, - .pApplicationName = "FlutterEngine", - .applicationVersion = VK_MAKE_VERSION(1, 0, 0), - .pEngineName = "FlutterEngine", - .engineVersion = VK_MAKE_VERSION(1, 0, 0), - .apiVersion = VK_MAKE_VERSION(1, 0, 0), - }; +GrContext* VulkanWindow::GetSkiaGrContext() { + return skia_gr_context_.get(); +} - const char* extensions[] = { - VK_KHR_SURFACE_EXTENSION_NAME, platform_surface_->ExtensionName(), - }; +bool VulkanWindow::CreateSkiaGrContext() { + auto backend_context = CreateSkiaBackendContext(); - const VkInstanceCreateInfo create_info = { - .sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, - .pNext = nullptr, - .flags = 0, - .pApplicationInfo = &info, - .enabledLayerCount = 0, - .ppEnabledLayerNames = nullptr, - .enabledExtensionCount = sizeof(extensions) / sizeof(const char*), - .ppEnabledExtensionNames = extensions, - }; - - VkInstance instance = VK_NULL_HANDLE; - if (vk.createInstance(&create_info, nullptr, &instance) != VK_SUCCESS) { + if (backend_context == nullptr) { return false; } - instance_ = {instance, - [this](VkInstance i) { vk.destroyInstance(i, nullptr); }}; + sk_sp context(GrContext::Create( + kVulkan_GrBackend, + reinterpret_cast(backend_context.get()))); + + if (context == nullptr) { + return false; + } + + skia_vk_backend_context_ = backend_context; + skia_gr_context_ = context; return true; } -bool VulkanWindow::CreateSurface() { - if (!instance_) { - return false; +sk_sp VulkanWindow::CreateSkiaBackendContext() { + auto interface = vk->CreateSkiaInterface(); + + if (interface == nullptr || !interface->validate(0)) { + return nullptr; } - VkSurfaceKHR surface = platform_surface_->CreateSurfaceHandle(vk, instance_); - - if (surface == VK_NULL_HANDLE) { - return false; + uint32_t skia_features = 0; + if (!logical_device_->GetPhysicalDeviceFeaturesSkia(&skia_features)) { + return nullptr; } - surface_ = {surface, [this](VkSurfaceKHR surface) { - vk.destroySurfaceKHR(instance_, surface, nullptr); - }}; - - return true; + auto context = sk_make_sp(); + context->fInstance = application_->GetInstance(); + context->fPhysicalDevice = logical_device_->GetPhysicalDeviceHandle(); + context->fDevice = logical_device_->GetHandle(); + context->fQueue = logical_device_->GetQueueHandle(); + context->fGraphicsQueueIndex = logical_device_->GetGraphicsQueueIndex(); + context->fMinAPIVersion = application_->GetAPIVersion(); + context->fExtensions = kKHR_surface_GrVkExtensionFlag | + kKHR_swapchain_GrVkExtensionFlag | + surface_->GetNativeSurface().GetSkiaExtensionName(); + context->fFeatures = skia_features; + context->fInterface.reset(interface.release()); + return context; } -bool VulkanWindow::SelectPhysicalDevice() { - if (instance_ == nullptr) { - return false; +sk_sp VulkanWindow::AcquireSurface() { + if (!IsValid()) { + FTL_DLOG(INFO) << "Surface is invalid."; + return nullptr; } - uint32_t device_count = 0; - if (vk.enumeratePhysicalDevices(instance_, &device_count, nullptr) != - VK_SUCCESS) { - return false; - } + auto surface_size = surface_->GetSize(); - if (device_count == 0) { - // No available devices. - return false; - } - - VkPhysicalDevice devices[device_count]; - - if (vk.enumeratePhysicalDevices(instance_, &device_count, devices) != - VK_SUCCESS) { - return false; - } - - // Pick the first one available. - physical_device_ = {devices[0], {}}; - return true; -} - -bool VulkanWindow::CreateLogicalDevice() { - if (physical_device_ == nullptr) { - return false; - } - - float priorities[] = {1.0f}; - - const VkDeviceQueueCreateInfo queue_create = { - .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, - .pNext = nullptr, - .flags = 0, - .queueFamilyIndex = 0, - .queueCount = 1, - .pQueuePriorities = priorities, - }; - - const char* extensions[] = { - VK_KHR_SWAPCHAIN_EXTENSION_NAME, - }; - - const VkDeviceCreateInfo create_info = { - .sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, - .pNext = nullptr, - .flags = 0, - .queueCreateInfoCount = 1, - .pQueueCreateInfos = &queue_create, - .enabledLayerCount = 0, - .ppEnabledLayerNames = nullptr, - .enabledExtensionCount = sizeof(extensions) / sizeof(const char*), - .ppEnabledExtensionNames = extensions, - .pEnabledFeatures = nullptr, - }; - - VkDevice device = VK_NULL_HANDLE; - - if (vk.createDevice(physical_device_, &create_info, nullptr, &device) != - VK_SUCCESS) { - return false; - } - - device_ = {device, - [this](VkDevice device) { vk.destroyDevice(device, nullptr); }}; - - return true; -} - -bool VulkanWindow::AcquireDeviceQueue() { - if (device_ == nullptr) { - return false; - } - - VkQueue queue = VK_NULL_HANDLE; - vk.getDeviceQueue(device_, 0, 0, &queue); - - if (queue == VK_NULL_HANDLE) { - return false; - } - - queue_ = {queue, {}}; - - return true; -} - -std::pair VulkanWindow::ChooseSurfaceFormat() { - if (!physical_device_ || !surface_) { - return {false, {}}; - } - - uint32_t format_count = 0; - if (vk.getPhysicalDeviceSurfaceFormatsKHR( - physical_device_, surface_, &format_count, nullptr) != VK_SUCCESS) { - return {false, {}}; - } - - if (format_count == 0) { - return {false, {}}; - } - - VkSurfaceFormatKHR formats[format_count]; - if (vk.getPhysicalDeviceSurfaceFormatsKHR( - physical_device_, surface_, &format_count, formats) != VK_SUCCESS) { - return {false, {}}; - } - - for (uint32_t i = 0; i < format_count; i++) { - if (formats[i].format == VK_FORMAT_R8G8B8A8_UNORM) { - return {true, formats[i]}; + // This check is theoretically unnecessary as the swapchain should report that + // the surface is out-of-date and perform swapchain recreation at the new + // configuration. However, on Android, the swapchain never reports that it is + // of date. Hence this extra check. Platforms that don't have this issue, or, + // cant report this information (which is optional anyway), report a zero + // size. + if (surface_size != SkISize::Make(0, 0) && + surface_size != swapchain_->GetSize()) { + FTL_DLOG(INFO) << "Swapchain and surface sizes are out of sync. Recreating " + "swapchain."; + if (!RecreateSwapchain()) { + FTL_DLOG(INFO) << "Could not recreate swapchain."; + valid_ = false; + return nullptr; } } - return {false, {}}; -} + while (true) { + sk_sp surface; + auto acquire_result = VulkanSwapchain::AcquireStatus::ErrorSurfaceLost; -std::pair VulkanWindow::ChoosePresentMode() { - if (!physical_device_ || !surface_) { - return {false, {}}; - } + std::tie(acquire_result, surface) = swapchain_->AcquireSurface(); - uint32_t modes_count = 0; - - if (vk.getPhysicalDeviceSurfacePresentModesKHR( - physical_device_, surface_, &modes_count, nullptr) != VK_SUCCESS) { - return {false, {}}; - } - - if (modes_count == 0) { - return {false, {}}; - } - - VkPresentModeKHR modes[modes_count]; - - if (vk.getPhysicalDeviceSurfacePresentModesKHR( - physical_device_, surface_, &modes_count, modes) != VK_SUCCESS) { - return {false, {}}; - } - - for (uint32_t i = 0; i < modes_count; i++) { - if (modes[i] == VK_PRESENT_MODE_MAILBOX_KHR) { - return {true, modes[i]}; - } - } - - return {true, VK_PRESENT_MODE_FIFO_KHR}; -} - -bool VulkanWindow::CreateSwapChain() { - if (!device_ || !surface_) { - return false; - } - - // Query Capabilities - - VkSurfaceCapabilitiesKHR capabilities = {0}; - if (vk.getPhysicalDeviceSurfaceCapabilitiesKHR(physical_device_, surface_, - &capabilities) != VK_SUCCESS) { - return false; - } - - // Query Format - - VkSurfaceFormatKHR format = {}; - bool query_result = false; - - std::tie(query_result, format) = ChooseSurfaceFormat(); - - if (!query_result) { - return false; - } - - // Query Present Mode - - VkPresentModeKHR presentMode = VK_PRESENT_MODE_FIFO_KHR; - std::tie(query_result, presentMode) = ChoosePresentMode(); - - if (!query_result) { - return false; - } - - // Construct the Swapchain - - const VkSwapchainCreateInfoKHR create_info = { - .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR, - .pNext = nullptr, - .flags = 0, - .surface = surface_, - .minImageCount = capabilities.minImageCount, - .imageFormat = format.format, - .imageColorSpace = format.colorSpace, - .imageExtent = capabilities.currentExtent, - .imageArrayLayers = 1, - .imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, - .imageSharingMode = VK_SHARING_MODE_EXCLUSIVE, - .queueFamilyIndexCount = 0, - .pQueueFamilyIndices = nullptr, - .preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR, - .compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR, - .presentMode = presentMode, - .clipped = VK_FALSE, - .oldSwapchain = VK_NULL_HANDLE, - }; - - VkSwapchainKHR swapchain = VK_NULL_HANDLE; - - if (vk.createSwapchainKHR(device_, &create_info, nullptr, &swapchain) != - VK_SUCCESS) { - return false; - } - - swapchain_ = {swapchain, [this](VkSwapchainKHR swapchain) { - vk.destroySwapchainKHR(device_, swapchain, nullptr); - }}; - - return true; -} - -bool VulkanWindow::SetupBuffers() { - if (!device_ || !swapchain_) { - return false; - } - - uint32_t count = 0; - if (vk.getSwapchainImagesKHR(device_, swapchain_, &count, nullptr) != - VK_SUCCESS) { - return false; - } - - if (count == 0) { - return false; - } - - VkImage images[count]; - - if (vk.getSwapchainImagesKHR(device_, swapchain_, &count, images) != - VK_SUCCESS) { - return false; - } - - if (count == 0) { - return false; - } - - auto image_collector = [](VkImage image) { - // We are only just getting references to images owned by the swapchain. - // There is no ownership change. - }; - - backbuffers_.clear(); - - for (uint32_t i = 0; i < count; i++) { - std::unique_ptr backbuffer(new VulkanBackbuffer( - vk, device_, command_pool_, {images[i], image_collector})); - - if (!backbuffer->IsValid()) { - return false; + if (acquire_result == VulkanSwapchain::AcquireStatus::Success) { + // Successfully acquired a surface from the swapchain. Nothing more to do. + return surface; } - backbuffers_.emplace_back(std::move(backbuffer)); + if (acquire_result == VulkanSwapchain::AcquireStatus::ErrorSurfaceLost) { + // Surface is lost. This is an unrecoverable error. + FTL_DLOG(INFO) << "Swapchain reported surface was lost."; + return nullptr; + } + + if (acquire_result == + VulkanSwapchain::AcquireStatus::ErrorSurfaceOutOfDate) { + // Surface out of date. Recreate the swapchain at the new configuration. + if (RecreateSwapchain()) { + // Swapchain was recreated, try surface acquisition again. + continue; + } else { + // Could not recreate the swapchain at the new configuration. + FTL_DLOG(INFO) << "Swapchain reported surface was out of date but " + "could not recreate the swapchain at the new " + "configuration."; + valid_ = false; + return nullptr; + } + } + + break; } - return true; + FTL_DCHECK(false) << "Unhandled VulkanSwapchain::AcquireResult"; + return nullptr; } -bool VulkanWindow::CreateCommandPool() { - if (!device_) { +bool VulkanWindow::SwapBuffers() { + if (!IsValid()) { + FTL_DLOG(INFO) << "Window was invalid."; return false; } - const VkCommandPoolCreateInfo create_info = { - .sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, - .pNext = nullptr, - .flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, - .queueFamilyIndex = 0, - }; + return swapchain_->Submit(); +} - VkCommandPool command_pool = VK_NULL_HANDLE; - if (vk.createCommandPool(device_, &create_info, nullptr, &command_pool) != - VK_SUCCESS) { +bool VulkanWindow::RecreateSwapchain() { + // This way, we always lose our reference to the old swapchain. Even if we + // cannot create a new one to replace it. + auto old_swapchain = std::move(swapchain_); + + if (!vk->IsValid()) { return false; } - command_pool_ = {command_pool, [this](VkCommandPool pool) { - vk.destroyCommandPool(device_, pool, nullptr); - }}; + if (logical_device_ == nullptr || !logical_device_->IsValid()) { + return false; + } + + if (surface_ == nullptr || !surface_->IsValid()) { + return false; + } + + if (skia_gr_context_ == nullptr) { + return false; + } + + auto swapchain = std::make_unique( + *vk, *logical_device_, *surface_, skia_gr_context_.get(), + std::move(old_swapchain), logical_device_->GetGraphicsQueueIndex()); + + if (!swapchain->IsValid()) { + return false; + } + + swapchain_ = std::move(swapchain); return true; } diff --git a/engine/src/flutter/vulkan/vulkan_window.h b/engine/src/flutter/vulkan/vulkan_window.h index 93c40954cb..d5c7eee6cc 100644 --- a/engine/src/flutter/vulkan/vulkan_window.h +++ b/engine/src/flutter/vulkan/vulkan_window.h @@ -5,58 +5,61 @@ #ifndef FLUTTER_VULKAN_VULKAN_WINDOW_H_ #define FLUTTER_VULKAN_VULKAN_WINDOW_H_ -#include +#include #include +#include #include +#include "flutter/vulkan/vulkan_proc_table.h" +#include "lib/ftl/compiler_specific.h" #include "lib/ftl/macros.h" -#include "vulkan_handle.h" -#include "vulkan_proc_table.h" -#include "vulkan_backbuffer.h" -#include "vulkan_surface.h" +#include "third_party/skia/include/core/SkRefCnt.h" +#include "third_party/skia/include/core/SkSize.h" +#include "third_party/skia/include/core/SkSurface.h" +#include "third_party/skia/include/gpu/GrContext.h" +#include "third_party/skia/include/gpu/vk/GrVkBackendContext.h" namespace vulkan { +class VulkanNativeSurface; +class VulkanDevice; +class VulkanSurface; +class VulkanSwapchain; +class VulkanImage; +class VulkanApplication; +class VulkanBackbuffer; + class VulkanWindow { public: - VulkanWindow(std::unique_ptr platform_surface); + VulkanWindow(ftl::RefPtr proc_table, + std::unique_ptr native_surface); ~VulkanWindow(); bool IsValid() const; + GrContext* GetSkiaGrContext(); + + sk_sp AcquireSurface(); + + bool SwapBuffers(); + private: bool valid_; - VulkanProcTable vk; - VulkanHandle instance_; - std::unique_ptr platform_surface_; - VulkanHandle surface_; - VulkanHandle physical_device_; - VulkanHandle device_; - VulkanHandle queue_; - VulkanHandle swapchain_; - std::vector> backbuffers_; - VulkanHandle command_pool_; + ftl::RefPtr vk; + std::unique_ptr application_; + std::unique_ptr logical_device_; + std::unique_ptr surface_; + std::unique_ptr swapchain_; + sk_sp skia_vk_backend_context_; + sk_sp skia_gr_context_; - bool CreateInstance(); + bool CreateSkiaGrContext(); - bool CreateSurface(); + sk_sp CreateSkiaBackendContext(); - bool SelectPhysicalDevice(); - - bool CreateLogicalDevice(); - - bool AcquireDeviceQueue(); - - bool CreateSwapChain(); - - bool SetupBuffers(); - - bool CreateCommandPool(); - - std::pair ChooseSurfaceFormat(); - - std::pair ChoosePresentMode(); + FTL_WARN_UNUSED_RESULT + bool RecreateSwapchain(); FTL_DISALLOW_COPY_AND_ASSIGN(VulkanWindow); };