[Impeller] Stub a Vulkan backend. (flutter/engine#34717)

This commit is contained in:
Chinmay Garde
2022-07-18 16:26:05 -07:00
committed by GitHub
parent be6994913a
commit b69a07df25
61 changed files with 2270 additions and 22 deletions

View File

@@ -732,6 +732,39 @@ FILE: ../../../flutter/impeller/renderer/backend/metal/texture_mtl.h
FILE: ../../../flutter/impeller/renderer/backend/metal/texture_mtl.mm
FILE: ../../../flutter/impeller/renderer/backend/metal/vertex_descriptor_mtl.h
FILE: ../../../flutter/impeller/renderer/backend/metal/vertex_descriptor_mtl.mm
FILE: ../../../flutter/impeller/renderer/backend/vulkan/allocator_vk.cc
FILE: ../../../flutter/impeller/renderer/backend/vulkan/allocator_vk.h
FILE: ../../../flutter/impeller/renderer/backend/vulkan/capabilities_vk.cc
FILE: ../../../flutter/impeller/renderer/backend/vulkan/capabilities_vk.h
FILE: ../../../flutter/impeller/renderer/backend/vulkan/command_buffer_vk.cc
FILE: ../../../flutter/impeller/renderer/backend/vulkan/command_buffer_vk.h
FILE: ../../../flutter/impeller/renderer/backend/vulkan/context_vk.cc
FILE: ../../../flutter/impeller/renderer/backend/vulkan/context_vk.h
FILE: ../../../flutter/impeller/renderer/backend/vulkan/device_buffer_vk.cc
FILE: ../../../flutter/impeller/renderer/backend/vulkan/device_buffer_vk.h
FILE: ../../../flutter/impeller/renderer/backend/vulkan/formats_vk.cc
FILE: ../../../flutter/impeller/renderer/backend/vulkan/formats_vk.h
FILE: ../../../flutter/impeller/renderer/backend/vulkan/pipeline_library_vk.cc
FILE: ../../../flutter/impeller/renderer/backend/vulkan/pipeline_library_vk.h
FILE: ../../../flutter/impeller/renderer/backend/vulkan/pipeline_vk.cc
FILE: ../../../flutter/impeller/renderer/backend/vulkan/pipeline_vk.h
FILE: ../../../flutter/impeller/renderer/backend/vulkan/render_pass_vk.cc
FILE: ../../../flutter/impeller/renderer/backend/vulkan/render_pass_vk.h
FILE: ../../../flutter/impeller/renderer/backend/vulkan/sampler_library_vk.cc
FILE: ../../../flutter/impeller/renderer/backend/vulkan/sampler_library_vk.h
FILE: ../../../flutter/impeller/renderer/backend/vulkan/sampler_vk.cc
FILE: ../../../flutter/impeller/renderer/backend/vulkan/sampler_vk.h
FILE: ../../../flutter/impeller/renderer/backend/vulkan/shader_function_vk.cc
FILE: ../../../flutter/impeller/renderer/backend/vulkan/shader_function_vk.h
FILE: ../../../flutter/impeller/renderer/backend/vulkan/shader_library_vk.cc
FILE: ../../../flutter/impeller/renderer/backend/vulkan/shader_library_vk.h
FILE: ../../../flutter/impeller/renderer/backend/vulkan/surface_vk.cc
FILE: ../../../flutter/impeller/renderer/backend/vulkan/surface_vk.h
FILE: ../../../flutter/impeller/renderer/backend/vulkan/texture_vk.cc
FILE: ../../../flutter/impeller/renderer/backend/vulkan/texture_vk.h
FILE: ../../../flutter/impeller/renderer/backend/vulkan/vertex_descriptor_vk.cc
FILE: ../../../flutter/impeller/renderer/backend/vulkan/vertex_descriptor_vk.h
FILE: ../../../flutter/impeller/renderer/backend/vulkan/vk.h
FILE: ../../../flutter/impeller/renderer/buffer.cc
FILE: ../../../flutter/impeller/renderer/buffer.h
FILE: ../../../flutter/impeller/renderer/buffer_view.cc

View File

@@ -25,6 +25,10 @@ config("impeller_public_config") {
defines += [ "IMPELLER_ENABLE_OPENGLES=1" ]
}
if (impeller_enable_vulkan) {
defines += [ "IMPELLER_ENABLE_VULKAN=1" ]
}
if (impeller_trace_all_gl_calls) {
defines += [ "IMPELLER_TRACE_ALL_GL_CALLS" ]
}

View File

@@ -108,4 +108,11 @@ std::shared_ptr<fml::Mapping> CreateMappingFromAllocation(
);
}
std::shared_ptr<fml::Mapping> CreateMappingWithString(std::string string) {
auto buffer = std::make_shared<std::string>(std::move(string));
return std::make_unique<fml::NonOwnedMapping>(
reinterpret_cast<const uint8_t*>(buffer->c_str()), buffer->length(),
[buffer](auto, auto) {});
}
} // namespace impeller

View File

@@ -46,4 +46,9 @@ std::shared_ptr<fml::Mapping> CreateMappingWithCopy(const uint8_t* contents,
std::shared_ptr<fml::Mapping> CreateMappingFromAllocation(
std::shared_ptr<Allocation> allocation);
std::shared_ptr<fml::Mapping> CreateMappingWithString(
std::shared_ptr<const std::string> string);
std::shared_ptr<fml::Mapping> CreateMappingWithString(std::string string);
} // namespace impeller

View File

