From 621719cab66d8eb31e9b59e6782898fad1a040f2 Mon Sep 17 00:00:00 2001 From: Chinmay Garde Date: Sat, 16 Apr 2022 19:14:50 -0700 Subject: [PATCH] Add impellerc options to compile OpenGL Desktop and ES variant shaders. (flutter/engine#139) Also parameterize all unit-tests so all backends are automatically tested. --- engine/src/flutter/impeller/compiler/BUILD.gn | 14 +- .../impeller/compiler/code_gen_template.h | 6 +- .../src/flutter/impeller/compiler/compiler.cc | 406 +++++------------- .../src/flutter/impeller/compiler/compiler.h | 42 +- .../impeller/compiler/compiler_backend.cc | 84 ++++ .../impeller/compiler/compiler_backend.h | 57 +++ .../impeller/compiler/compiler_test.cc | 167 +++++++ .../flutter/impeller/compiler/compiler_test.h | 34 ++ .../impeller/compiler/compiler_unittests.cc | 77 +--- .../impeller/compiler/impellerc_main.cc | 44 +- .../src/flutter/impeller/compiler/includer.cc | 117 +++++ .../src/flutter/impeller/compiler/includer.h | 59 +++ engine/src/flutter/impeller/compiler/logger.h | 5 + .../flutter/impeller/compiler/reflector.cc | 19 +- .../src/flutter/impeller/compiler/reflector.h | 6 +- .../impeller/compiler/source_options.cc | 18 + .../impeller/compiler/source_options.h | 35 ++ .../src/flutter/impeller/compiler/switches.cc | 28 +- .../src/flutter/impeller/compiler/switches.h | 4 +- engine/src/flutter/impeller/compiler/types.cc | 216 ++++++++++ engine/src/flutter/impeller/compiler/types.h | 58 +++ .../src/flutter/impeller/tools/impeller.gni | 6 +- 22 files changed, 1044 insertions(+), 458 deletions(-) create mode 100644 engine/src/flutter/impeller/compiler/compiler_backend.cc create mode 100644 engine/src/flutter/impeller/compiler/compiler_backend.h create mode 100644 engine/src/flutter/impeller/compiler/compiler_test.cc create mode 100644 engine/src/flutter/impeller/compiler/compiler_test.h create mode 100644 engine/src/flutter/impeller/compiler/includer.cc create mode 100644 engine/src/flutter/impeller/compiler/includer.h create mode 100644 engine/src/flutter/impeller/compiler/source_options.cc create mode 100644 engine/src/flutter/impeller/compiler/source_options.h create mode 100644 engine/src/flutter/impeller/compiler/types.cc create mode 100644 engine/src/flutter/impeller/compiler/types.h diff --git a/engine/src/flutter/impeller/compiler/BUILD.gn b/engine/src/flutter/impeller/compiler/BUILD.gn index 64155540c4..249944ca64 100644 --- a/engine/src/flutter/impeller/compiler/BUILD.gn +++ b/engine/src/flutter/impeller/compiler/BUILD.gn @@ -9,12 +9,20 @@ impeller_component("compiler_lib") { "code_gen_template.h", "compiler.cc", "compiler.h", + "compiler_backend.cc", + "compiler_backend.h", "include_dir.h", + "includer.cc", + "includer.h", "logger.h", "reflector.cc", "reflector.h", + "source_options.cc", + "source_options.h", "switches.cc", "switches.h", + "types.cc", + "types.h", "utilities.cc", "utilities.h", ] @@ -52,7 +60,11 @@ impeller_component("compiler_unittests") { output_name = "impellerc_unittests" - sources = [ "compiler_unittests.cc" ] + sources = [ + "compiler_test.cc", + "compiler_test.h", + "compiler_unittests.cc", + ] deps = [ ":compiler_lib", diff --git a/engine/src/flutter/impeller/compiler/code_gen_template.h b/engine/src/flutter/impeller/compiler/code_gen_template.h index 835c2b8cc4..dc699e8445 100644 --- a/engine/src/flutter/impeller/compiler/code_gen_template.h +++ b/engine/src/flutter/impeller/compiler/code_gen_template.h @@ -53,7 +53,7 @@ struct {{camel_case(shader_name)}}{{camel_case(shader_stage)}}Shader { static constexpr auto kResource{{camel_case(buffer.name)}} = ShaderUniformSlot<{{buffer.name}}> { // {{buffer.name}} "{{buffer.name}}", // name - {{buffer.msl_res_0}}u, // binding + {{buffer.ext_res_0}}u, // binding }; {% endfor %} {% endif %} @@ -91,8 +91,8 @@ struct {{camel_case(shader_name)}}{{camel_case(shader_stage)}}Shader { static constexpr auto kResource{{camel_case(sampled_image.name)}} = SampledImageSlot { // {{sampled_image.name}} "{{sampled_image.name}}", // name - {{sampled_image.msl_res_0}}u, // texture - {{sampled_image.msl_res_1}}u, // sampler + {{sampled_image.ext_res_0}}u, // texture + {{sampled_image.ext_res_1}}u, // sampler }; {% endfor %} {% endif %} diff --git a/engine/src/flutter/impeller/compiler/compiler.cc b/engine/src/flutter/impeller/compiler/compiler.cc index 8e1150d4cf..11cc3c7389 100644 --- a/engine/src/flutter/impeller/compiler/compiler.cc +++ b/engine/src/flutter/impeller/compiler/compiler.cc @@ -9,207 +9,62 @@ #include #include "flutter/fml/paths.h" +#include "impeller/compiler/compiler_backend.h" +#include "impeller/compiler/includer.h" #include "impeller/compiler/logger.h" namespace impeller { namespace compiler { -#define COMPILER_ERROR \ - ::impeller::compiler::AutoLogger(error_stream_) << GetSourcePrefix() - -#define COMPILER_ERROR_NO_PREFIX ::impeller::compiler::AutoLogger(error_stream_) - -struct IncluderData { - std::string file_name; - std::unique_ptr mapping; - - IncluderData(std::string p_file_name, std::unique_ptr p_mapping) - : file_name(std::move(p_file_name)), mapping(std::move(p_mapping)) {} -}; - -class Includer final : public shaderc::CompileOptions::IncluderInterface { - public: - Includer(std::shared_ptr working_directory, - std::vector include_dirs, - std::function on_file_included) - : working_directory_(std::move(working_directory)), - include_dirs_(std::move(include_dirs)), - on_file_included_(std::move(on_file_included)) {} - - // |shaderc::CompileOptions::IncluderInterface| - ~Includer() override = default; - - std::unique_ptr TryOpenMapping( - const IncludeDir& dir, - const char* requested_source) { - if (!dir.dir || !dir.dir->is_valid()) { - return nullptr; - } - - if (requested_source == nullptr) { - return nullptr; - } - - std::string source(requested_source); - if (source.empty()) { - return nullptr; - } - - auto mapping = fml::FileMapping::CreateReadOnly(*dir.dir, requested_source); - if (!mapping || !mapping->IsValid()) { - return nullptr; - } - - on_file_included_(fml::paths::JoinPaths({dir.name, requested_source})); - - return mapping; - } - - std::unique_ptr FindFirstMapping( - const char* requested_source) { - // Always try the working directory first no matter what the include - // directories are. - { - IncludeDir dir; - dir.name = "."; - dir.dir = working_directory_; - if (auto mapping = TryOpenMapping(dir, requested_source)) { - return mapping; - } - } - - for (const auto& include_dir : include_dirs_) { - if (auto mapping = TryOpenMapping(include_dir, requested_source)) { - return mapping; - } - } - return nullptr; - } - - // |shaderc::CompileOptions::IncluderInterface| - shaderc_include_result* GetInclude(const char* requested_source, - shaderc_include_type type, - const char* requesting_source, - size_t include_depth) override { - auto result = std::make_unique(); - - // Default initialize to failed inclusion. - result->source_name = ""; - result->source_name_length = 0; - - constexpr const char* kFileNotFoundMessage = "Included file not found."; - result->content = kFileNotFoundMessage; - result->content_length = ::strlen(kFileNotFoundMessage); - result->user_data = nullptr; - - if (!working_directory_ || !working_directory_->is_valid()) { - return result.release(); - } - - if (requested_source == nullptr) { - return result.release(); - } - - auto file = FindFirstMapping(requested_source); - - if (!file || file->GetMapping() == nullptr) { - return result.release(); - } - - auto includer_data = - std::make_unique(requested_source, std::move(file)); - - result->source_name = includer_data->file_name.c_str(); - result->source_name_length = includer_data->file_name.length(); - result->content = reinterpret_castcontent)>( - includer_data->mapping->GetMapping()); - result->content_length = includer_data->mapping->GetSize(); - result->user_data = includer_data.release(); - - return result.release(); - } - - // |shaderc::CompileOptions::IncluderInterface| - void ReleaseInclude(shaderc_include_result* data) override { - delete reinterpret_cast(data->user_data); - delete data; - } - - private: - std::shared_ptr working_directory_; - std::vector include_dirs_; - std::function on_file_included_; - - FML_DISALLOW_COPY_AND_ASSIGN(Includer); -}; - -static std::string ShaderCErrorToString(shaderc_compilation_status status) { - switch (status) { - case shaderc_compilation_status::shaderc_compilation_status_success: - return "Success"; - case shaderc_compilation_status::shaderc_compilation_status_invalid_stage: - return "Invalid Shader Stage Specified"; - case shaderc_compilation_status:: - shaderc_compilation_status_compilation_error: - return "Compilation Error"; - case shaderc_compilation_status::shaderc_compilation_status_internal_error: - return "Internal Error"; - case shaderc_compilation_status:: - shaderc_compilation_status_null_result_object: - return "Internal error. Null Result Object"; - case shaderc_compilation_status:: - shaderc_compilation_status_invalid_assembly: - return "Invalid Assembly"; - case shaderc_compilation_status:: - shaderc_compilation_status_validation_error: - return "Validation Error"; - case shaderc_compilation_status:: - shaderc_compilation_status_transformation_error: - return "Transformation Error"; - case shaderc_compilation_status:: - shaderc_compilation_status_configuration_error: - return "Configuration Error"; - } - return "Unknown Internal Error"; +static CompilerBackend CreateMSLCompiler(const spirv_cross::ParsedIR& ir, + const SourceOptions& source_options) { + auto sl_compiler = std::make_shared(ir); + spirv_cross::CompilerMSL::Options sl_options; + sl_options.platform = + TargetPlatformToMSLPlatform(source_options.target_platform); + // If this version specification changes, the GN rules that process the + // Metal to AIR must be updated as well. + sl_options.msl_version = + spirv_cross::CompilerMSL::Options::make_msl_version(1, 2); + sl_compiler->set_msl_options(sl_options); + return sl_compiler; } -static shaderc_shader_kind ToShaderCShaderKind(Compiler::SourceType type) { - switch (type) { - case Compiler::SourceType::kVertexShader: - return shaderc_shader_kind::shaderc_vertex_shader; - case Compiler::SourceType::kFragmentShader: - return shaderc_shader_kind::shaderc_fragment_shader; - case Compiler::SourceType::kUnknown: +static CompilerBackend CreateGLSLCompiler(const spirv_cross::ParsedIR& ir, + const SourceOptions& source_options) { + auto gl_compiler = std::make_shared(ir); + spirv_cross::CompilerGLSL::Options sl_options; + sl_options.force_zero_initialized_variables = true; + if (source_options.target_platform == TargetPlatform::kOpenGLES) { + sl_options.version = 100; + sl_options.es = true; + } + gl_compiler->set_common_options(sl_options); + return gl_compiler; +} + +static CompilerBackend CreateCompiler(const spirv_cross::ParsedIR& ir, + const SourceOptions& source_options) { + CompilerBackend compiler; + switch (source_options.target_platform) { + case TargetPlatform::kMetalDesktop: + case TargetPlatform::kMetalIOS: + compiler = CreateMSLCompiler(ir, source_options); + break; + case TargetPlatform::kUnknown: + case TargetPlatform::kFlutterSPIRV: + case TargetPlatform::kOpenGLES: + case TargetPlatform::kOpenGLDesktop: + compiler = CreateGLSLCompiler(ir, source_options); break; } - return shaderc_shader_kind::shaderc_glsl_infer_from_source; -} - -static spv::ExecutionModel ToExecutionModel(Compiler::SourceType type) { - switch (type) { - case Compiler::SourceType::kVertexShader: - return spv::ExecutionModel::ExecutionModelVertex; - case Compiler::SourceType::kFragmentShader: - return spv::ExecutionModel::ExecutionModelFragment; - case Compiler::SourceType::kUnknown: - break; - } - return spv::ExecutionModel::ExecutionModelMax; - ; -} - -static spirv_cross::CompilerMSL::Options::Platform -CompilerTargetPlatformToCompilerMSLTargetPlatform( - Compiler::TargetPlatform platform) { - switch (platform) { - case Compiler::TargetPlatform::kIPhoneOS: - return spirv_cross::CompilerMSL::Options::Platform::iOS; - case Compiler::TargetPlatform::kMacOS: - // Unknown should not happen due to prior validation. - case Compiler::TargetPlatform::kFlutterSPIRV: - case Compiler::TargetPlatform::kUnknown: - return spirv_cross::CompilerMSL::Options::Platform::macOS; + if (!compiler) { + return {}; } + auto* backend = compiler.GetCompiler(); + backend->rename_entry_point("main", source_options.entry_point_name, + ToExecutionModel(source_options.type)); + return compiler; } Compiler::Compiler(const fml::Mapping& source_mapping, @@ -234,43 +89,51 @@ Compiler::Compiler(const fml::Mapping& source_mapping, return; } - shaderc::CompileOptions options; + shaderc::CompileOptions spirv_options; // Make sure reflection is as effective as possible. The generated shaders // will be processed later by backend specific compilers. So optimizations // here are irrelevant and get in the way of generating reflection code. - options.SetGenerateDebugInfo(); + spirv_options.SetGenerateDebugInfo(); // Expects GLSL 4.60 (Core Profile). // https://www.khronos.org/registry/OpenGL/specs/gl/GLSLangSpec.4.60.pdf - options.SetSourceLanguage( + spirv_options.SetSourceLanguage( shaderc_source_language::shaderc_source_language_glsl); - options.SetForcedVersionProfile(460, shaderc_profile::shaderc_profile_core); - if (source_options.target_platform == TargetPlatform::kFlutterSPIRV) { - options.SetOptimizationLevel( - shaderc_optimization_level::shaderc_optimization_level_size); - options.SetTargetEnvironment( - shaderc_target_env::shaderc_target_env_opengl, - shaderc_env_version::shaderc_env_version_opengl_4_5 - ); - options.SetTargetSpirv(shaderc_spirv_version::shaderc_spirv_version_1_0); - } else { - options.SetOptimizationLevel( - shaderc_optimization_level::shaderc_optimization_level_zero); - options.SetTargetEnvironment( - shaderc_target_env::shaderc_target_env_vulkan, - shaderc_env_version::shaderc_env_version_vulkan_1_1 - ); - options.SetTargetSpirv(shaderc_spirv_version::shaderc_spirv_version_1_3); + spirv_options.SetForcedVersionProfile(460, + shaderc_profile::shaderc_profile_core); + switch (source_options.target_platform) { + case TargetPlatform::kMetalDesktop: + case TargetPlatform::kMetalIOS: + case TargetPlatform::kOpenGLES: + case TargetPlatform::kOpenGLDesktop: + spirv_options.SetOptimizationLevel( + shaderc_optimization_level::shaderc_optimization_level_zero); + spirv_options.SetTargetEnvironment( + shaderc_target_env::shaderc_target_env_vulkan, + shaderc_env_version::shaderc_env_version_vulkan_1_1); + spirv_options.SetTargetSpirv( + shaderc_spirv_version::shaderc_spirv_version_1_3); + break; + case TargetPlatform::kFlutterSPIRV: + spirv_options.SetOptimizationLevel( + shaderc_optimization_level::shaderc_optimization_level_size); + spirv_options.SetTargetEnvironment( + shaderc_target_env::shaderc_target_env_opengl, + shaderc_env_version::shaderc_env_version_opengl_4_5); + spirv_options.SetTargetSpirv( + shaderc_spirv_version::shaderc_spirv_version_1_0); + break; + case TargetPlatform::kUnknown: + COMPILER_ERROR << "Target platform invalid."; + return; } - options.SetAutoBindUniforms(true); - options.SetAutoMapLocations(true); - - options.AddMacroDefinition("IMPELLER_DEVICE"); + spirv_options.SetAutoBindUniforms(true); + spirv_options.SetAutoMapLocations(true); std::vector included_file_names; - options.SetIncluder(std::make_unique( + spirv_options.SetIncluder(std::make_unique( options_.working_directory, options_.include_dirs, [&included_file_names](auto included_name) { included_file_names.emplace_back(std::move(included_name)); @@ -291,7 +154,7 @@ Compiler::Compiler(const fml::Mapping& source_mapping, shader_kind, // shader_kind source_options.file_name.c_str(), // input_file_name source_options.entry_point_name.c_str(), // entry_point_name - options // options + spirv_options // options )); if (spv_result_->GetCompilationStatus() != shaderc_compilation_status::shaderc_compilation_status_success) { @@ -307,7 +170,7 @@ Compiler::Compiler(const fml::Mapping& source_mapping, included_file_names_ = std::move(included_file_names); } - if (!TargetPlatformNeedsMSL(source_options.target_platform)) { + if (!TargetPlatformNeedsSL(source_options.target_platform)) { is_valid_ = true; return; } @@ -322,34 +185,25 @@ Compiler::Compiler(const fml::Mapping& source_mapping, const auto parsed_ir = std::make_shared(parser.get_parsed_ir()); - const auto msl_compiler = - std::make_shared(*parsed_ir); + auto sl_compiler = CreateCompiler(*parsed_ir, options_); - { - msl_compiler->rename_entry_point("main", options_.entry_point_name, - ToExecutionModel(options_.type)); + if (!sl_compiler) { + COMPILER_ERROR << "Could not create compiler for target platform."; + return; } - { - spirv_cross::CompilerMSL::Options msl_options; - msl_options.platform = CompilerTargetPlatformToCompilerMSLTargetPlatform( - options_.target_platform); - // If this version specification changes, the GN rules that process the - // Metal to AIR must be updated as well. - msl_options.msl_version = - spirv_cross::CompilerMSL::Options::make_msl_version(1, 2); - msl_compiler->set_msl_options(msl_options); - } + sl_string_ = + std::make_shared(sl_compiler.GetCompiler()->compile()); - msl_string_ = std::make_shared(msl_compiler->compile()); - - if (!msl_string_) { + if (!sl_string_) { COMPILER_ERROR << "Could not generate MSL from SPIRV"; return; } - reflector_ = std::make_unique(std::move(reflector_options), - parsed_ir, msl_compiler); + reflector_ = std::make_unique(std::move(reflector_options), // + parsed_ir, // + sl_compiler // + ); if (!reflector_->IsValid()) { COMPILER_ERROR << "Could not complete reflection on generated shader."; @@ -374,87 +228,21 @@ std::unique_ptr Compiler::GetSPIRVAssembly() const { [result = spv_result_](auto, auto) mutable { result.reset(); }); } -std::unique_ptr Compiler::GetMSLShaderSource() const { - if (!msl_string_) { +std::unique_ptr Compiler::GetSLShaderSource() const { + if (!sl_string_) { return nullptr; } return std::make_unique( - reinterpret_cast(msl_string_->c_str()), - msl_string_->length(), - [string = msl_string_](auto, auto) mutable { string.reset(); }); + reinterpret_cast(sl_string_->c_str()), + sl_string_->length(), + [string = sl_string_](auto, auto) mutable { string.reset(); }); } bool Compiler::IsValid() const { return is_valid_; } -static bool StringEndWith(const std::string& string, - const std::string& suffix) { - if (suffix.size() > string.size()) { - return false; - } - - if (suffix.empty() || suffix.empty()) { - return false; - } - - return string.rfind(suffix) == (string.size() - suffix.size()); -} - -Compiler::SourceType Compiler::SourceTypeFromFileName( - const std::string& file_name) { - if (StringEndWith(file_name, ".vert")) { - return Compiler::SourceType::kVertexShader; - } - - if (StringEndWith(file_name, ".frag")) { - return Compiler::SourceType::kFragmentShader; - } - - return Compiler::SourceType::kUnknown; -} - -std::string Compiler::EntryPointFromSourceName(const std::string& file_name, - SourceType type) { - std::stringstream stream; - std::filesystem::path file_path(file_name); - stream << file_path.stem().native() << "_"; - switch (type) { - case SourceType::kUnknown: - stream << "unknown"; - break; - case SourceType::kVertexShader: - stream << "vertex"; - break; - case SourceType::kFragmentShader: - stream << "fragment"; - break; - } - stream << "_main"; - return stream.str(); -} - -bool Compiler::TargetPlatformNeedsMSL(TargetPlatform platform) { - switch (platform) { - case TargetPlatform::kIPhoneOS: - case TargetPlatform::kMacOS: - return true; - default: - return false; - } -} - -bool Compiler::TargetPlatformNeedsReflection(TargetPlatform platform) { - switch (platform) { - case TargetPlatform::kIPhoneOS: - case TargetPlatform::kMacOS: - return true; - default: - return false; - } -} - std::string Compiler::GetSourcePrefix() const { std::stringstream stream; stream << options_.file_name << ": "; diff --git a/engine/src/flutter/impeller/compiler/compiler.h b/engine/src/flutter/impeller/compiler/compiler.h index 6acbde58e6..635c778f28 100644 --- a/engine/src/flutter/impeller/compiler/compiler.h +++ b/engine/src/flutter/impeller/compiler/compiler.h @@ -12,6 +12,8 @@ #include "flutter/fml/mapping.h" #include "impeller/compiler/include_dir.h" #include "impeller/compiler/reflector.h" +#include "impeller/compiler/source_options.h" +#include "impeller/compiler/types.h" #include "shaderc/shaderc.hpp" #include "third_party/spirv_cross/spirv_msl.hpp" #include "third_party/spirv_cross/spirv_parser.hpp" @@ -21,42 +23,6 @@ namespace compiler { class Compiler { public: - enum class SourceType { - kUnknown, - kVertexShader, - kFragmentShader, - }; - - enum class TargetPlatform { - kUnknown, - kMacOS, - kIPhoneOS, - kFlutterSPIRV, - }; - - static SourceType SourceTypeFromFileName(const std::string& file_name); - - static std::string EntryPointFromSourceName(const std::string& file_name, - SourceType type); - - static bool TargetPlatformNeedsMSL(TargetPlatform platform); - - static bool TargetPlatformNeedsReflection(TargetPlatform platform); - - struct SourceOptions { - SourceType type = SourceType::kUnknown; - TargetPlatform target_platform = TargetPlatform::kUnknown; - std::shared_ptr working_directory; - std::vector include_dirs; - std::string file_name = "main.glsl"; - std::string entry_point_name = "main"; - - SourceOptions() = default; - - SourceOptions(const std::string& file_name) - : type(SourceTypeFromFileName(file_name)), file_name(file_name) {} - }; - Compiler(const fml::Mapping& source_mapping, SourceOptions options, Reflector::Options reflector_options); @@ -67,7 +33,7 @@ class Compiler { std::unique_ptr GetSPIRVAssembly() const; - std::unique_ptr GetMSLShaderSource() const; + std::unique_ptr GetSLShaderSource() const; std::string GetErrorMessages() const; @@ -81,7 +47,7 @@ class Compiler { private: SourceOptions options_; std::shared_ptr spv_result_; - std::shared_ptr msl_string_; + std::shared_ptr sl_string_; std::stringstream error_stream_; std::unique_ptr reflector_; std::vector included_file_names_; diff --git a/engine/src/flutter/impeller/compiler/compiler_backend.cc b/engine/src/flutter/impeller/compiler/compiler_backend.cc new file mode 100644 index 0000000000..14a6d7868e --- /dev/null +++ b/engine/src/flutter/impeller/compiler/compiler_backend.cc @@ -0,0 +1,84 @@ +// 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/compiler/compiler_backend.h" + +namespace impeller { +namespace compiler { + +CompilerBackend::CompilerBackend(MSLCompiler compiler) : compiler_(compiler) {} + +CompilerBackend::CompilerBackend(GLSLCompiler compiler) : compiler_(compiler) {} + +CompilerBackend::CompilerBackend() = default; + +CompilerBackend::CompilerBackend(Compiler compiler) + : compiler_(std::move(compiler)){}; + +CompilerBackend::~CompilerBackend() = default; + +const spirv_cross::Compiler* CompilerBackend::operator->() const { + return GetCompiler(); +} + +uint32_t CompilerBackend::GetExtendedMSLResourceBinding( + ExtendedResourceIndex index, + spirv_cross::ID id) const { + const auto kOOBIndex = static_cast(-1); + auto compiler = GetMSLCompiler(); + if (!compiler) { + return kOOBIndex; + } + switch (index) { + case ExtendedResourceIndex::kPrimary: + return compiler->get_automatic_msl_resource_binding(id); + case ExtendedResourceIndex::kSecondary: + return compiler->get_automatic_msl_resource_binding_secondary(id); + break; + } + return kOOBIndex; +} + +const spirv_cross::Compiler* CompilerBackend::GetCompiler() const { + if (auto compiler = GetGLSLCompiler()) { + return compiler; + } + + if (auto compiler = GetMSLCompiler()) { + return compiler; + } + + return nullptr; +} + +spirv_cross::Compiler* CompilerBackend::GetCompiler() { + if (auto* msl = std::get_if(&compiler_)) { + return msl->get(); + } + if (auto* glsl = std::get_if(&compiler_)) { + return glsl->get(); + } + return nullptr; +} + +const spirv_cross::CompilerMSL* CompilerBackend::GetMSLCompiler() const { + if (auto* msl = std::get_if(&compiler_)) { + return msl->get(); + } + return nullptr; +} + +const spirv_cross::CompilerGLSL* CompilerBackend::GetGLSLCompiler() const { + if (auto* glsl = std::get_if(&compiler_)) { + return glsl->get(); + } + return nullptr; +} + +CompilerBackend::operator bool() const { + return !!GetCompiler(); +} + +} // namespace compiler +} // namespace impeller diff --git a/engine/src/flutter/impeller/compiler/compiler_backend.h b/engine/src/flutter/impeller/compiler/compiler_backend.h new file mode 100644 index 0000000000..14686b748f --- /dev/null +++ b/engine/src/flutter/impeller/compiler/compiler_backend.h @@ -0,0 +1,57 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#pragma once + +#include +#include + +#include "flutter/fml/logging.h" +#include "flutter/fml/macros.h" +#include "third_party/spirv_cross/spirv_glsl.hpp" +#include "third_party/spirv_cross/spirv_msl.hpp" + +namespace impeller { +namespace compiler { + +struct CompilerBackend { + using MSLCompiler = std::shared_ptr; + using GLSLCompiler = std::shared_ptr; + using Compiler = std::variant; + + CompilerBackend(MSLCompiler compiler); + + CompilerBackend(GLSLCompiler compiler); + + CompilerBackend(Compiler compiler); + + CompilerBackend(); + + ~CompilerBackend(); + + const spirv_cross::Compiler* operator->() const; + + operator bool() const; + + enum class ExtendedResourceIndex { + kPrimary, + kSecondary, + }; + uint32_t GetExtendedMSLResourceBinding(ExtendedResourceIndex index, + spirv_cross::ID id) const; + + const spirv_cross::Compiler* GetCompiler() const; + + spirv_cross::Compiler* GetCompiler(); + + private: + Compiler compiler_; + + const spirv_cross::CompilerMSL* GetMSLCompiler() const; + + const spirv_cross::CompilerGLSL* GetGLSLCompiler() const; +}; + +} // namespace compiler +} // namespace impeller diff --git a/engine/src/flutter/impeller/compiler/compiler_test.cc b/engine/src/flutter/impeller/compiler/compiler_test.cc new file mode 100644 index 0000000000..c2ead9c7d9 --- /dev/null +++ b/engine/src/flutter/impeller/compiler/compiler_test.cc @@ -0,0 +1,167 @@ +// 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/compiler/compiler_test.h" + +#include + +namespace impeller { +namespace compiler { +namespace testing { + +static fml::UniqueFD CreateIntermediatesDirectory() { + auto test_name = flutter::testing::GetCurrentTestName(); + std::replace(test_name.begin(), test_name.end(), '/', '_'); + std::replace(test_name.begin(), test_name.end(), '.', '_'); + return fml::OpenDirectory(flutter::testing::OpenFixturesDirectory(), + test_name.c_str(), + true, // create if necessary + fml::FilePermission::kReadWrite); +} + +CompilerTest::CompilerTest() + : intermediates_directory_(CreateIntermediatesDirectory()) { + FML_CHECK(intermediates_directory_.is_valid()); +} + +CompilerTest::~CompilerTest() = default; + +static std::string ReflectionHeaderName(const char* fixture_name) { + std::stringstream stream; + stream << fixture_name << ".h"; + return stream.str(); +} + +static std::string ReflectionCCName(const char* fixture_name) { + std::stringstream stream; + stream << fixture_name << ".cc"; + return stream.str(); +} + +static std::string ReflectionJSONName(const char* fixture_name) { + std::stringstream stream; + stream << fixture_name << ".json"; + return stream.str(); +} + +static std::string SPIRVFileName(const char* fixture_name) { + std::stringstream stream; + stream << fixture_name << ".spv"; + return stream.str(); +} + +static std::string SLFileName(const char* fixture_name, + TargetPlatform platform) { + std::stringstream stream; + stream << fixture_name << "." << TargetPlatformSLExtension(platform); + return stream.str(); +} + +bool CompilerTest::CanCompileAndReflect(const char* fixture_name) const { + auto fixture = flutter::testing::OpenFixtureAsMapping(fixture_name); + if (!fixture->GetMapping()) { + VALIDATION_LOG << "Could not find shader in fixtures: " << fixture_name; + return false; + } + + SourceOptions source_options(fixture_name); + source_options.target_platform = GetParam(); + source_options.working_directory = std::make_shared( + flutter::testing::OpenFixturesDirectory()); + source_options.entry_point_name = EntryPointFunctionNameFromSourceName( + fixture_name, SourceTypeFromFileName(fixture_name), GetParam()); + + Reflector::Options reflector_options; + reflector_options.header_file_name = ReflectionHeaderName(fixture_name); + reflector_options.shader_name = "shader_name"; + + Compiler compiler(*fixture.get(), source_options, reflector_options); + if (!compiler.IsValid()) { + VALIDATION_LOG << "Compilation failed: " << compiler.GetErrorMessages(); + return false; + } + + auto spirv_assembly = compiler.GetSPIRVAssembly(); + if (!spirv_assembly) { + VALIDATION_LOG << "No spirv was generated."; + return false; + } + + if (!fml::WriteAtomically(intermediates_directory_, + SPIRVFileName(fixture_name).c_str(), + *spirv_assembly)) { + VALIDATION_LOG << "Could not write SPIRV intermediates."; + return false; + } + + if (TargetPlatformNeedsSL(GetParam())) { + auto sl_source = compiler.GetSLShaderSource(); + if (!sl_source) { + VALIDATION_LOG << "No SL source was generated."; + return false; + } + + if (!fml::WriteAtomically(intermediates_directory_, + SLFileName(fixture_name, GetParam()).c_str(), + *sl_source)) { + VALIDATION_LOG << "Could not write SL intermediates."; + return false; + } + } + + if (TargetPlatformNeedsReflection(GetParam())) { + auto reflector = compiler.GetReflector(); + if (!reflector) { + VALIDATION_LOG + << "No reflector was found for target platform SL compiler."; + return false; + } + + auto reflection_json = reflector->GetReflectionJSON(); + auto reflection_header = reflector->GetReflectionHeader(); + auto reflection_source = reflector->GetReflectionCC(); + + if (!reflection_json) { + VALIDATION_LOG << "Reflection JSON was not found."; + return false; + } + + if (!reflection_header) { + VALIDATION_LOG << "Reflection header was not found."; + return false; + } + + if (!reflection_source) { + VALIDATION_LOG << "Reflection source was not found."; + return false; + } + + if (!fml::WriteAtomically(intermediates_directory_, + ReflectionHeaderName(fixture_name).c_str(), + *reflection_header)) { + VALIDATION_LOG << "Could not write reflection header intermediates."; + return false; + } + + if (!fml::WriteAtomically(intermediates_directory_, + ReflectionCCName(fixture_name).c_str(), + *reflection_header)) { + VALIDATION_LOG << "Could not write reflection CC intermediates."; + return false; + } + + if (!fml::WriteAtomically(intermediates_directory_, + ReflectionJSONName(fixture_name).c_str(), + *reflection_header)) { + VALIDATION_LOG << "Could not write reflection json intermediates."; + return false; + } + } + + return true; +} + +} // namespace testing +} // namespace compiler +} // namespace impeller diff --git a/engine/src/flutter/impeller/compiler/compiler_test.h b/engine/src/flutter/impeller/compiler/compiler_test.h new file mode 100644 index 0000000000..f3141c2135 --- /dev/null +++ b/engine/src/flutter/impeller/compiler/compiler_test.h @@ -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 "flutter/fml/macros.h" +#include "flutter/testing/testing.h" +#include "impeller/base/validation.h" +#include "impeller/compiler/compiler.h" +#include "impeller/compiler/source_options.h" +#include "impeller/compiler/types.h" + +namespace impeller { +namespace compiler { +namespace testing { + +class CompilerTest : public ::testing::TestWithParam { + public: + CompilerTest(); + + ~CompilerTest(); + + bool CanCompileAndReflect(const char* fixture_name) const; + + private: + fml::UniqueFD intermediates_directory_; + + FML_DISALLOW_COPY_AND_ASSIGN(CompilerTest); +}; + +} // namespace testing +} // namespace compiler +} // namespace impeller diff --git a/engine/src/flutter/impeller/compiler/compiler_unittests.cc b/engine/src/flutter/impeller/compiler/compiler_unittests.cc index 3ca5da7ca8..6d598fa431 100644 --- a/engine/src/flutter/impeller/compiler/compiler_unittests.cc +++ b/engine/src/flutter/impeller/compiler/compiler_unittests.cc @@ -3,72 +3,39 @@ // found in the LICENSE file. #include "flutter/testing/testing.h" -#include "gtest/gtest.h" #include "impeller/base/validation.h" #include "impeller/compiler/compiler.h" +#include "impeller/compiler/compiler_test.h" +#include "impeller/compiler/source_options.h" +#include "impeller/compiler/types.h" namespace impeller { namespace compiler { namespace testing { -class CompilerTest : public ::testing::Test { - public: - CompilerTest() - : intermediates_directory_( - fml::OpenDirectory(flutter::testing::GetFixturesPath(), - false, - fml::FilePermission::kRead)) { - FML_CHECK(intermediates_directory_.is_valid()); - } - - ~CompilerTest() = default; - - bool CanCompileFixture(const char* fixture_name, - Compiler::TargetPlatform target_platform) const { - auto fixture = flutter::testing::OpenFixtureAsMapping(fixture_name); - if (!fixture->GetMapping()) { - VALIDATION_LOG << "Could not find shader in fixtures: " << fixture_name; - return false; - } - Compiler::SourceOptions compiler_options(fixture_name); - compiler_options.target_platform = target_platform; - compiler_options.working_directory = std::make_shared( - flutter::testing::OpenFixturesDirectory()); - Reflector::Options reflector_options; - Compiler compiler(*fixture.get(), compiler_options, reflector_options); - if (!compiler.IsValid()) { - VALIDATION_LOG << "Compilation failed: " << compiler.GetErrorMessages(); - return false; - } - return true; - } - - private: - fml::UniqueFD intermediates_directory_; - - FML_DISALLOW_COPY_AND_ASSIGN(CompilerTest); -}; - -TEST_F(CompilerTest, ShaderKindMatchingIsSuccessful) { - ASSERT_EQ(Compiler::SourceTypeFromFileName("hello.vert"), - Compiler::SourceType::kVertexShader); - ASSERT_EQ(Compiler::SourceTypeFromFileName("hello.frag"), - Compiler::SourceType::kFragmentShader); - ASSERT_EQ(Compiler::SourceTypeFromFileName("hello.msl"), - Compiler::SourceType::kUnknown); - ASSERT_EQ(Compiler::SourceTypeFromFileName("hello.glsl"), - Compiler::SourceType::kUnknown); +TEST(CompilerTest, ShaderKindMatchingIsSuccessful) { + ASSERT_EQ(SourceTypeFromFileName("hello.vert"), SourceType::kVertexShader); + ASSERT_EQ(SourceTypeFromFileName("hello.frag"), SourceType::kFragmentShader); + ASSERT_EQ(SourceTypeFromFileName("hello.msl"), SourceType::kUnknown); + ASSERT_EQ(SourceTypeFromFileName("hello.glsl"), SourceType::kUnknown); } -TEST_F(CompilerTest, CanCompileSample) { - ASSERT_TRUE(CanCompileFixture( - "sample.vert", Compiler::TargetPlatform::kMacOS)); +TEST_P(CompilerTest, CanCompile) { + ASSERT_TRUE(CanCompileAndReflect("sample.vert")); } -TEST_F(CompilerTest, CanTargetFlutterSPIRV) { - ASSERT_TRUE(CanCompileFixture( - "test_texture.frag", Compiler::TargetPlatform::kFlutterSPIRV)); -} +#define INSTANTIATE_TARGET_PLATFORM_TEST_SUITE_P(suite_name) \ + INSTANTIATE_TEST_SUITE_P( \ + suite_name, CompilerTest, \ + ::testing::Values( \ + TargetPlatform::kOpenGLES, TargetPlatform::kOpenGLDesktop, \ + TargetPlatform::kMetalDesktop, TargetPlatform::kMetalIOS, \ + TargetPlatform::kFlutterSPIRV), \ + [](const ::testing::TestParamInfo& info) { \ + return TargetPlatformToString(info.param); \ + }); + +INSTANTIATE_TARGET_PLATFORM_TEST_SUITE_P(CompilerSuite); } // namespace testing } // namespace compiler diff --git a/engine/src/flutter/impeller/compiler/impellerc_main.cc b/engine/src/flutter/impeller/compiler/impellerc_main.cc index bb25d8daa5..f61b112604 100644 --- a/engine/src/flutter/impeller/compiler/impellerc_main.cc +++ b/engine/src/flutter/impeller/compiler/impellerc_main.cc @@ -9,6 +9,7 @@ #include "flutter/fml/macros.h" #include "flutter/fml/mapping.h" #include "impeller/compiler/compiler.h" +#include "impeller/compiler/source_options.h" #include "impeller/compiler/switches.h" #include "impeller/compiler/utilities.h" #include "third_party/shaderc/libshaderc/include/shaderc/shaderc.hpp" @@ -36,15 +37,16 @@ bool Main(const fml::CommandLine& command_line) { return false; } - Compiler::SourceOptions options; + SourceOptions options; options.target_platform = switches.target_platform; - options.type = Compiler::SourceTypeFromFileName(switches.source_file_name); + options.type = SourceTypeFromFileName(switches.source_file_name); options.working_directory = switches.working_directory; options.file_name = switches.source_file_name; options.include_dirs = switches.include_directories; - options.entry_point_name = Compiler::EntryPointFromSourceName( + options.entry_point_name = EntryPointFunctionNameFromSourceName( switches.source_file_name, - Compiler::SourceTypeFromFileName(switches.source_file_name)); + SourceTypeFromFileName(switches.source_file_name), + switches.target_platform); Reflector::Options reflector_options; reflector_options.shader_name = @@ -69,22 +71,22 @@ bool Main(const fml::CommandLine& command_line) { return false; } - if (Compiler::TargetPlatformNeedsMSL(options.target_platform)) { + if (TargetPlatformNeedsSL(options.target_platform)) { if (!fml::WriteAtomically(*switches.working_directory, - switches.metal_file_name.c_str(), - *compiler.GetMSLShaderSource())) { + switches.sl_file_name.c_str(), + *compiler.GetSLShaderSource())) { std::cerr << "Could not write file to " << switches.spirv_file_name << std::endl; return false; } } - - if (Compiler::TargetPlatformNeedsReflection(options.target_platform)) { + if (TargetPlatformNeedsReflection(options.target_platform)) { if (!switches.reflection_json_name.empty()) { - if (!fml::WriteAtomically(*switches.working_directory, - switches.reflection_json_name.c_str(), - *compiler.GetReflector()->GetReflectionJSON())) { + if (!fml::WriteAtomically( + *switches.working_directory, + switches.reflection_json_name.c_str(), + *compiler.GetReflector()->GetReflectionJSON())) { std::cerr << "Could not write reflection json to " << switches.reflection_json_name << std::endl; return false; @@ -116,18 +118,20 @@ bool Main(const fml::CommandLine& command_line) { if (!switches.depfile_path.empty()) { std::string result_file; switch (switches.target_platform) { - case Compiler::TargetPlatform::kMacOS: - case Compiler::TargetPlatform::kIPhoneOS: - result_file = switches.metal_file_name; + case TargetPlatform::kMetalDesktop: + case TargetPlatform::kMetalIOS: + case TargetPlatform::kOpenGLES: + case TargetPlatform::kOpenGLDesktop: + result_file = switches.sl_file_name; break; - case Compiler::TargetPlatform::kFlutterSPIRV: - case Compiler::TargetPlatform::kUnknown: + case TargetPlatform::kFlutterSPIRV: + case TargetPlatform::kUnknown: result_file = switches.spirv_file_name; break; } - if (!fml::WriteAtomically( - *switches.working_directory, switches.depfile_path.c_str(), - *compiler.CreateDepfileContents({result_file}))) { + if (!fml::WriteAtomically(*switches.working_directory, + switches.depfile_path.c_str(), + *compiler.CreateDepfileContents({result_file}))) { std::cerr << "Could not write depfile to " << switches.depfile_path << std::endl; return false; diff --git a/engine/src/flutter/impeller/compiler/includer.cc b/engine/src/flutter/impeller/compiler/includer.cc new file mode 100644 index 0000000000..3be266f33a --- /dev/null +++ b/engine/src/flutter/impeller/compiler/includer.cc @@ -0,0 +1,117 @@ +// 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/compiler/includer.h" + +#include "flutter/fml/paths.h" + +namespace impeller { +namespace compiler { + +Includer::Includer(std::shared_ptr working_directory, + std::vector include_dirs, + std::function on_file_included) + : working_directory_(std::move(working_directory)), + include_dirs_(std::move(include_dirs)), + on_file_included_(std::move(on_file_included)) {} + +// |shaderc::CompileOptions::IncluderInterface| +Includer::~Includer() = default; + +std::unique_ptr Includer::TryOpenMapping( + const IncludeDir& dir, + const char* requested_source) { + if (!dir.dir || !dir.dir->is_valid()) { + return nullptr; + } + + if (requested_source == nullptr) { + return nullptr; + } + + std::string source(requested_source); + if (source.empty()) { + return nullptr; + } + + auto mapping = fml::FileMapping::CreateReadOnly(*dir.dir, requested_source); + if (!mapping || !mapping->IsValid()) { + return nullptr; + } + + on_file_included_(fml::paths::JoinPaths({dir.name, requested_source})); + + return mapping; +} + +std::unique_ptr Includer::FindFirstMapping( + const char* requested_source) { + // Always try the working directory first no matter what the include + // directories are. + { + IncludeDir dir; + dir.name = "."; + dir.dir = working_directory_; + if (auto mapping = TryOpenMapping(dir, requested_source)) { + return mapping; + } + } + + for (const auto& include_dir : include_dirs_) { + if (auto mapping = TryOpenMapping(include_dir, requested_source)) { + return mapping; + } + } + return nullptr; +} + +shaderc_include_result* Includer::GetInclude(const char* requested_source, + shaderc_include_type type, + const char* requesting_source, + size_t include_depth) { + auto result = std::make_unique(); + + // Default initialize to failed inclusion. + result->source_name = ""; + result->source_name_length = 0; + + constexpr const char* kFileNotFoundMessage = "Included file not found."; + result->content = kFileNotFoundMessage; + result->content_length = ::strlen(kFileNotFoundMessage); + result->user_data = nullptr; + + if (!working_directory_ || !working_directory_->is_valid()) { + return result.release(); + } + + if (requested_source == nullptr) { + return result.release(); + } + + auto file = FindFirstMapping(requested_source); + + if (!file || file->GetMapping() == nullptr) { + return result.release(); + } + + auto includer_data = + std::make_unique(requested_source, std::move(file)); + + result->source_name = includer_data->file_name.c_str(); + result->source_name_length = includer_data->file_name.length(); + result->content = reinterpret_castcontent)>( + includer_data->mapping->GetMapping()); + result->content_length = includer_data->mapping->GetSize(); + result->user_data = includer_data.release(); + + return result.release(); +} + +void Includer::ReleaseInclude(shaderc_include_result* data) { + delete reinterpret_cast(data->user_data); + delete data; +} + +} // namespace compiler +} // namespace impeller diff --git a/engine/src/flutter/impeller/compiler/includer.h b/engine/src/flutter/impeller/compiler/includer.h new file mode 100644 index 0000000000..0c373a6b3d --- /dev/null +++ b/engine/src/flutter/impeller/compiler/includer.h @@ -0,0 +1,59 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#pragma once + +#include + +#include "flutter/fml/macros.h" +#include "flutter/fml/mapping.h" +#include "impeller/compiler/include_dir.h" +#include "shaderc/shaderc.hpp" + +namespace impeller { +namespace compiler { + +struct IncluderData { + std::string file_name; + std::unique_ptr mapping; + + IncluderData(std::string p_file_name, std::unique_ptr p_mapping) + : file_name(std::move(p_file_name)), mapping(std::move(p_mapping)) {} +}; + +class Includer final : public shaderc::CompileOptions::IncluderInterface { + public: + Includer(std::shared_ptr working_directory, + std::vector include_dirs, + std::function on_file_included); + + // |shaderc::CompileOptions::IncluderInterface| + ~Includer() override; + + // |shaderc::CompileOptions::IncluderInterface| + shaderc_include_result* GetInclude(const char* requested_source, + shaderc_include_type type, + const char* requesting_source, + size_t include_depth) override; + + // |shaderc::CompileOptions::IncluderInterface| + void ReleaseInclude(shaderc_include_result* data) override; + + private: + std::shared_ptr working_directory_; + std::vector include_dirs_; + std::function on_file_included_; + + std::unique_ptr TryOpenMapping( + const IncludeDir& dir, + const char* requested_source); + + std::unique_ptr FindFirstMapping( + const char* requested_source); + + FML_DISALLOW_COPY_AND_ASSIGN(Includer); +}; + +} // namespace compiler +} // namespace impeller diff --git a/engine/src/flutter/impeller/compiler/logger.h b/engine/src/flutter/impeller/compiler/logger.h index b4938a5f46..fb07dd079b 100644 --- a/engine/src/flutter/impeller/compiler/logger.h +++ b/engine/src/flutter/impeller/compiler/logger.h @@ -34,5 +34,10 @@ class AutoLogger { FML_DISALLOW_COPY_AND_ASSIGN(AutoLogger); }; +#define COMPILER_ERROR \ + ::impeller::compiler::AutoLogger(error_stream_) << GetSourcePrefix() + +#define COMPILER_ERROR_NO_PREFIX ::impeller::compiler::AutoLogger(error_stream_) + } // namespace compiler } // namespace impeller diff --git a/engine/src/flutter/impeller/compiler/reflector.cc b/engine/src/flutter/impeller/compiler/reflector.cc index d7786dcc7d..c3896aea55 100644 --- a/engine/src/flutter/impeller/compiler/reflector.cc +++ b/engine/src/flutter/impeller/compiler/reflector.cc @@ -90,7 +90,7 @@ static std::string StringToShaderStage(std::string str) { Reflector::Reflector(Options options, std::shared_ptr ir, - std::shared_ptr compiler) + CompilerBackend compiler) : options_(std::move(options)), ir_(std::move(ir)), compiler_(std::move(compiler)) { @@ -305,14 +305,10 @@ std::optional Reflector::ReflectResource( resource.id, spv::Decoration::DecorationLocation); result["index"] = compiler_->get_decoration(resource.id, spv::Decoration::DecorationIndex); - result["msl_res_0"] = - compiler_->get_automatic_msl_resource_binding(resource.id); - result["msl_res_1"] = - compiler_->get_automatic_msl_resource_binding_secondary(resource.id); - result["msl_res_2"] = - compiler_->get_automatic_msl_resource_binding_tertiary(resource.id); - result["msl_res_3"] = - compiler_->get_automatic_msl_resource_binding_quaternary(resource.id); + result["ext_res_0"] = compiler_.GetExtendedMSLResourceBinding( + CompilerBackend::ExtendedResourceIndex::kPrimary, resource.id); + result["ext_res_1"] = compiler_.GetExtendedMSLResourceBinding( + CompilerBackend::ExtendedResourceIndex::kSecondary, resource.id); auto type = ReflectType(resource.type_id); if (!type.has_value()) { return std::nullopt; @@ -607,7 +603,7 @@ struct VertexType { }; static VertexType VertexTypeFromInputResource( - const spirv_cross::CompilerMSL& compiler, + const spirv_cross::Compiler& compiler, const spirv_cross::Resource* resource) { VertexType result; result.variable_name = resource->name; @@ -692,7 +688,8 @@ Reflector::ReflectPerVertexStructDefinition( if (resource == nullptr) { return std::nullopt; } - const auto vertex_type = VertexTypeFromInputResource(*compiler_, resource); + const auto vertex_type = + VertexTypeFromInputResource(*compiler_.GetCompiler(), resource); StructMember member; member.name = vertex_type.variable_name; diff --git a/engine/src/flutter/impeller/compiler/reflector.h b/engine/src/flutter/impeller/compiler/reflector.h index 302b26456c..cacaa7c4ea 100644 --- a/engine/src/flutter/impeller/compiler/reflector.h +++ b/engine/src/flutter/impeller/compiler/reflector.h @@ -9,6 +9,7 @@ #include "flutter/fml/macros.h" #include "flutter/fml/mapping.h" +#include "impeller/compiler/compiler_backend.h" #include "inja/inja.hpp" #include "third_party/spirv_cross/spirv_msl.hpp" #include "third_party/spirv_cross/spirv_parser.hpp" @@ -32,7 +33,7 @@ class Reflector { Reflector(Options options, std::shared_ptr ir, - std::shared_ptr compiler); + CompilerBackend compiler); ~Reflector(); @@ -65,8 +66,7 @@ class Reflector { const Options options_; const std::shared_ptr ir_; - // TODO(csg): There is no reason this needs to the MSL subtype. - const std::shared_ptr compiler_; + const CompilerBackend compiler_; std::unique_ptr template_arguments_; std::shared_ptr reflection_header_; std::shared_ptr reflection_cc_; diff --git a/engine/src/flutter/impeller/compiler/source_options.cc b/engine/src/flutter/impeller/compiler/source_options.cc new file mode 100644 index 0000000000..eeb1bcf8b7 --- /dev/null +++ b/engine/src/flutter/impeller/compiler/source_options.cc @@ -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/compiler/source_options.h" + +namespace impeller { +namespace compiler { + +SourceOptions::SourceOptions() = default; + +SourceOptions::SourceOptions(const std::string& file_name) + : type(SourceTypeFromFileName(file_name)), file_name(file_name) {} + +SourceOptions::~SourceOptions() = default; + +} // namespace compiler +} // namespace impeller diff --git a/engine/src/flutter/impeller/compiler/source_options.h b/engine/src/flutter/impeller/compiler/source_options.h new file mode 100644 index 0000000000..e5a3dc54a9 --- /dev/null +++ b/engine/src/flutter/impeller/compiler/source_options.h @@ -0,0 +1,35 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#pragma once + +#include +#include +#include + +#include "flutter/fml/macros.h" +#include "flutter/fml/unique_fd.h" +#include "impeller/compiler/include_dir.h" +#include "impeller/compiler/types.h" + +namespace impeller { +namespace compiler { + +struct SourceOptions { + SourceType type = SourceType::kUnknown; + TargetPlatform target_platform = TargetPlatform::kUnknown; + std::shared_ptr working_directory; + std::vector include_dirs; + std::string file_name = "main.glsl"; + std::string entry_point_name = "main"; + + SourceOptions(); + + ~SourceOptions(); + + SourceOptions(const std::string& file_name); +}; + +} // namespace compiler +} // namespace impeller diff --git a/engine/src/flutter/impeller/compiler/switches.cc b/engine/src/flutter/impeller/compiler/switches.cc index ef55ae0752..f3caea51d2 100644 --- a/engine/src/flutter/impeller/compiler/switches.cc +++ b/engine/src/flutter/impeller/compiler/switches.cc @@ -12,10 +12,12 @@ namespace impeller { namespace compiler { -static const std::map kKnownPlatforms = { - {"macos", Compiler::TargetPlatform::kMacOS}, - {"ios", Compiler::TargetPlatform::kIPhoneOS}, - {"flutter-spirv", Compiler::TargetPlatform::kFlutterSPIRV}, +static const std::map kKnownPlatforms = { + {"metal-desktop", TargetPlatform::kMetalDesktop}, + {"metal-ios", TargetPlatform::kMetalIOS}, + {"opengl-es", TargetPlatform::kOpenGLES}, + {"opengl-desktop", TargetPlatform::kOpenGLDesktop}, + {"flutter-spirv", TargetPlatform::kFlutterSPIRV}, }; void Switches::PrintHelp(std::ostream& stream) { @@ -26,7 +28,7 @@ void Switches::PrintHelp(std::ostream& stream) { } stream << " ]" << std::endl; stream << "--input=" << std::endl; - stream << "--metal=" << std::endl; + stream << "--sl=" << std::endl; stream << "--spirv=" << std::endl; stream << "[optional] --reflection-json=" << std::endl; stream << "[optional] --reflection-header=" @@ -40,16 +42,16 @@ Switches::Switches() = default; Switches::~Switches() = default; -static Compiler::TargetPlatform TargetPlatformFromCommandLine( +static TargetPlatform TargetPlatformFromCommandLine( const fml::CommandLine& command_line) { - auto target = Compiler::TargetPlatform::kUnknown; + auto target = TargetPlatform::kUnknown; for (const auto& platform : kKnownPlatforms) { if (command_line.HasOption(platform.first)) { // If the platform has already been determined, the caller may have // specified multiple platforms. This is an error and only one must be // selected. - if (target != Compiler::TargetPlatform::kUnknown) { - return Compiler::TargetPlatform::kUnknown; + if (target != TargetPlatform::kUnknown) { + return TargetPlatform::kUnknown; } target = platform.second; // Keep going to detect duplicates. @@ -65,7 +67,7 @@ Switches::Switches(const fml::CommandLine& command_line) false, // create if necessary, fml::FilePermission::kRead))), source_file_name(command_line.GetOptionValueWithDefault("input", "")), - metal_file_name(command_line.GetOptionValueWithDefault("metal", "")), + sl_file_name(command_line.GetOptionValueWithDefault("sl", "")), spirv_file_name(command_line.GetOptionValueWithDefault("spirv", "")), reflection_json_name( command_line.GetOptionValueWithDefault("reflection-json", "")), @@ -98,7 +100,7 @@ Switches::Switches(const fml::CommandLine& command_line) bool Switches::AreValid(std::ostream& explain) const { bool valid = true; - if (target_platform == Compiler::TargetPlatform::kUnknown) { + if (target_platform == TargetPlatform::kUnknown) { explain << "The target platform (only one) was not specified." << std::endl; valid = false; } @@ -113,8 +115,8 @@ bool Switches::AreValid(std::ostream& explain) const { valid = false; } - if (metal_file_name.empty() && Compiler::TargetPlatformNeedsMSL(target_platform)) { - explain << "Metal file name was empty." << std::endl; + if (sl_file_name.empty() && TargetPlatformNeedsSL(target_platform)) { + explain << "Target shading language file name was empty." << std::endl; valid = false; } diff --git a/engine/src/flutter/impeller/compiler/switches.h b/engine/src/flutter/impeller/compiler/switches.h index 3b7fac89d2..173ac20838 100644 --- a/engine/src/flutter/impeller/compiler/switches.h +++ b/engine/src/flutter/impeller/compiler/switches.h @@ -17,11 +17,11 @@ namespace impeller { namespace compiler { struct Switches { - Compiler::TargetPlatform target_platform = Compiler::TargetPlatform::kUnknown; + TargetPlatform target_platform = TargetPlatform::kUnknown; std::shared_ptr working_directory; std::vector include_directories; std::string source_file_name; - std::string metal_file_name; + std::string sl_file_name; std::string spirv_file_name; std::string reflection_json_name; std::string reflection_header_name; diff --git a/engine/src/flutter/impeller/compiler/types.cc b/engine/src/flutter/impeller/compiler/types.cc new file mode 100644 index 0000000000..adbf277dfa --- /dev/null +++ b/engine/src/flutter/impeller/compiler/types.cc @@ -0,0 +1,216 @@ +// 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/compiler/types.h" + +#include +#include + +#include "flutter/fml/logging.h" + +namespace impeller { +namespace compiler { + +static bool StringEndWith(const std::string& string, + const std::string& suffix) { + if (suffix.size() > string.size()) { + return false; + } + + if (suffix.empty() || suffix.empty()) { + return false; + } + + return string.rfind(suffix) == (string.size() - suffix.size()); +} + +SourceType SourceTypeFromFileName(const std::string& file_name) { + if (StringEndWith(file_name, ".vert")) { + return SourceType::kVertexShader; + } + + if (StringEndWith(file_name, ".frag")) { + return SourceType::kFragmentShader; + } + + return SourceType::kUnknown; +} + +std::string TargetPlatformToString(TargetPlatform platform) { + switch (platform) { + case TargetPlatform::kUnknown: + return "Unknown"; + case TargetPlatform::kMetalDesktop: + return "MetalDesktop"; + case TargetPlatform::kMetalIOS: + return "MetaliOS"; + case TargetPlatform::kFlutterSPIRV: + return "FlutterSPIRV"; + case TargetPlatform::kOpenGLES: + return "OpenGLES"; + case TargetPlatform::kOpenGLDesktop: + return "OpenGLDesktop"; + } + FML_UNREACHABLE(); +} + +static std::string UniqueEntryPointFunctionNameFromSourceName( + const std::string& file_name, + SourceType type) { + std::stringstream stream; + std::filesystem::path file_path(file_name); + stream << file_path.stem().native() << "_"; + switch (type) { + case SourceType::kUnknown: + stream << "unknown"; + break; + case SourceType::kVertexShader: + stream << "vertex"; + break; + case SourceType::kFragmentShader: + stream << "fragment"; + break; + } + stream << "_main"; + return stream.str(); +} + +std::string EntryPointFunctionNameFromSourceName(const std::string& file_name, + SourceType type, + TargetPlatform platform) { + switch (platform) { + case TargetPlatform::kMetalDesktop: + case TargetPlatform::kMetalIOS: + return UniqueEntryPointFunctionNameFromSourceName(file_name, type); + case TargetPlatform::kUnknown: + case TargetPlatform::kFlutterSPIRV: + case TargetPlatform::kOpenGLES: + case TargetPlatform::kOpenGLDesktop: + return "main"; + } + FML_UNREACHABLE(); +} + +bool TargetPlatformNeedsSL(TargetPlatform platform) { + switch (platform) { + case TargetPlatform::kMetalIOS: + case TargetPlatform::kMetalDesktop: + case TargetPlatform::kOpenGLES: + case TargetPlatform::kOpenGLDesktop: + return true; + case TargetPlatform::kUnknown: + case TargetPlatform::kFlutterSPIRV: + return false; + } + FML_UNREACHABLE(); +} + +bool TargetPlatformNeedsReflection(TargetPlatform platform) { + switch (platform) { + case TargetPlatform::kMetalIOS: + case TargetPlatform::kMetalDesktop: + case TargetPlatform::kOpenGLES: + case TargetPlatform::kOpenGLDesktop: + return true; + case TargetPlatform::kUnknown: + case TargetPlatform::kFlutterSPIRV: + return false; + } + FML_UNREACHABLE(); +} + +std::string ShaderCErrorToString(shaderc_compilation_status status) { + using Status = shaderc_compilation_status; + switch (status) { + case Status::shaderc_compilation_status_success: + return "Success"; + case Status::shaderc_compilation_status_invalid_stage: + return "Invalid shader stage specified"; + case Status::shaderc_compilation_status_compilation_error: + return "Compilation error"; + case Status::shaderc_compilation_status_internal_error: + return "Internal error"; + case Status::shaderc_compilation_status_null_result_object: + return "Internal error. Null result object"; + case Status::shaderc_compilation_status_invalid_assembly: + return "Invalid assembly"; + case Status::shaderc_compilation_status_validation_error: + return "Validation error"; + case Status::shaderc_compilation_status_transformation_error: + return "Transformation error"; + case Status::shaderc_compilation_status_configuration_error: + return "Configuration error"; + } + return "Unknown internal error"; +} + +shaderc_shader_kind ToShaderCShaderKind(SourceType type) { + switch (type) { + case SourceType::kVertexShader: + return shaderc_shader_kind::shaderc_vertex_shader; + case SourceType::kFragmentShader: + return shaderc_shader_kind::shaderc_fragment_shader; + case SourceType::kUnknown: + break; + } + return shaderc_shader_kind::shaderc_glsl_infer_from_source; +} + +spv::ExecutionModel ToExecutionModel(SourceType type) { + switch (type) { + case SourceType::kVertexShader: + return spv::ExecutionModel::ExecutionModelVertex; + case SourceType::kFragmentShader: + return spv::ExecutionModel::ExecutionModelFragment; + case SourceType::kUnknown: + break; + } + return spv::ExecutionModel::ExecutionModelMax; +} + +spirv_cross::CompilerMSL::Options::Platform TargetPlatformToMSLPlatform( + TargetPlatform platform) { + switch (platform) { + case TargetPlatform::kMetalIOS: + return spirv_cross::CompilerMSL::Options::Platform::iOS; + case TargetPlatform::kMetalDesktop: + return spirv_cross::CompilerMSL::Options::Platform::macOS; + case TargetPlatform::kFlutterSPIRV: + case TargetPlatform::kOpenGLES: + case TargetPlatform::kOpenGLDesktop: + case TargetPlatform::kUnknown: + return spirv_cross::CompilerMSL::Options::Platform::macOS; + } + FML_UNREACHABLE(); +} + +std::string SourceTypeToString(SourceType type) { + switch (type) { + case SourceType::kUnknown: + return "unknown"; + case SourceType::kVertexShader: + return "vert"; + case SourceType::kFragmentShader: + return "frag"; + } + FML_UNREACHABLE(); +} + +std::string TargetPlatformSLExtension(TargetPlatform platform) { + switch (platform) { + case TargetPlatform::kUnknown: + return "unknown"; + case TargetPlatform::kMetalDesktop: + case TargetPlatform::kMetalIOS: + return "metal"; + case TargetPlatform::kFlutterSPIRV: + case TargetPlatform::kOpenGLES: + case TargetPlatform::kOpenGLDesktop: + return "glsl"; + } + FML_UNREACHABLE(); +} + +} // namespace compiler +} // namespace impeller diff --git a/engine/src/flutter/impeller/compiler/types.h b/engine/src/flutter/impeller/compiler/types.h new file mode 100644 index 0000000000..b760122b38 --- /dev/null +++ b/engine/src/flutter/impeller/compiler/types.h @@ -0,0 +1,58 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#pragma once + +#include + +#include "flutter/fml/macros.h" +#include "shaderc/shaderc.hpp" +#include "third_party/spirv_cross/spirv_cross.hpp" +#include "third_party/spirv_cross/spirv_msl.hpp" + +namespace impeller { +namespace compiler { + +enum class SourceType { + kUnknown, + kVertexShader, + kFragmentShader, +}; + +enum class TargetPlatform { + kUnknown, + kMetalDesktop, + kMetalIOS, + kFlutterSPIRV, + kOpenGLES, + kOpenGLDesktop, +}; + +SourceType SourceTypeFromFileName(const std::string& file_name); + +std::string SourceTypeToString(SourceType type); + +std::string TargetPlatformToString(TargetPlatform platform); + +std::string TargetPlatformSLExtension(TargetPlatform platform); + +std::string EntryPointFunctionNameFromSourceName(const std::string& file_name, + SourceType type, + TargetPlatform platform); + +bool TargetPlatformNeedsSL(TargetPlatform platform); + +bool TargetPlatformNeedsReflection(TargetPlatform platform); + +std::string ShaderCErrorToString(shaderc_compilation_status status); + +shaderc_shader_kind ToShaderCShaderKind(SourceType type); + +spv::ExecutionModel ToExecutionModel(SourceType type); + +spirv_cross::CompilerMSL::Options::Platform TargetPlatformToMSLPlatform( + TargetPlatform platform); + +} // namespace compiler +} // namespace impeller diff --git a/engine/src/flutter/impeller/tools/impeller.gni b/engine/src/flutter/impeller/tools/impeller.gni index f82595760b..e4430563b0 100644 --- a/engine/src/flutter/impeller/tools/impeller.gni +++ b/engine/src/flutter/impeller/tools/impeller.gni @@ -185,7 +185,7 @@ template("impeller_shaders_real") { args = [ "--input={{source}}", - "--metal=$metal_intermediate_path", + "--sl=$metal_intermediate_path", "--spirv=$spirv_intermediate_path", "--reflection-json=$reflection_json_path", "--reflection-header=$reflection_header_path", @@ -195,10 +195,10 @@ template("impeller_shaders_real") { ] if (is_mac) { - args += [ "--macos" ] + args += [ "--metal-desktop" ] } if (is_ios) { - args += [ "--ios" ] + args += [ "--metal-ios" ] } }