@@ -31,7 +31,7 @@ bool BlobWriter::AddBlobAtPath(const std::string& std_path) {
return false;
}
if (path.extension() != ".gles") {
if (path.extension() != ".gles" && path.extension() != ".vkspv") {
FML_LOG(ERROR) << "File path doesn't have a known shader extension "
<< path;
return false;
@@ -43,7 +43,8 @@ bool BlobWriter::AddBlobAtPath(const std::string& std_path) {
auto shader_type = InferShaderTypefromFileExtension(path.extension());
if (!shader_type.has_value()) {
FML_LOG(ERROR) << "Could not infer shader type from file extension.";
FML_LOG(ERROR) << "Could not infer shader type from file extension: "
<< path.extension().string();
return false;
}

View File

@@ -9,6 +9,7 @@
#include <sstream>
#include "flutter/fml/paths.h"
#include "impeller/base/allocation.h"
#include "impeller/compiler/compiler_backend.h"
#include "impeller/compiler/includer.h"
#include "impeller/compiler/logger.h"
@@ -59,6 +60,7 @@ static bool EntryPointMustBeNamedMain(TargetPlatform platform) {
FML_UNREACHABLE();
case TargetPlatform::kMetalDesktop:
case TargetPlatform::kMetalIOS:
case TargetPlatform::kVulkan:
case TargetPlatform::kRuntimeStageMetal:
return false;
case TargetPlatform::kFlutterSPIRV:
@@ -79,6 +81,7 @@ static CompilerBackend CreateCompiler(const spirv_cross::ParsedIR& ir,
case TargetPlatform::kMetalIOS:
case TargetPlatform::kRuntimeStageMetal:
case TargetPlatform::kRuntimeStageGLES:
case TargetPlatform::kVulkan:
compiler = CreateMSLCompiler(ir, source_options);
break;
case TargetPlatform::kUnknown:
@@ -149,6 +152,15 @@ Compiler::Compiler(const fml::Mapping& source_mapping,
spirv_options.SetTargetSpirv(
shaderc_spirv_version::shaderc_spirv_version_1_3);
break;
case TargetPlatform::kVulkan:
spirv_options.SetOptimizationLevel(
shaderc_optimization_level::shaderc_optimization_level_performance);
spirv_options.SetTargetEnvironment(
shaderc_target_env::shaderc_target_env_vulkan,
shaderc_env_version::shaderc_env_version_vulkan_1_0);
spirv_options.SetTargetSpirv(
shaderc_spirv_version::shaderc_spirv_version_1_0);
break;
case TargetPlatform::kRuntimeStageMetal:
case TargetPlatform::kRuntimeStageGLES:
spirv_options.SetOptimizationLevel(
@@ -262,10 +274,20 @@ Compiler::Compiler(const fml::Mapping& source_mapping,
return;
}
sl_string_ =
std::make_shared<std::string>(sl_compiler.GetCompiler()->compile());
// We need to invoke the compiler even if we don't use the SL mapping later
// for Vulkan. The reflector needs information that is only valid after a
// successful compilation call.
auto sl_compilation_result =
CreateMappingWithString(sl_compiler.GetCompiler()->compile());
if (!sl_string_) {
// If the target is Vulkan, our shading language is SPIRV which we already
// have. If it isn't, we need to invoke the appropriate compiler to compile
// the SPIRV to the target SL.
sl_mapping_ = source_options.target_platform == TargetPlatform::kVulkan
? GetSPIRVAssembly()
: sl_compilation_result;
if (!sl_mapping_) {
COMPILER_ERROR << "Could not generate SL from SPIRV";
return;
}
@@ -299,15 +321,8 @@ std::unique_ptr<fml::Mapping> Compiler::GetSPIRVAssembly() const {
[result = spv_result_](auto, auto) mutable { result.reset(); });
}
std::unique_ptr<fml::Mapping> Compiler::GetSLShaderSource() const {
if (!sl_string_) {
return nullptr;
}
return std::make_unique<fml::NonOwnedMapping>(
reinterpret_cast<const uint8_t*>(sl_string_->c_str()),
sl_string_->length(),
[string = sl_string_](auto, auto) mutable { string.reset(); });
std::shared_ptr<fml::Mapping> Compiler::GetSLShaderSource() const {
return sl_mapping_;
}
bool Compiler::IsValid() const {

View File

@@ -33,7 +33,7 @@ class Compiler {
std::unique_ptr<fml::Mapping> GetSPIRVAssembly() const;
std::unique_ptr<fml::Mapping> GetSLShaderSource() const;
std::shared_ptr<fml::Mapping> GetSLShaderSource() const;
std::string GetErrorMessages() const;
@@ -47,7 +47,7 @@ class Compiler {
private:
SourceOptions options_;
std::shared_ptr<shaderc::SpvCompilationResult> spv_result_;
std::shared_ptr<std::string> sl_string_;
std::shared_ptr<fml::Mapping> sl_mapping_;
std::stringstream error_stream_;
std::unique_ptr<Reflector> reflector_;
std::vector<std::string> included_file_names_;

View File

@@ -173,6 +173,7 @@ bool Main(const fml::CommandLine& command_line) {
case TargetPlatform::kRuntimeStageMetal:
case TargetPlatform::kRuntimeStageGLES:
case TargetPlatform::kSkSL:
case TargetPlatform::kVulkan:
result_file = switches.sl_file_name;
break;
case TargetPlatform::kFlutterSPIRV:

View File

@@ -58,6 +58,7 @@ static std::optional<fb::TargetPlatform> ToTargetPlatform(
case TargetPlatform::kSkSL:
case TargetPlatform::kOpenGLES:
case TargetPlatform::kOpenGLDesktop:
case TargetPlatform::kVulkan:
return std::nullopt;
case TargetPlatform::kRuntimeStageMetal:
return fb::TargetPlatform::kMetal;

View File

@@ -15,6 +15,7 @@ namespace compiler {
static const std::map<std::string, TargetPlatform> kKnownPlatforms = {
{"metal-desktop", TargetPlatform::kMetalDesktop},
{"metal-ios", TargetPlatform::kMetalIOS},
{"vulkan", TargetPlatform::kVulkan},
{"opengl-es", TargetPlatform::kOpenGLES},
{"opengl-desktop", TargetPlatform::kOpenGLDesktop},
{"flutter-spirv", TargetPlatform::kFlutterSPIRV},

View File

@@ -63,6 +63,8 @@ std::string TargetPlatformToString(TargetPlatform platform) {
return "OpenGLES";
case TargetPlatform::kOpenGLDesktop:
return "OpenGLDesktop";
case TargetPlatform::kVulkan:
return "Vulkan";
case TargetPlatform::kRuntimeStageMetal:
return "RuntimeStageMetal";
case TargetPlatform::kRuntimeStageGLES:
@@ -111,6 +113,7 @@ bool TargetPlatformNeedsSL(TargetPlatform platform) {
case TargetPlatform::kRuntimeStageMetal:
case TargetPlatform::kRuntimeStageGLES:
case TargetPlatform::kSkSL:
case TargetPlatform::kVulkan:
return true;
case TargetPlatform::kUnknown:
case TargetPlatform::kFlutterSPIRV:
@@ -127,6 +130,7 @@ bool TargetPlatformNeedsReflection(TargetPlatform platform) {
case TargetPlatform::kOpenGLDesktop:
case TargetPlatform::kRuntimeStageMetal:
case TargetPlatform::kRuntimeStageGLES:
case TargetPlatform::kVulkan:
return true;
case TargetPlatform::kUnknown:
case TargetPlatform::kFlutterSPIRV:
@@ -210,6 +214,7 @@ spirv_cross::CompilerMSL::Options::Platform TargetPlatformToMSLPlatform(
case TargetPlatform::kOpenGLES:
case TargetPlatform::kOpenGLDesktop:
case TargetPlatform::kRuntimeStageGLES:
case TargetPlatform::kVulkan:
case TargetPlatform::kUnknown:
return spirv_cross::CompilerMSL::Options::Platform::macOS;
}
@@ -248,6 +253,8 @@ std::string TargetPlatformSLExtension(TargetPlatform platform) {
case TargetPlatform::kOpenGLDesktop:
case TargetPlatform::kRuntimeStageGLES:
return "glsl";
case TargetPlatform::kVulkan:
return "vk.spirv";
}
FML_UNREACHABLE();
}
@@ -273,6 +280,7 @@ bool TargetPlatformIsOpenGL(TargetPlatform platform) {
case TargetPlatform::kUnknown:
case TargetPlatform::kFlutterSPIRV:
case TargetPlatform::kSkSL:
case TargetPlatform::kVulkan:
return false;
}
FML_UNREACHABLE();
@@ -290,6 +298,7 @@ bool TargetPlatformIsMetal(TargetPlatform platform) {
case TargetPlatform::kOpenGLES:
case TargetPlatform::kOpenGLDesktop:
case TargetPlatform::kRuntimeStageGLES:
case TargetPlatform::kVulkan:
return false;
}
FML_UNREACHABLE();

View File

@@ -32,6 +32,7 @@ enum class TargetPlatform {
kFlutterSPIRV,
kOpenGLES,
kOpenGLDesktop,
kVulkan,
kRuntimeStageMetal,
kRuntimeStageGLES,
kSkSL,

View File

@@ -16,7 +16,6 @@ impeller_shaders("shader_fixtures") {
"impeller.vert",
"instanced_draw.frag",
"instanced_draw.vert",
"sample.vert",
"simple.vert",
"test_texture.frag",
"test_texture.vert",

View File

@@ -33,6 +33,13 @@ impeller_component("playground") {
]
}
if (impeller_enable_vulkan) {
sources += [
"backend/vulkan/playground_impl_vk.cc",
"backend/vulkan/playground_impl_vk.h",
]
}
public_deps = [
"../entity:entity_shaders",
"../fixtures:shader_fixtures",

View File

@@ -0,0 +1,78 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/playground/backend/vulkan/playground_impl_vk.h"
#include "impeller/renderer/backend/vulkan/vk.h"
#include <GLFW/glfw3.h>
#include "flutter/fml/logging.h"
#include "flutter/fml/mapping.h"
#include "impeller/entity/vk/entity_shaders_vk.h"
#include "impeller/fixtures/vk/fixtures_shaders_vk.h"
#include "impeller/playground/imgui/vk/imgui_shaders_vk.h"
#include "impeller/renderer/backend/vulkan/context_vk.h"
#include "impeller/renderer/backend/vulkan/formats_vk.h"
#include "impeller/renderer/backend/vulkan/surface_vk.h"
#include "impeller/renderer/backend/vulkan/texture_vk.h"
namespace impeller {
static std::vector<std::shared_ptr<fml::Mapping>>
ShaderLibraryMappingsForPlayground() {
return {
std::make_shared<fml::NonOwnedMapping>(impeller_entity_shaders_vk_data,
impeller_entity_shaders_vk_length),
std::make_shared<fml::NonOwnedMapping>(
impeller_fixtures_shaders_vk_data,
impeller_fixtures_shaders_vk_length),
std::make_shared<fml::NonOwnedMapping>(impeller_imgui_shaders_vk_data,
impeller_imgui_shaders_vk_length),
};
}
PlaygroundImplVK::PlaygroundImplVK()
: concurrent_loop_(fml::ConcurrentMessageLoop::Create()) {
if (!::glfwVulkanSupported()) {
VALIDATION_LOG << "Attempted to initialize a Vulkan playground on a system "
"that does not support Vulkan.";
return;
}
auto context = ContextVK::Create(reinterpret_cast<PFN_vkGetInstanceProcAddr>(
&::glfwGetInstanceProcAddress), //
ShaderLibraryMappingsForPlayground(), //
nullptr, //
concurrent_loop_->GetTaskRunner(), //
"Playground Library" //
);
if (!context || !context->IsValid()) {
VALIDATION_LOG << "Could not create Vulkan context in the playground.";
return;
}
context_ = std::move(context);
}
PlaygroundImplVK::~PlaygroundImplVK() = default;
// |PlaygroundImpl|
std::shared_ptr<Context> PlaygroundImplVK::GetContext() const {
return context_;
}
// |PlaygroundImpl|
PlaygroundImpl::WindowHandle PlaygroundImplVK::GetWindowHandle() const {
FML_UNREACHABLE();
}
// |PlaygroundImpl|
std::unique_ptr<Surface> PlaygroundImplVK::AcquireSurfaceFrame(
std::shared_ptr<Context> context) {
FML_UNREACHABLE();
}
} // namespace impeller

View File

@@ -0,0 +1,36 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#pragma once
#include "flutter/fml/concurrent_message_loop.h"
#include "flutter/fml/macros.h"
#include "impeller/playground/playground_impl.h"
namespace impeller {
class PlaygroundImplVK final : public PlaygroundImpl {
public:
PlaygroundImplVK();
~PlaygroundImplVK();
private:
std::shared_ptr<fml::ConcurrentMessageLoop> concurrent_loop_;
std::shared_ptr<Context> context_;
// |PlaygroundImpl|
std::shared_ptr<Context> GetContext() const override;
// |PlaygroundImpl|
WindowHandle GetWindowHandle() const override;
// |PlaygroundImpl|
std::unique_ptr<Surface> AcquireSurfaceFrame(
std::shared_ptr<Context> context) override;
FML_DISALLOW_COPY_AND_ASSIGN(PlaygroundImplVK);
};
} // namespace impeller

View File

@@ -36,6 +36,8 @@ std::string PlaygroundBackendToString(PlaygroundBackend backend) {
return "Metal";
case PlaygroundBackend::kOpenGLES:
return "OpenGLES";
case PlaygroundBackend::kVulkan:
return "Vulkan";
}
FML_UNREACHABLE();
}
@@ -96,6 +98,12 @@ static constexpr bool PlatformSupportsBackend(PlaygroundBackend backend) {
#else // IMPELLER_ENABLE_OPENGLES
return false;
#endif // IMPELLER_ENABLE_OPENGLES
case PlaygroundBackend::kVulkan:
#if IMPELLER_ENABLE_VULKAN
return true;
#else // IMPELLER_ENABLE_VULKAN
return false;
#endif // IMPELLER_ENABLE_VULKAN
}
FML_UNREACHABLE();
}

View File

@@ -20,6 +20,7 @@ class PlaygroundImpl;
enum class PlaygroundBackend {
kMetal,
kOpenGLES,
kVulkan,
};
std::string PlaygroundBackendToString(PlaygroundBackend backend);
@@ -86,7 +87,8 @@ class Playground : public ::testing::TestWithParam<PlaygroundBackend> {
INSTANTIATE_TEST_SUITE_P( \
Play, playground, \
::testing::Values(PlaygroundBackend::kMetal, \
PlaygroundBackend::kOpenGLES), \
PlaygroundBackend::kOpenGLES, \
PlaygroundBackend::kVulkan), \
[](const ::testing::TestParamInfo<Playground::ParamType>& info) { \
return PlaygroundBackendToString(info.param); \
});

View File

@@ -15,6 +15,10 @@
#include "impeller/playground/backend/gles/playground_impl_gles.h"
#endif // IMPELLER_ENABLE_OPENGLES
#if IMPELLER_ENABLE_VULKAN
#include "impeller/playground/backend/vulkan/playground_impl_vk.h"
#endif // IMPELLER_ENABLE_VULKAN
namespace impeller {
std::unique_ptr<PlaygroundImpl> PlaygroundImpl::Create(
@@ -28,6 +32,10 @@ std::unique_ptr<PlaygroundImpl> PlaygroundImpl::Create(
case PlaygroundBackend::kOpenGLES:
return std::make_unique<PlaygroundImplGLES>();
#endif // IMPELLER_ENABLE_OPENGLES
#if IMPELLER_ENABLE_VULKAN
case PlaygroundBackend::kVulkan:
return std::make_unique<PlaygroundImplVK>();
#endif // IMPELLER_ENABLE_VULKAN
default:
FML_CHECK(false) << "Attempted to create playground with backend that "
"isn't available or was disabled on this platform: "

View File

@@ -14,4 +14,8 @@ group("backend") {
if (impeller_enable_opengles) {
public_deps += [ "gles" ]
}
if (impeller_enable_vulkan) {
public_deps += [ "vulkan" ]
}
}

View File

@@ -166,6 +166,11 @@ static bool LinkProgram(
return true;
}
// |PipelineLibrary|
bool PipelineLibraryGLES::IsValid() const {
return reactor_ != nullptr;
}
// |PipelineLibrary|
PipelineFuture PipelineLibraryGLES::GetRenderPipeline(
PipelineDescriptor descriptor) {
@@ -205,6 +210,7 @@ PipelineFuture PipelineLibraryGLES::GetRenderPipeline(
new PipelineGLES(reactor_ptr, strong_this, descriptor));
auto program = reactor.GetGLHandle(pipeline->GetProgramHandle());
if (!program.has_value()) {
promise->set_value(nullptr);
VALIDATION_LOG << "Could not obtain program handle.";
return;
}

View File

@@ -25,6 +25,9 @@ class PipelineLibraryGLES final : public PipelineLibrary {
PipelineLibraryGLES(ReactorGLES::Ref reactor);
// |PipelineLibrary|
bool IsValid() const override;
// |PipelineLibrary|
PipelineFuture GetRenderPipeline(PipelineDescriptor descriptor) override;

View File

@@ -28,6 +28,9 @@ class PipelineLibraryMTL final : public PipelineLibrary {
PipelineLibraryMTL(id<MTLDevice> device);
// |PipelineLibrary|
bool IsValid() const override;
// |PipelineLibrary|
PipelineFuture GetRenderPipeline(PipelineDescriptor descriptor) override;

View File

@@ -68,13 +68,19 @@ static id<MTLDepthStencilState> CreateDepthStencilDescriptor(
return [device newDepthStencilStateWithDescriptor:descriptor];
}
// |PipelineLibrary|
bool PipelineLibraryMTL::IsValid() const {
return device_ != nullptr;
}
// |PipelineLibrary|
PipelineFuture PipelineLibraryMTL::GetRenderPipeline(
PipelineDescriptor descriptor) {
if (auto found = pipelines_.find(descriptor); found != pipelines_.end()) {
return found->second;
}
if (device_ == nil) {
if (!IsValid()) {
return RealizedFuture<std::shared_ptr<Pipeline>>(nullptr);
}

View File

@@ -0,0 +1,51 @@
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import("../../../tools/impeller.gni")
impeller_component("vulkan") {
sources = [
"allocator_vk.cc",
"allocator_vk.h",
"capabilities_vk.cc",
"capabilities_vk.h",
"command_buffer_vk.cc",
"command_buffer_vk.h",
"context_vk.cc",
"context_vk.h",
"device_buffer_vk.cc",
"device_buffer_vk.h",
"formats_vk.cc",
"formats_vk.h",
"pipeline_library_vk.cc",
"pipeline_library_vk.h",
"pipeline_vk.cc",
"pipeline_vk.h",
"render_pass_vk.cc",
"render_pass_vk.h",
"sampler_library_vk.cc",
"sampler_library_vk.h",
"sampler_vk.cc",
"sampler_vk.h",
"shader_function_vk.cc",
"shader_function_vk.h",
"shader_library_vk.cc",
"shader_library_vk.h",
"surface_vk.cc",
"surface_vk.h",
"texture_vk.cc",
"texture_vk.h",
"vertex_descriptor_vk.cc",
"vertex_descriptor_vk.h",
"vk.h",
]
public_deps = [
"../../:renderer",
"../../../blobcat:blobcat_lib",
"//flutter/fml",
"//third_party/vulkan-deps/vulkan-headers/src:vulkan_headers",
"//third_party/vulkan_memory_allocator",
]
}

View File

@@ -0,0 +1,68 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
_Pragma("GCC diagnostic push");
_Pragma("GCC diagnostic ignored \"-Wnullability-completeness\"");
_Pragma("GCC diagnostic ignored \"-Wunused-variable\"");
_Pragma("GCC diagnostic ignored \"-Wthread-safety-analysis\"");
#define VMA_IMPLEMENTATION
#include "impeller/renderer/backend/vulkan/allocator_vk.h"
_Pragma("GCC diagnostic pop");
namespace impeller {
AllocatorVK::AllocatorVK(uint32_t vulkan_api_version,
const vk::PhysicalDevice& physical_device,
const vk::Device& logical_device,
const vk::Instance& instance,
PFN_vkGetInstanceProcAddr get_instance_proc_address,
PFN_vkGetDeviceProcAddr get_device_proc_address) {
VmaVulkanFunctions proc_table = {};
proc_table.vkGetInstanceProcAddr = get_instance_proc_address;
proc_table.vkGetDeviceProcAddr = get_device_proc_address;
VmaAllocatorCreateInfo allocator_info = {};
allocator_info.vulkanApiVersion = vulkan_api_version;
allocator_info.physicalDevice = physical_device;
allocator_info.device = logical_device;
allocator_info.instance = instance;
allocator_info.pVulkanFunctions = &proc_table;
VmaAllocator allocator = {};
auto result = vk::Result{::vmaCreateAllocator(&allocator_info, &allocator)};
if (result != vk::Result::eSuccess) {
VALIDATION_LOG << "Could not create memory allocator";
return;
}
allocator_ = allocator;
is_valid_ = true;
}
AllocatorVK::~AllocatorVK() {
if (allocator_) {
::vmaDestroyAllocator(allocator_);
}
}
// |Allocator|
bool AllocatorVK::IsValid() const {
return is_valid_;
}
// |Allocator|
std::shared_ptr<Texture> AllocatorVK::CreateTexture(
StorageMode mode,
const TextureDescriptor& desc) {
FML_UNREACHABLE();
}
// |Allocator|
std::shared_ptr<DeviceBuffer> AllocatorVK::CreateBuffer(StorageMode mode,
size_t length) {
FML_UNREACHABLE();
}
} // namespace impeller

View File

@@ -0,0 +1,46 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#pragma once
#include "flutter/fml/macros.h"
#include "impeller/renderer/allocator.h"
#include "impeller/renderer/backend/vulkan/vk.h"
namespace impeller {
class AllocatorVK final : public Allocator {
public:
// |Allocator|
~AllocatorVK() override;
private:
friend class ContextVK;
VmaAllocator allocator_ = {};
bool is_valid_ = false;
AllocatorVK(uint32_t vulkan_api_version,
const vk::PhysicalDevice& physical_device,
const vk::Device& logical_device,
const vk::Instance& instance,
PFN_vkGetInstanceProcAddr get_instance_proc_address,
PFN_vkGetDeviceProcAddr get_device_proc_address);
// |Allocator|
bool IsValid() const;
// |Allocator|
std::shared_ptr<DeviceBuffer> CreateBuffer(StorageMode mode,
size_t length) override;
// |Allocator|
std::shared_ptr<Texture> CreateTexture(
StorageMode mode,
const TextureDescriptor& desc) override;
FML_DISALLOW_COPY_AND_ASSIGN(AllocatorVK);
};
} // namespace impeller

View File

@@ -0,0 +1,42 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/renderer/backend/vulkan/capabilities_vk.h"
#include "impeller/renderer/backend/vulkan/vk.h"
namespace impeller {
CapabilitiesVK::CapabilitiesVK() {
for (const auto& ext : vk::enumerateInstanceExtensionProperties().value) {
extensions_.insert(ext.extensionName);
}
for (const auto& layer : vk::enumerateInstanceLayerProperties().value) {
layers_.insert(layer.layerName);
}
}
CapabilitiesVK::~CapabilitiesVK() = default;
bool CapabilitiesVK::HasExtension(const std::string& extension) const {
return extensions_.count(extension) == 1u;
}
bool CapabilitiesVK::HasLayer(const std::string& layer) const {
return layers_.count(layer) == 1u;
}
bool CapabilitiesVK::HasLayerExtension(const std::string& layer,
const std::string& extension) {
for (const auto& ext :
vk::enumerateInstanceExtensionProperties(layer).value) {
if (std::string{ext.extensionName} == extension) {
return true;
}
}
return false;
}
} // namespace impeller

View File

@@ -0,0 +1,34 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#pragma once
#include <set>
#include <string>
#include "flutter/fml/macros.h"
namespace impeller {
class CapabilitiesVK {
public:
CapabilitiesVK();
~CapabilitiesVK();
bool HasExtension(const std::string& extension) const;
bool HasLayer(const std::string& layer) const;
bool HasLayerExtension(const std::string& layer,
const std::string& extension);
private:
std::set<std::string> extensions_;
std::set<std::string> layers_;
FML_DISALLOW_COPY_AND_ASSIGN(CapabilitiesVK);
};
} // namespace impeller

View File

@@ -0,0 +1,33 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/renderer/backend/vulkan/command_buffer_vk.h"
#include "flutter/fml/logging.h"
#include "impeller/renderer/render_target.h"
namespace impeller {
CommandBufferVK::CommandBufferVK() = default;
CommandBufferVK::~CommandBufferVK() = default;
void CommandBufferVK::SetLabel(const std::string& label) const {
FML_UNREACHABLE();
}
bool CommandBufferVK::IsValid() const {
FML_UNREACHABLE();
}
bool CommandBufferVK::SubmitCommands(CompletionCallback callback) {
FML_UNREACHABLE();
}
std::shared_ptr<RenderPass> CommandBufferVK::OnCreateRenderPass(
RenderTarget target) const {
FML_UNREACHABLE();
}
} // namespace impeller

View File

@@ -0,0 +1,38 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#pragma once
#include "flutter/fml/macros.h"
#include "impeller/renderer/command_buffer.h"
namespace impeller {
class CommandBufferVK final : public CommandBuffer {
public:
// |CommandBuffer|
~CommandBufferVK() override;
private:
friend class ContextMTL;
CommandBufferVK();
// |CommandBuffer|
void SetLabel(const std::string& label) const override;
// |CommandBuffer|
bool IsValid() const override;
// |CommandBuffer|
bool SubmitCommands(CompletionCallback callback) override;
// |CommandBuffer|
std::shared_ptr<RenderPass> OnCreateRenderPass(
RenderTarget target) const override;
FML_DISALLOW_COPY_AND_ASSIGN(CommandBufferVK);
};
} // namespace impeller

View File

@@ -0,0 +1,424 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/renderer/backend/vulkan/context_vk.h"
#include <map>
#include <optional>
#include <set>
#include <string>
#include "flutter/fml/build_config.h"
#include "flutter/fml/trace_event.h"
#include "impeller/base/validation.h"
#include "impeller/renderer/backend/vulkan/capabilities_vk.h"
#include "impeller/renderer/backend/vulkan/vk.h"
VULKAN_HPP_DEFAULT_DISPATCH_LOADER_DYNAMIC_STORAGE
namespace impeller {
static std::set<std::string> kRequiredDeviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME,
#if FML_OS_MACOSX
"VK_KHR_portability_subset", // For Molten VK. No define present in header.
#endif
};
static bool HasRequiredQueues(const vk::PhysicalDevice& device) {
auto present_flags = vk::QueueFlags{};
for (const auto& queue : device.getQueueFamilyProperties()) {
if (queue.queueCount == 0) {
continue;
}
present_flags |= queue.queueFlags;
}
return static_cast<VkQueueFlags>(present_flags &
(vk::QueueFlagBits::eGraphics |
vk::QueueFlagBits::eCompute |
vk::QueueFlagBits::eTransfer));
}
static bool HasRequiredExtensions(const vk::PhysicalDevice& device) {
std::set<std::string> exts;
for (const auto& ext : device.enumerateDeviceExtensionProperties().value) {
exts.insert(ext.extensionName);
}
for (const auto& req_ext : kRequiredDeviceExtensions) {
if (exts.count(req_ext) != 1u) {
return false;
}
}
return true;
}
static vk::PhysicalDeviceFeatures GetRequiredPhysicalDeviceFeatures() {
vk::PhysicalDeviceFeatures features;
features.setRobustBufferAccess(true);
return features;
};
static bool HasRequiredProperties(const vk::PhysicalDevice& device) {
auto properties = device.getProperties();
if (!(properties.limits.framebufferColorSampleCounts &
(vk::SampleCountFlagBits::e1 | vk::SampleCountFlagBits::e4))) {
return false;
}
return true;
}
static bool IsPhysicalDeviceCompatible(const vk::PhysicalDevice& device) {
if (!HasRequiredQueues(device)) {
VALIDATION_LOG << "Device doesn't have required queues.";
return false;
}
if (!HasRequiredExtensions(device)) {
VALIDATION_LOG << "Device doesn't have required extensions.";
return false;
}
if (!HasRequiredProperties(device)) {
VALIDATION_LOG << "Device doesn't have required properties.";
return false;
}
return true;
}
static std::optional<vk::PhysicalDevice> PickPhysicalDevice(
const vk::Instance& instance) {
for (const auto& device : instance.enumeratePhysicalDevices().value) {
if (IsPhysicalDeviceCompatible(device)) {
return device;
}
}
return std::nullopt;
}
static std::vector<vk::DeviceQueueCreateInfo> GetQueueCreateInfos(
std::initializer_list<QueueVK> queues) {
std::map<size_t /* family */, size_t /* index */> family_index_map;
for (const auto& queue : queues) {
family_index_map[queue.family] = 0;
}
for (const auto& queue : queues) {
auto value = family_index_map[queue.family];
family_index_map[queue.family] = std::max(value, queue.index);
}
static float kQueuePriority = 1.0f;
std::vector<vk::DeviceQueueCreateInfo> infos;
for (const auto& item : family_index_map) {
vk::DeviceQueueCreateInfo info;
info.setQueueFamilyIndex(item.first);
info.setQueueCount(item.second + 1);
info.setQueuePriorities(kQueuePriority);
infos.push_back(info);
}
return infos;
}
static std::optional<QueueVK> PickQueue(const vk::PhysicalDevice& device,
vk::QueueFlagBits flags) {
// This can be modified to ensure that dedicated queues are returned for each
// queue type depending on support.
const auto families = device.getQueueFamilyProperties();
for (size_t i = 0u; i < families.size(); i++) {
if (!(families[i].queueFlags & flags)) {
continue;
}
return QueueVK{.family = i, .index = 0};
}
return std::nullopt;
}
std::shared_ptr<ContextVK> ContextVK::Create(
PFN_vkGetInstanceProcAddr proc_address_callback,
const std::vector<std::shared_ptr<fml::Mapping>>& shader_libraries_data,
const std::shared_ptr<const fml::Mapping>& pipeline_cache_data,
std::shared_ptr<fml::ConcurrentTaskRunner> worker_task_runner,
const std::string& label) {
auto context = std::shared_ptr<ContextVK>(new ContextVK(
proc_address_callback, //
shader_libraries_data, //
pipeline_cache_data, //
std::move(worker_task_runner), //
label //
));
if (!context->IsValid()) {
return nullptr;
}
return context;
}
ContextVK::ContextVK(
PFN_vkGetInstanceProcAddr proc_address_callback,
const std::vector<std::shared_ptr<fml::Mapping>>& shader_libraries_data,
const std::shared_ptr<const fml::Mapping>& pipeline_cache_data,
std::shared_ptr<fml::ConcurrentTaskRunner> worker_task_runner,
const std::string& label)
: worker_task_runner_(std::move(worker_task_runner)) {
TRACE_EVENT0("impeller", "ContextVK::Create");
if (!worker_task_runner_) {
VALIDATION_LOG << "Invalid worker task runner.";
return;
}
auto& dispatcher = VULKAN_HPP_DEFAULT_DISPATCHER;
dispatcher.init(proc_address_callback);
auto capabilities = std::make_unique<CapabilitiesVK>();
vk::InstanceCreateFlags instance_flags = {};
std::vector<const char*> enabled_layers;
std::vector<const char*> enabled_extensions;
// This define may need to change into a runtime check if using SwiftShader on
// Mac.
#if FML_OS_MACOSX
//----------------------------------------------------------------------------
/// Ensure we need any Vulkan implementations that are not fully compliant
/// with the requested Vulkan Spec. This is necessary for MoltenVK on Mac
/// (backed by Metal).
///
if (!capabilities->HasExtension(
VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME)) {
VALIDATION_LOG << "On Mac: Required extension "
<< VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME
<< " absent.";
return;
}
// Molten VK on Mac is not fully compliant. We opt into being OK not getting
// back a fully compliant version of a Vulkan implementation.
enabled_extensions.push_back(VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME);
instance_flags |= vk::InstanceCreateFlagBits::eEnumeratePortabilityKHR;
if (!capabilities->HasExtension(
VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) {
VALIDATION_LOG << "On Mac: Required extension "
<< VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME
<< " absent.";
return;
}
// This is dependency of VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME which
// is a requirement for opting into Molten VK on Mac.
enabled_extensions.push_back(
VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
#endif // FML_OS_MACOSX
//----------------------------------------------------------------------------
/// Even though this is a WSI responsibility, require the surface extension
/// for swapchains.
if (!capabilities->HasExtension(VK_KHR_SURFACE_EXTENSION_NAME)) {
VALIDATION_LOG << "Required extension " VK_KHR_SURFACE_EXTENSION_NAME
<< " absent.";
return;
}
enabled_extensions.push_back(VK_KHR_SURFACE_EXTENSION_NAME);
//----------------------------------------------------------------------------
/// Enable any and all validation as well as debug toggles.
///
auto has_debug_utils = false;
constexpr const char* kKhronosValidationLayerName =
"VK_LAYER_KHRONOS_validation";
if (capabilities->HasLayer(kKhronosValidationLayerName)) {
enabled_layers.push_back(kKhronosValidationLayerName);
if (capabilities->HasLayerExtension(kKhronosValidationLayerName,
VK_EXT_DEBUG_UTILS_EXTENSION_NAME)) {
enabled_extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
has_debug_utils = true;
} else {
FML_LOG(ERROR) << "Vulkan debug utils are absent.";
}
} else {
FML_LOG(ERROR) << "Vulkan validation layers are absent.";
}
vk::ApplicationInfo application_info;
application_info.setApplicationVersion(VK_API_VERSION_1_0);
application_info.setApiVersion(VK_API_VERSION_1_0);
application_info.setEngineVersion(VK_API_VERSION_1_0);
application_info.setPEngineName("Impeller");
application_info.setPApplicationName("Impeller");
vk::InstanceCreateInfo instance_info;
instance_info.setPEnabledLayerNames(enabled_layers);
instance_info.setPEnabledExtensionNames(enabled_extensions);
instance_info.setPApplicationInfo(&application_info);
instance_info.setFlags(instance_flags);
auto instance = vk::createInstanceUnique(instance_info);
if (instance.result != vk::Result::eSuccess) {
FML_LOG(ERROR) << "Could not create instance: "
<< vk::to_string(instance.result);
return;
}
dispatcher.init(instance.value.get());
vk::UniqueDebugUtilsMessengerEXT debug_messenger;
if (has_debug_utils) {
vk::DebugUtilsMessengerCreateInfoEXT debug_messenger_info;
debug_messenger_info.messageSeverity =
vk::DebugUtilsMessageSeverityFlagBitsEXT::eWarning |
vk::DebugUtilsMessageSeverityFlagBitsEXT::eError;
debug_messenger_info.messageType =
vk::DebugUtilsMessageTypeFlagBitsEXT::eGeneral |
vk::DebugUtilsMessageTypeFlagBitsEXT::ePerformance |
vk::DebugUtilsMessageTypeFlagBitsEXT::eValidation;
debug_messenger_info.pUserData = nullptr;
debug_messenger_info.pfnUserCallback =
[](VkDebugUtilsMessageSeverityFlagBitsEXT severity,
VkDebugUtilsMessageTypeFlagsEXT type,
const VkDebugUtilsMessengerCallbackDataEXT* data,
void* user_data) -> VkBool32 {
FML_DCHECK(false)
<< vk::to_string(vk::DebugUtilsMessageSeverityFlagBitsEXT{severity})
<< ": " << data->pMessage;
return true;
};
auto debug_messenger_result =
instance.value->createDebugUtilsMessengerEXTUnique(
debug_messenger_info);
if (debug_messenger_result.result != vk::Result::eSuccess) {
FML_LOG(ERROR) << "Could not create debug messenger: "
<< vk::to_string(debug_messenger_result.result);
return;
}
debug_messenger = std::move(debug_messenger_result.value);
}
auto physical_device = PickPhysicalDevice(instance.value.get());
if (!physical_device.has_value()) {
VALIDATION_LOG << "No valid Vulkan device found.";
return;
}
auto graphics_queue =
PickQueue(physical_device.value(), vk::QueueFlagBits::eGraphics);
auto transfer_queue =
PickQueue(physical_device.value(), vk::QueueFlagBits::eTransfer);
auto compute_queue =
PickQueue(physical_device.value(), vk::QueueFlagBits::eCompute);
if (!graphics_queue.has_value() || !transfer_queue.has_value() ||
!compute_queue.has_value()) {
VALIDATION_LOG << "Could not pick device queues.";
return;
}
std::vector<const char*> required_extensions;
for (const auto& ext : kRequiredDeviceExtensions) {
required_extensions.push_back(ext.data());
}
const auto queue_create_infos = GetQueueCreateInfos(
{graphics_queue.value(), compute_queue.value(), transfer_queue.value()});
const auto required_features = GetRequiredPhysicalDeviceFeatures();
vk::DeviceCreateInfo device_info;
device_info.setQueueCreateInfos(queue_create_infos);
device_info.setPEnabledExtensionNames(required_extensions);
device_info.setPEnabledFeatures(&required_features);
// Device layers are deprecated and ignored.
auto device = physical_device->createDeviceUnique(device_info);
if (device.result != vk::Result::eSuccess) {
VALIDATION_LOG << "Could not create logical device.";
return;
}
auto allocator = std::shared_ptr<AllocatorVK>(new AllocatorVK(
application_info.apiVersion, //
physical_device.value(), //
device.value.get(), //
instance.value.get(), //
dispatcher.vkGetInstanceProcAddr, //
dispatcher.vkGetDeviceProcAddr //
));
if (!allocator->IsValid()) {
VALIDATION_LOG << "Could not create memory allocator.";
return;
}
auto pipeline_library = std::shared_ptr<PipelineLibraryVK>(
new PipelineLibraryVK(device.value.get(), //
pipeline_cache_data, //
worker_task_runner_ //
));
if (!pipeline_library->IsValid()) {
VALIDATION_LOG << "Could not create pipeline library.";
return;
}
auto sampler_library = std::shared_ptr<SamplerLibraryVK>(
new SamplerLibraryVK(device.value.get()));
auto shader_library = std::shared_ptr<ShaderLibraryVK>(
new ShaderLibraryVK(device.value.get(), shader_libraries_data));
if (!shader_library->IsValid()) {
VALIDATION_LOG << "Could not create shader library.";
return;
}
instance_ = std::move(instance.value);
debug_messenger_ = std::move(debug_messenger);
device_ = std::move(device.value);
allocator_ = std::move(allocator);
shader_library_ = std::move(shader_library);
sampler_library_ = std::move(sampler_library);
pipeline_library_ = std::move(pipeline_library);
graphics_queue_ =
device_->getQueue(graphics_queue->family, graphics_queue->index);
compute_queue_ =
device_->getQueue(compute_queue->family, compute_queue->index);
transfer_queue_ =
device_->getQueue(transfer_queue->family, transfer_queue->index);
is_valid_ = true;
}
ContextVK::~ContextVK() = default;
bool ContextVK::IsValid() const {
return is_valid_;
}
std::shared_ptr<Allocator> ContextVK::GetPermanentsAllocator() const {
return allocator_;
}
std::shared_ptr<Allocator> ContextVK::GetTransientsAllocator() const {
return allocator_;
}
std::shared_ptr<ShaderLibrary> ContextVK::GetShaderLibrary() const {
return shader_library_;
}
std::shared_ptr<SamplerLibrary> ContextVK::GetSamplerLibrary() const {
return sampler_library_;
}
std::shared_ptr<PipelineLibrary> ContextVK::GetPipelineLibrary() const {
return pipeline_library_;
}
std::shared_ptr<CommandBuffer> ContextVK::CreateRenderCommandBuffer() const {
FML_UNREACHABLE();
}
std::shared_ptr<CommandBuffer> ContextVK::CreateTransferCommandBuffer() const {
FML_UNREACHABLE();
}
} // namespace impeller

View File

@@ -0,0 +1,82 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#pragma once
#include <memory>
#include "flutter/fml/concurrent_message_loop.h"
#include "flutter/fml/macros.h"
#include "flutter/fml/mapping.h"
#include "impeller/base/backend_cast.h"
#include "impeller/renderer/backend/vulkan/allocator_vk.h"
#include "impeller/renderer/backend/vulkan/pipeline_library_vk.h"
#include "impeller/renderer/backend/vulkan/sampler_library_vk.h"
#include "impeller/renderer/backend/vulkan/shader_library_vk.h"
#include "impeller/renderer/backend/vulkan/vk.h"
#include "impeller/renderer/context.h"
namespace impeller {
class ContextVK final : public Context, public BackendCast<ContextVK, Context> {
public:
static std::shared_ptr<ContextVK> Create(
PFN_vkGetInstanceProcAddr proc_address_callback,
const std::vector<std::shared_ptr<fml::Mapping>>& shader_libraries_data,
const std::shared_ptr<const fml::Mapping>& pipeline_cache_data,
std::shared_ptr<fml::ConcurrentTaskRunner> worker_task_runner,
const std::string& label);
// |Context|
~ContextVK() override;
// |Context|
bool IsValid() const override;
private:
std::shared_ptr<fml::ConcurrentTaskRunner> worker_task_runner_;
vk::UniqueInstance instance_;
vk::UniqueDebugUtilsMessengerEXT debug_messenger_;
vk::UniqueDevice device_;
std::shared_ptr<AllocatorVK> allocator_;
std::shared_ptr<ShaderLibraryVK> shader_library_;
std::shared_ptr<SamplerLibraryVK> sampler_library_;
std::shared_ptr<PipelineLibraryVK> pipeline_library_;
vk::Queue graphics_queue_;
vk::Queue compute_queue_;
vk::Queue transfer_queue_;
bool is_valid_ = false;
ContextVK(
PFN_vkGetInstanceProcAddr proc_address_callback,
const std::vector<std::shared_ptr<fml::Mapping>>& shader_libraries_data,
const std::shared_ptr<const fml::Mapping>& pipeline_cache_data,
std::shared_ptr<fml::ConcurrentTaskRunner> worker_task_runner,
const std::string& label);
// |Context|
std::shared_ptr<Allocator> GetPermanentsAllocator() const override;
// |Context|
std::shared_ptr<Allocator> GetTransientsAllocator() const override;
// |Context|
std::shared_ptr<ShaderLibrary> GetShaderLibrary() const override;
// |Context|
std::shared_ptr<SamplerLibrary> GetSamplerLibrary() const override;
// |Context|
std::shared_ptr<PipelineLibrary> GetPipelineLibrary() const override;
// |Context|
std::shared_ptr<CommandBuffer> CreateRenderCommandBuffer() const override;
// |Context|
std::shared_ptr<CommandBuffer> CreateTransferCommandBuffer() const override;
FML_DISALLOW_COPY_AND_ASSIGN(ContextVK);
};
} // namespace impeller

View File

@@ -0,0 +1,11 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/renderer/backend/vulkan/device_buffer_vk.h"
namespace impeller {
//
} // namespace impeller

View File

@@ -0,0 +1,38 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#pragma once
#include "flutter/fml/macros.h"
#include "impeller/base/backend_cast.h"
#include "impeller/renderer/device_buffer.h"
namespace impeller {
class DeviceBufferVK final : public DeviceBuffer,
public BackendCast<DeviceBufferVK, DeviceBuffer> {
public:
// |DeviceBuffer|
~DeviceBufferVK() override;
private:
friend class AllocatorVK;
DeviceBufferVK(size_t size, StorageMode mode);
// |DeviceBuffer|
bool CopyHostBuffer(const uint8_t* source,
Range source_range,
size_t offset) override;
// |DeviceBuffer|
bool SetLabel(const std::string& label) override;
// |DeviceBuffer|
bool SetLabel(const std::string& label, Range range) override;
FML_DISALLOW_COPY_AND_ASSIGN(DeviceBufferVK);
};
} // namespace impeller

View File

@@ -0,0 +1,11 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/renderer/backend/vulkan/formats_vk.h"
namespace impeller {
//
} // namespace impeller

View File

@@ -0,0 +1,135 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#pragma once
#include "flutter/fml/macros.h"
#include "impeller/renderer/backend/vulkan/vk.h"
#include "impeller/renderer/formats.h"
#include "impeller/renderer/shader_types.h"
namespace impeller {
constexpr vk::SampleCountFlagBits ToVKSampleCountFlagBits(SampleCount count) {
switch (count) {
case SampleCount::kCount1:
return vk::SampleCountFlagBits::e1;
case SampleCount::kCount4:
return vk::SampleCountFlagBits::e4;
}
FML_UNREACHABLE();
}
constexpr vk::BlendFactor ToVKBlendFactor(BlendFactor factor) {
switch (factor) {
case BlendFactor::kZero:
return vk::BlendFactor::eZero;
case BlendFactor::kOne:
return vk::BlendFactor::eOne;
case BlendFactor::kSourceColor:
return vk::BlendFactor::eSrcColor;
case BlendFactor::kOneMinusSourceColor:
return vk::BlendFactor::eOneMinusSrcColor;
case BlendFactor::kSourceAlpha:
return vk::BlendFactor::eSrcAlpha;
case BlendFactor::kOneMinusSourceAlpha:
return vk::BlendFactor::eOneMinusSrcAlpha;
case BlendFactor::kDestinationColor:
return vk::BlendFactor::eDstColor;
case BlendFactor::kOneMinusDestinationColor:
return vk::BlendFactor::eOneMinusDstColor;
case BlendFactor::kDestinationAlpha:
return vk::BlendFactor::eDstAlpha;
case BlendFactor::kOneMinusDestinationAlpha:
return vk::BlendFactor::eOneMinusDstAlpha;
case BlendFactor::kSourceAlphaSaturated:
return vk::BlendFactor::eSrcAlphaSaturate;
case BlendFactor::kBlendColor:
return vk::BlendFactor::eConstantColor;
case BlendFactor::kOneMinusBlendColor:
return vk::BlendFactor::eOneMinusConstantColor;
case BlendFactor::kBlendAlpha:
return vk::BlendFactor::eConstantAlpha;
case BlendFactor::kOneMinusBlendAlpha:
return vk::BlendFactor::eOneMinusConstantAlpha;
}
FML_UNREACHABLE();
}
constexpr vk::BlendOp ToVKBlendOp(BlendOperation op) {
switch (op) {
case BlendOperation::kAdd:
return vk::BlendOp::eAdd;
case BlendOperation::kSubtract:
return vk::BlendOp::eSubtract;
case BlendOperation::kReverseSubtract:
return vk::BlendOp::eReverseSubtract;
}
FML_UNREACHABLE();
}
constexpr vk::ColorComponentFlags ToVKColorComponentFlags(
std::underlying_type_t<ColorWriteMask> type) {
using UnderlyingType = decltype(type);
vk::ColorComponentFlags mask;
if (type & static_cast<UnderlyingType>(ColorWriteMask::kRed)) {
mask |= vk::ColorComponentFlagBits::eR;
}
if (type & static_cast<UnderlyingType>(ColorWriteMask::kGreen)) {
mask |= vk::ColorComponentFlagBits::eG;
}
if (type & static_cast<UnderlyingType>(ColorWriteMask::kBlue)) {
mask |= vk::ColorComponentFlagBits::eB;
}
if (type & static_cast<UnderlyingType>(ColorWriteMask::kAlpha)) {
mask |= vk::ColorComponentFlagBits::eA;
}
return mask;
}
constexpr vk::PipelineColorBlendAttachmentState
ToVKPipelineColorBlendAttachmentState(const ColorAttachmentDescriptor& desc) {
vk::PipelineColorBlendAttachmentState res;
res.setBlendEnable(desc.blending_enabled);
res.setSrcColorBlendFactor(ToVKBlendFactor(desc.src_color_blend_factor));
res.setColorBlendOp(ToVKBlendOp(desc.color_blend_op));
res.setDstColorBlendFactor(ToVKBlendFactor(desc.dst_color_blend_factor));
res.setSrcAlphaBlendFactor(ToVKBlendFactor(desc.src_alpha_blend_factor));
res.setAlphaBlendOp(ToVKBlendOp(desc.alpha_blend_op));
res.setDstAlphaBlendFactor(ToVKBlendFactor(desc.dst_alpha_blend_factor));
res.setColorWriteMask(ToVKColorComponentFlags(desc.write_mask));
return res;
}
constexpr std::optional<vk::ShaderStageFlagBits> ToVKShaderStageFlagBits(
ShaderStage stage) {
switch (stage) {
case ShaderStage::kUnknown:
return std::nullopt;
case ShaderStage::kVertex:
return vk::ShaderStageFlagBits::eVertex;
case ShaderStage::kFragment:
return vk::ShaderStageFlagBits::eFragment;
case ShaderStage::kTessellationControl:
return vk::ShaderStageFlagBits::eTessellationControl;
case ShaderStage::kTessellationEvaluation:
return vk::ShaderStageFlagBits::eTessellationEvaluation;
case ShaderStage::kCompute:
return vk::ShaderStageFlagBits::eCompute;
}
FML_UNREACHABLE();
}
} // namespace impeller

View File

@@ -0,0 +1,286 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/renderer/backend/vulkan/pipeline_library_vk.h"
#include "flutter/fml/trace_event.h"
#include "impeller/base/promise.h"
#include "impeller/base/validation.h"
#include "impeller/renderer/backend/vulkan/formats_vk.h"
#include "impeller/renderer/backend/vulkan/shader_function_vk.h"
namespace impeller {
PipelineLibraryVK::PipelineLibraryVK(
const vk::Device& device,
const std::shared_ptr<const fml::Mapping>& pipeline_cache_data,
std::shared_ptr<fml::ConcurrentTaskRunner> worker_task_runner)
: worker_task_runner_(std::move(worker_task_runner)) {
if (!worker_task_runner_) {
return;
}
vk::PipelineCacheCreateInfo cache_info;
if (pipeline_cache_data) {
cache_info.pInitialData = pipeline_cache_data->GetMapping();
cache_info.initialDataSize = pipeline_cache_data->GetSize();
}
auto cache = device.createPipelineCacheUnique(cache_info);
if (cache.result != vk::Result::eSuccess) {
VALIDATION_LOG << "Could not create pipeline cache.";
return;
}
device_ = device;
cache_ = std::move(cache.value);
is_valid_ = true;
}
PipelineLibraryVK::~PipelineLibraryVK() = default;
// |PipelineLibrary|
bool PipelineLibraryVK::IsValid() const {
return is_valid_;
}
// |PipelineLibrary|
PipelineFuture PipelineLibraryVK::GetRenderPipeline(
PipelineDescriptor descriptor) {
Lock lock(pipelines_mutex_);
if (auto found = pipelines_.find(descriptor); found != pipelines_.end()) {
return found->second;
}
if (!IsValid()) {
return RealizedFuture<std::shared_ptr<Pipeline>>(nullptr);
}
auto promise = std::make_shared<std::promise<std::shared_ptr<Pipeline>>>();
auto future = PipelineFuture{promise->get_future()};
pipelines_[descriptor] = future;
auto weak_this = weak_from_this();
worker_task_runner_->PostTask([descriptor, weak_this, promise]() {
auto thiz = weak_this.lock();
if (!thiz) {
promise->set_value(nullptr);
VALIDATION_LOG << "Pipeline library was collected before the pipeline "
"could be created.";
return;
}
promise->set_value(
PipelineLibraryVK::Cast(thiz.get())->CreatePipeline(descriptor));
});
return future;
}
static vk::AttachmentDescription CreatePlaceholderAttachmentDescription(
vk::Format format,
SampleCount sample_count) {
vk::AttachmentDescription desc;
// See
// https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/chap8.html#renderpass-compatibility
// Format and samples must match for sub-pass compatibility
desc.setFormat(format);
desc.setSamples(ToVKSampleCountFlagBits(sample_count));
// The rest of these are placeholders and the right values will be set when
// the render-pass to be used with the framebuffer is created.
desc.setLoadOp(vk::AttachmentLoadOp::eDontCare);
desc.setStoreOp(vk::AttachmentStoreOp::eDontCare);
desc.setStencilLoadOp(vk::AttachmentLoadOp::eDontCare);
desc.setStencilStoreOp(vk::AttachmentStoreOp::eDontCare);
desc.setInitialLayout(vk::ImageLayout::eUndefined);
desc.setFinalLayout(vk::ImageLayout::eGeneral);
return desc;
}
std::shared_ptr<PipelineVK> PipelineLibraryVK::CreatePipeline(
const PipelineDescriptor& desc) const {
TRACE_EVENT0("flutter", __FUNCTION__);
vk::GraphicsPipelineCreateInfo pipeline_info;
//----------------------------------------------------------------------------
/// Dynamic States
///
vk::PipelineDynamicStateCreateInfo dynamic_state_info;
std::vector<vk::DynamicState> dynamic_states = {
vk::DynamicState::eViewport,
vk::DynamicState::eScissor,
vk::DynamicState::eStencilReference,
};
dynamic_state_info.setDynamicStates(dynamic_states);
pipeline_info.setPDynamicState(&dynamic_state_info);
//----------------------------------------------------------------------------
/// Viewport State
///
vk::PipelineViewportStateCreateInfo viewport_state;
viewport_state.setViewportCount(1u);
viewport_state.setScissorCount(1u);
// The actual viewport and scissor rects are not set here since they are
// dynamic as mentioned above in the dynamic state info.
pipeline_info.setPViewportState(&viewport_state);
//----------------------------------------------------------------------------
/// Shader Stages
///
std::vector<vk::PipelineShaderStageCreateInfo> shader_stages;
for (const auto& entrypoint : desc.GetStageEntrypoints()) {
auto stage = ToVKShaderStageFlagBits(entrypoint.first);
if (!stage.has_value()) {
VALIDATION_LOG << "Unsupported shader type in pipeline: "
<< desc.GetLabel();
return nullptr;
}
vk::PipelineShaderStageCreateInfo info;
info.setStage(stage.value());
info.setPName("main");
info.setModule(
ShaderFunctionVK::Cast(entrypoint.second.get())->GetModule());
shader_stages.push_back(std::move(info));
}
pipeline_info.setStages(shader_stages);
//----------------------------------------------------------------------------
/// Rasterization State
/// TODO(106380): Move front face and cull mode to pipeline state instead of
/// draw command. These are hard-coded here for now.
///
vk::PipelineRasterizationStateCreateInfo rasterization_state;
rasterization_state.setFrontFace(vk::FrontFace::eClockwise);
rasterization_state.setCullMode(vk::CullModeFlagBits::eNone);
rasterization_state.setPolygonMode(vk::PolygonMode::eFill);
rasterization_state.setLineWidth(1.0f);
pipeline_info.setPRasterizationState(&rasterization_state);
//----------------------------------------------------------------------------
/// Multi-sample State
///
vk::PipelineMultisampleStateCreateInfo multisample_state;
multisample_state.setRasterizationSamples(
ToVKSampleCountFlagBits(desc.GetSampleCount()));
pipeline_info.setPMultisampleState(&multisample_state);
//----------------------------------------------------------------------------
/// Primitive Input Assembly State
/// TODO(106379): Move primitive topology to the the pipeline instead of it
/// being on the draw call. This is hard-coded right now.
///
vk::PipelineInputAssemblyStateCreateInfo input_assembly;
input_assembly.setTopology(vk::PrimitiveTopology::eTriangleList);
pipeline_info.setPInputAssemblyState(&input_assembly);
//----------------------------------------------------------------------------
/// Color Blend State
///
std::vector<vk::PipelineColorBlendAttachmentState> attachment_blend_state;
for (const auto& color_desc : desc.GetColorAttachmentDescriptors()) {
// TODO(csg): The blend states are per color attachment. But it isn't clear
// how the color attachment indices are specified in the pipeline create
// info. But, this should always work for one color attachment.
attachment_blend_state.push_back(
ToVKPipelineColorBlendAttachmentState(color_desc.second));
}
vk::PipelineColorBlendStateCreateInfo blend_state;
blend_state.setAttachments(attachment_blend_state);
pipeline_info.setPColorBlendState(&blend_state);
//----------------------------------------------------------------------------
/// Render Pass
/// We are NOT going to use the same render pass with the framebuffer (later)
/// and the graphics pipeline (here). Instead, we are going to ensure that the
/// sub-passes are compatible. To see the compatibility rules, see the Vulkan
/// spec:
/// https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/chap8.html#renderpass-compatibility
/// TODO(106378): Add a format specifier to the ColorAttachmentDescriptor,
/// StencilAttachmentDescriptor, and, DepthAttachmentDescriptor.
/// Right now, these are placeholders.
///
std::vector<vk::AttachmentReference> color_attachment_references;
std::vector<vk::AttachmentReference> resolve_attachment_references;
std::optional<vk::AttachmentReference> depth_stencil_attachment_reference;
std::vector<vk::AttachmentDescription> render_pass_attachments;
const auto sample_count = desc.GetSampleCount();
// Set the color attachment.
render_pass_attachments.push_back(CreatePlaceholderAttachmentDescription(
vk::Format::eR8G8B8A8Unorm, sample_count));
color_attachment_references.push_back(vk::AttachmentReference(
render_pass_attachments.size() - 1u, vk::ImageLayout::eGeneral));
// Set the resolve attachment if MSAA is enabled.
if (sample_count != SampleCount::kCount1) {
render_pass_attachments.push_back(CreatePlaceholderAttachmentDescription(
vk::Format::eR8G8B8A8Unorm, SampleCount::kCount1));
resolve_attachment_references.push_back(vk::AttachmentReference(
render_pass_attachments.size() - 1u, vk::ImageLayout::eGeneral));
}
if (desc.HasStencilAttachmentDescriptors()) {
render_pass_attachments.push_back(CreatePlaceholderAttachmentDescription(
vk::Format::eS8Uint, sample_count));
depth_stencil_attachment_reference = vk::AttachmentReference(
render_pass_attachments.size() - 1u, vk::ImageLayout::eGeneral);
}
vk::SubpassDescription subpass_info;
subpass_info.setPipelineBindPoint(vk::PipelineBindPoint::eGraphics);
subpass_info.setColorAttachments(color_attachment_references);
subpass_info.setResolveAttachments(resolve_attachment_references);
if (depth_stencil_attachment_reference.has_value()) {
subpass_info.setPDepthStencilAttachment(
&depth_stencil_attachment_reference.value());
}
vk::RenderPassCreateInfo render_pass_info;
render_pass_info.setSubpasses(subpass_info);
render_pass_info.setAttachments(render_pass_attachments);
auto render_pass = device_.createRenderPassUnique(render_pass_info);
if (render_pass.result != vk::Result::eSuccess) {
VALIDATION_LOG << "Could not create render pass for pipeline "
<< desc.GetLabel() << ": "
<< vk::to_string(render_pass.result);
return nullptr;
}
pipeline_info.setRenderPass(render_pass.value.get());
//----------------------------------------------------------------------------
/// Pipeline Layout a.k.a the descriptor sets and uniforms.
///
std::vector<vk::DescriptorSetLayout> descriptor_set_layouts;
// TODO(106377): Wire this up from the C++ generated headers.
vk::PipelineLayoutCreateInfo pipeline_layout_info;
pipeline_layout_info.setSetLayouts(descriptor_set_layouts);
auto pipeline_layout =
device_.createPipelineLayoutUnique(pipeline_layout_info);
if (pipeline_layout.result != vk::Result::eSuccess) {
VALIDATION_LOG << "Could not create pipeline layout for pipeline "
<< desc.GetLabel() << ": "
<< vk::to_string(pipeline_layout.result);
return nullptr;
}
pipeline_info.setLayout(pipeline_layout.value.get());
// TODO(WIP)
// pipeline_info.setPVertexInputState(&vertex_input_state);
// pipeline_info.setPDepthStencilState(&depth_stencil_state_);
// pipeline_info.setLayout(pipeline_layout);
// See the note in the header about why this is a reader lock.
ReaderLock lock(cache_mutex_);
auto pipeline =
device_.createGraphicsPipelineUnique(cache_.get(), pipeline_info);
if (pipeline.result != vk::Result::eSuccess) {
VALIDATION_LOG << "Could not create graphics pipeline: " << desc.GetLabel();
return nullptr;
}
FML_UNREACHABLE();
}
} // namespace impeller

View File

@@ -0,0 +1,61 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#pragma once
#include "flutter/fml/concurrent_message_loop.h"
#include "flutter/fml/macros.h"
#include "flutter/fml/mapping.h"
#include "impeller/base/backend_cast.h"
#include "impeller/base/thread.h"
#include "impeller/renderer/backend/vulkan/pipeline_vk.h"
#include "impeller/renderer/backend/vulkan/vk.h"
#include "impeller/renderer/pipeline_library.h"
namespace impeller {
class ContextVK;
class PipelineLibraryVK final
: public PipelineLibrary,
public BackendCast<PipelineLibraryVK, PipelineLibrary> {
public:
// |PipelineLibrary|
~PipelineLibraryVK() override;
private:
friend ContextVK;
vk::Device device_;
// On locking around the pipeline cache: The cache is internally synchronized.
// So there is no need to hold a writer lock around its use when pipelines are
// being created. The time it takes for implementations to spend within the
// critical section of the cache is limited compared to the time it
// takes for the "create pipeline" call itself. The writer lock is only
// necessary when fetching pipeline cache data for persisting to disk.
mutable RWMutex cache_mutex_;
vk::UniquePipelineCache cache_ IPLR_GUARDED_BY(cache_mutex_);
std::shared_ptr<fml::ConcurrentTaskRunner> worker_task_runner_;
Mutex pipelines_mutex_;
PipelineMap pipelines_ IPLR_GUARDED_BY(pipelines_mutex_);
bool is_valid_ = false;
PipelineLibraryVK(
const vk::Device& device,
const std::shared_ptr<const fml::Mapping>& pipeline_cache_data,
std::shared_ptr<fml::ConcurrentTaskRunner> worker_task_runner);
// |PipelineLibrary|
bool IsValid() const override;
// |PipelineLibrary|
PipelineFuture GetRenderPipeline(PipelineDescriptor descriptor) override;
std::shared_ptr<PipelineVK> CreatePipeline(
const PipelineDescriptor& desc) const;
FML_DISALLOW_COPY_AND_ASSIGN(PipelineLibraryVK);
};
} // namespace impeller

View File

@@ -0,0 +1,11 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/renderer/backend/vulkan/pipeline_vk.h"
namespace impeller {
//
} // namespace impeller

View File

@@ -0,0 +1,30 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#pragma once
#include "flutter/fml/macros.h"
#include "impeller/base/backend_cast.h"
#include "impeller/renderer/pipeline.h"
namespace impeller {
class PipelineVK final : public Pipeline,
public BackendCast<PipelineVK, Pipeline> {
public:
// |Pipeline|
~PipelineVK() override;
private:
friend class PipelineLibraryMTL;
PipelineVK(std::weak_ptr<PipelineLibrary> library, PipelineDescriptor desc);
// |Pipeline|
bool IsValid() const override;
FML_DISALLOW_COPY_AND_ASSIGN(PipelineVK);
};
} // namespace impeller

View File

@@ -0,0 +1,11 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/renderer/backend/vulkan/render_pass_vk.h"
namespace impeller {
//
} // namespace impeller

View File

@@ -0,0 +1,36 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#pragma once
#include "flutter/fml/macros.h"
#include "impeller/renderer/render_pass.h"
#include "impeller/renderer/render_target.h"
namespace impeller {
class RenderPassVK final : public RenderPass {
public:
// |RenderPass|
~RenderPassVK() override;
private:
friend class CommandBufferVK;
RenderPassVK(RenderTarget target);
// |RenderPass|
bool IsValid() const override;
// |RenderPass|
void OnSetLabel(std::string label) override;
// |RenderPass|
bool EncodeCommands(
const std::shared_ptr<Allocator>& transients_allocator) const override;
FML_DISALLOW_COPY_AND_ASSIGN(RenderPassVK);
};
} // namespace impeller

View File

@@ -0,0 +1,18 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/renderer/backend/vulkan/sampler_library_vk.h"
namespace impeller {
SamplerLibraryVK::SamplerLibraryVK(vk::Device device) : device_(device) {}
SamplerLibraryVK::~SamplerLibraryVK() = default;
std::shared_ptr<const Sampler> SamplerLibraryVK::GetSampler(
SamplerDescriptor descriptor) {
FML_UNREACHABLE();
}
} // namespace impeller

View File

@@ -0,0 +1,38 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#pragma once
#include "flutter/fml/macros.h"
#include "impeller/base/backend_cast.h"
#include "impeller/base/comparable.h"
#include "impeller/renderer/backend/vulkan/vk.h"
#include "impeller/renderer/sampler_descriptor.h"
#include "impeller/renderer/sampler_library.h"
namespace impeller {
class SamplerLibraryVK final
: public SamplerLibrary,
public BackendCast<SamplerLibraryVK, SamplerLibrary> {
public:
// |SamplerLibrary|
~SamplerLibraryVK() override;
private:
friend class ContextVK;
vk::Device device_;
SamplerMap samplers_;
SamplerLibraryVK(vk::Device device);
// |SamplerLibrary|
std::shared_ptr<const Sampler> GetSampler(
SamplerDescriptor descriptor) override;
FML_DISALLOW_COPY_AND_ASSIGN(SamplerLibraryVK);
};
} // namespace impeller

View File

@@ -0,0 +1,11 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/renderer/backend/vulkan/sampler_vk.h"
namespace impeller {
//
} // namespace impeller

View File

@@ -0,0 +1,33 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#pragma once
#include "flutter/fml/macros.h"
#include "impeller/base/backend_cast.h"
#include "impeller/renderer/sampler.h"
namespace impeller {
class SamplerLibraryVK;
class SamplerVK final : public Sampler, public BackendCast<SamplerVK, Sampler> {
public:
SamplerVK();
// |Sampler|
~SamplerVK() override;
private:
friend SamplerLibraryVK;
SamplerVK(SamplerDescriptor desc);
// |Sampler|
bool IsValid() const override;
FML_DISALLOW_COPY_AND_ASSIGN(SamplerVK);
};
} // namespace impeller

View File

@@ -0,0 +1,22 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/renderer/backend/vulkan/shader_function_vk.h"
namespace impeller {
ShaderFunctionVK::ShaderFunctionVK(UniqueID parent_library_id,
std::string name,
ShaderStage stage,
vk::UniqueShaderModule module)
: ShaderFunction(parent_library_id, std::move(name), stage),
module_(std::move(module)) {}
ShaderFunctionVK::~ShaderFunctionVK() = default;
const vk::ShaderModule& ShaderFunctionVK::GetModule() const {
return module_.get();
}
} // namespace impeller

View File

@@ -0,0 +1,37 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#pragma once
#include "flutter/fml/macros.h"
#include "impeller/base/backend_cast.h"
#include "impeller/renderer/backend/vulkan/shader_function_vk.h"
#include "impeller/renderer/backend/vulkan/vk.h"
#include "impeller/renderer/shader_function.h"
namespace impeller {
class ShaderFunctionVK final
: public ShaderFunction,
public BackendCast<ShaderFunctionVK, ShaderFunction> {
public:
// |ShaderFunction|
~ShaderFunctionVK() override;
const vk::ShaderModule& GetModule() const;
private:
friend class ShaderLibraryVK;
vk::UniqueShaderModule module_;
ShaderFunctionVK(UniqueID parent_library_id,
std::string name,
ShaderStage stage,
vk::UniqueShaderModule module);
FML_DISALLOW_COPY_AND_ASSIGN(ShaderFunctionVK);
};
} // namespace impeller

View File

@@ -0,0 +1,123 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/renderer/backend/vulkan/shader_library_vk.h"
#include "flutter/fml/logging.h"
#include "flutter/fml/trace_event.h"
#include "impeller/blobcat/blob_library.h"
#include "impeller/renderer/backend/vulkan/shader_function_vk.h"
namespace impeller {
static ShaderStage ToShaderStage(Blob::ShaderType type) {
switch (type) {
case Blob::ShaderType::kVertex:
return ShaderStage::kVertex;
case Blob::ShaderType::kFragment:
return ShaderStage::kFragment;
}
FML_UNREACHABLE();
}
static std::string VKShaderNameToShaderKeyName(const std::string& name,
ShaderStage stage) {
std::stringstream stream;
stream << name;
switch (stage) {
case ShaderStage::kUnknown:
stream << "_unknown_";
break;
case ShaderStage::kVertex:
stream << "_vertex_";
break;
case ShaderStage::kFragment:
stream << "_fragment_";
break;
case ShaderStage::kTessellationControl:
stream << "_tessellation_control_";
break;
case ShaderStage::kTessellationEvaluation:
stream << "_tessellation_evaluation_";
break;
case ShaderStage::kCompute:
stream << "_compute_";
break;
}
stream << "main";
return stream.str();
}
ShaderLibraryVK::ShaderLibraryVK(
const vk::Device& device,
const std::vector<std::shared_ptr<fml::Mapping>>& shader_libraries_data) {
TRACE_EVENT0("impeller", "ShaderLibraryCreate");
ShaderFunctionMap functions;
bool success = true;
auto iterator = [&success, &device, &functions, library_id = library_id_](
auto type, //
const auto& name, //
const auto& mapping //
) -> bool {
vk::ShaderModuleCreateInfo shader_module_info;
shader_module_info.setPCode(
reinterpret_cast<const uint32_t*>(mapping->GetMapping()));
shader_module_info.setCodeSize(mapping->GetSize());
auto module = device.createShaderModuleUnique(shader_module_info);
if (module.result != vk::Result::eSuccess) {
VALIDATION_LOG << "Could not create shader module: "
<< vk::to_string(module.result);
success = false;
return false;
}
const auto stage = ToShaderStage(type);
const auto key_name = VKShaderNameToShaderKeyName(name, stage);
functions[ShaderKey{key_name, stage}] = std::shared_ptr<ShaderFunctionVK>(
new ShaderFunctionVK(library_id, //
key_name, //
stage, //
std::move(module.value) //
));
return true;
};
for (const auto& library_data : shader_libraries_data) {
auto blob_library = BlobLibrary{library_data};
if (!blob_library.IsValid()) {
VALIDATION_LOG << "Could not construct shader blob library.";
return;
}
blob_library.IterateAllBlobs(iterator);
}
if (!success) {
return;
}
functions_ = std::move(functions);
is_valid_ = true;
}
ShaderLibraryVK::~ShaderLibraryVK() = default;
bool ShaderLibraryVK::IsValid() const {
return is_valid_;
}
std::shared_ptr<const ShaderFunction> ShaderLibraryVK::GetFunction(
std::string_view name,
ShaderStage stage) {
const auto key = ShaderKey{{name.data(), name.size()}, stage};
auto found = functions_.find(key);
if (found != functions_.end()) {
return found->second;
}
return nullptr;
}
} // namespace impeller

View File

@@ -0,0 +1,40 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#pragma once
#include "flutter/fml/macros.h"
#include "impeller/base/comparable.h"
#include "impeller/renderer/backend/vulkan/vk.h"
#include "impeller/renderer/shader_key.h"
#include "impeller/renderer/shader_library.h"
namespace impeller {
class ShaderLibraryVK final : public ShaderLibrary {
public:
// |ShaderLibrary|
~ShaderLibraryVK() override;
// |ShaderLibrary|
bool IsValid() const override;
private:
friend class ContextVK;
const UniqueID library_id_;
ShaderFunctionMap functions_;
bool is_valid_ = false;
ShaderLibraryVK(
const vk::Device& device,
const std::vector<std::shared_ptr<fml::Mapping>>& shader_libraries_data);
// |ShaderLibrary|
std::shared_ptr<const ShaderFunction> GetFunction(std::string_view name,
ShaderStage stage) override;
FML_DISALLOW_COPY_AND_ASSIGN(ShaderLibraryVK);
};
} // namespace impeller

View File

@@ -0,0 +1,11 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/renderer/backend/vulkan/surface_vk.h"
namespace impeller {
//
} // namespace impeller

View File

@@ -0,0 +1,27 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#pragma once
#include "flutter/fml/macros.h"
#include "impeller/renderer/context.h"
#include "impeller/renderer/surface.h"
namespace impeller {
class SurfaceVK final : public Surface {
public:
// |Surface|
~SurfaceVK() override;
private:
SurfaceVK(RenderTarget target);
// |Surface|
bool Present() const override;
FML_DISALLOW_COPY_AND_ASSIGN(SurfaceVK);
};
} // namespace impeller

View File

@@ -0,0 +1,11 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/renderer/backend/vulkan/texture_vk.h"
namespace impeller {
//
} // namespace impeller

View File

@@ -0,0 +1,42 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#pragma once
#include "flutter/fml/macros.h"
#include "impeller/base/backend_cast.h"
#include "impeller/renderer/texture.h"
namespace impeller {
class TextureVK final : public Texture, public BackendCast<TextureVK, Texture> {
public:
TextureVK(TextureDescriptor desc);
// |Texture|
~TextureVK() override;
private:
// |Texture|
void SetLabel(std::string_view label) override;
// |Texture|
bool OnSetContents(const uint8_t* contents,
size_t length,
size_t slice) override;
// |Texture|
bool OnSetContents(std::shared_ptr<const fml::Mapping> mapping,
size_t slice) override;
// |Texture|
bool IsValid() const override;
// |Texture|
ISize GetSize() const override;
FML_DISALLOW_COPY_AND_ASSIGN(TextureVK);
};
} // namespace impeller

View File

@@ -0,0 +1,13 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/renderer/backend/vulkan/vertex_descriptor_vk.h"
namespace impeller {
VertexDescriptorVK::VertexDescriptorVK() = default;
VertexDescriptorVK::~VertexDescriptorVK() = default;
} // namespace impeller

View File

@@ -0,0 +1,21 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#pragma once
#include "flutter/fml/macros.h"
namespace impeller {
class VertexDescriptorVK {
public:
VertexDescriptorVK();
~VertexDescriptorVK();
private:
FML_DISALLOW_COPY_AND_ASSIGN(VertexDescriptorVK);
};
} // namespace impeller

View File

@@ -0,0 +1,40 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#pragma once
#include "flutter/fml/logging.h"
#include "impeller/base/validation.h"
#define VK_NO_PROTOTYPES
#define VULKAN_HPP_ASSERT FML_CHECK
#define VULKAN_HPP_NAMESPACE impeller::vk
#define VULKAN_HPP_ASSERT_ON_RESULT(ignored) \
{ [[maybe_unused]] auto res = (ignored); }
#define VULKAN_HPP_NO_EXCEPTIONS
#include "vulkan/vulkan.hpp"
static_assert(VK_HEADER_VERSION >= 215,
"Vulkan headers are must not be too old.");
#ifdef VMA_STATIC_VULKAN_FUNCTIONS
#undef VMA_STATIC_VULKAN_FUNCTIONS
#endif // VMA_STATIC_VULKAN_FUNCTIONS
#ifdef VMA_DYNAMIC_VULKAN_FUNCTIONS
#undef VMA_DYNAMIC_VULKAN_FUNCTIONS
#endif // VMA_DYNAMIC_VULKAN_FUNCTIONS
#define VMA_STATIC_VULKAN_FUNCTIONS 0
#define VMA_DYNAMIC_VULKAN_FUNCTIONS 1
#include "vk_mem_alloc.h"
namespace impeller {
struct QueueVK {
size_t family = 0;
size_t index = 0;
};
} // namespace impeller

View File

@@ -21,6 +21,8 @@ class PipelineLibrary : public std::enable_shared_from_this<PipelineLibrary> {
PipelineFuture GetRenderPipeline(
std::optional<PipelineDescriptor> descriptor);
virtual bool IsValid() const = 0;
virtual PipelineFuture GetRenderPipeline(PipelineDescriptor descriptor) = 0;
protected:

View File

@@ -17,7 +17,10 @@ declare_args() {
impeller_enable_metal = is_mac || is_ios
# Whether the OpenGLES backend is enabled.
impeller_enable_opengles = is_mac || is_linux || is_android || is_win
impeller_enable_opengles = is_mac || is_linux || is_android
# Whether the Vulkan backend is enabled.
impeller_enable_vulkan = false
# Whether to use a prebuilt impellerc.
# If this is the empty string, impellerc will be built.
@@ -35,11 +38,13 @@ declare_args() {
declare_args() {
# Whether Impeller shaders are supported on the platform.
impeller_shaders_supports_platform =
impeller_enable_metal || impeller_enable_opengles
impeller_enable_metal || impeller_enable_opengles ||
impeller_enable_vulkan
# Whether Impeller supports rendering on the platform.
impeller_supports_rendering =
impeller_enable_metal || impeller_enable_opengles
impeller_enable_metal || impeller_enable_opengles ||
impeller_enable_vulkan
}
# ------------------------------------------------------------------------------
@@ -493,6 +498,60 @@ template("impeller_shaders_gles") {
}
}
template("impeller_shaders_vk") {
assert(defined(invoker.shaders), "Impeller shaders must be specified.")
assert(defined(invoker.name), "Name of the shader library must be specified.")
shaders_base_name = string_join("",
[
invoker.name,
"_shaders_vk",
])
impellerc_vk = "impellerc_$target_name"
impellerc(impellerc_vk) {
shaders = invoker.shaders
sl_file_extension = "vkspv"
# Metal reflectors generate a superset of information.
if (impeller_enable_metal) {
intermediates_subdir = "vk"
}
shader_target_flag = "--vulkan"
defines = [ "IMPELLER_TARGET_VULKAN" ]
}
vk_lib = "genlib_$target_name"
blobcat_library(vk_lib) {
shaders =
filter_include(get_target_outputs(":$impellerc_vk"), [ "*.vkspv" ])
deps = [ ":$impellerc_vk" ]
}
reflect_vk = "reflect_$target_name"
impellerc_reflect(reflect_vk) {
impellerc_invocation = ":$impellerc_vk"
}
embed_vk_lib = "embed_$target_name"
embed_blob(embed_vk_lib) {
vk_library_files = get_target_outputs(":$vk_lib")
symbol_name = shaders_base_name
blob = vk_library_files[0]
hdr = "$target_gen_dir/vk/$shaders_base_name.h"
cc = "$target_gen_dir/vk/$shaders_base_name.c"
deps = [ ":$vk_lib" ]
}
group(target_name) {
public_deps = [ ":$embed_vk_lib" ]
if (!impeller_enable_metal) {
public_deps += [ ":$reflect_vk" ]
}
}
}
template("impeller_shaders") {
if (impeller_enable_metal) {
mtl_shaders = "mtl_$target_name"
@@ -510,6 +569,14 @@ template("impeller_shaders") {
}
}
if (impeller_enable_vulkan) {
vk_shaders = "vk_$target_name"
impeller_shaders_vk(vk_shaders) {
name = invoker.name
shaders = invoker.shaders
}
}
if (!impeller_shaders_supports_platform) {
not_needed(invoker, "*")
}
@@ -523,5 +590,9 @@ template("impeller_shaders") {
if (impeller_enable_opengles) {
public_deps += [ ":$gles_shaders" ]
}
if (impeller_enable_vulkan) {
public_deps += [ ":$vk_shaders" ]
}
}
}

View File

@@ -588,10 +588,12 @@ TEST(ImageDecoderTest, VerifySimpleDecoding) {
->dimensions(),
SkISize::Make(6, 2));
#if IMPELLER_SUPPORTS_RENDERING
ASSERT_EQ(ImageDecoderImpeller::DecompressTexture(descriptor.get(),
SkISize::Make(6, 2))
->dimensions(),
SkISize::Make(6, 2));
#endif // IMPELLER_SUPPORTS_RENDERING
}
TEST(ImageDecoderTest, VerifySubpixelDecodingPreservesExifOrientation) {