GPUDevice: Swap out glslang for shaderc

This commit is contained in:
Stenzek 2024-04-05 15:28:33 +10:00
parent e245884d16
commit 98241cb6ba
No known key found for this signature in database
15 changed files with 499 additions and 353 deletions

View File

@ -16,6 +16,11 @@ if(NOT WIN32 AND NOT ANDROID)
find_package(JPEG REQUIRED) # No version because flatpak uses libjpeg-turbo.
find_package(CURL REQUIRED)
find_package(Freetype 2.13.1 REQUIRED)
if(ENABLE_VULKAN OR APPLE)
find_package(Shaderc REQUIRED)
endif()
if(APPLE)
set(CMAKE_FIND_FRAMEWORK ${FIND_FRAMEWORK_BACKUP})
endif()

View File

@ -0,0 +1,32 @@
# - Try to find SHADERC
# Once done this will define
# SHADERC_FOUND - System has SHADERC
# SHADERC_INCLUDE_DIRS - The SHADERC include directories
# SHADERC_LIBRARIES - The libraries needed to use SHADERC
FIND_PATH(
SHADERC_INCLUDE_DIR shaderc/shaderc.h
HINTS /usr/include /usr/local/include
${SHADERC_PATH_INCLUDES}
)
FIND_LIBRARY(
SHADERC_LIBRARY
NAMES shaderc_shared
PATHS ${ADDITIONAL_LIBRARY_PATHS} ${SHADERC_PATH_LIB}
)
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(Shaderc DEFAULT_MSG
SHADERC_LIBRARY SHADERC_INCLUDE_DIR)
if(SHADERC_FOUND)
add_library(Shaderc::shaderc_shared UNKNOWN IMPORTED)
set_target_properties(Shaderc::shaderc_shared PROPERTIES
IMPORTED_LOCATION ${SHADERC_LIBRARY}
INTERFACE_INCLUDE_DIRECTORIES ${SHADERC_INCLUDE_DIR}
INTERFACE_COMPILE_DEFINITIONS "SHADERC_SHAREDLIB"
)
endif()
mark_as_advanced(SHADERC_INCLUDE_DIR SHADERC_LIBRARY)

View File

@ -522,6 +522,319 @@ NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
\****************************************************************************/
</pre>
<h3>Shaderc - <a href="https://github.com/google/shaderc">https://github.com/google/shaderc</a></h3>
<h3>SPIRV-Tools - <a href="https://github.com/KhronosGroup/SPIRV-Tools">https://github.com/KhronosGroup/SPIRV-Tools</a></h3>
<pre>
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
</pre>
<h3>SPIRV-Headers - <a href="https://github.com/KhronosGroup/SPIRV-Headers">https://github.com/KhronosGroup/SPIRV-Headers</a></h3>
<pre>
Files: All files except for those called out below.
Copyright (c) 2015-2024 The Khronos Group Inc.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and/or associated documentation files (the
"Materials"), to deal in the Materials without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Materials, and to
permit persons to whom the Materials are furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Materials.
MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS
KHRONOS STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS
SPECIFICATIONS AND HEADER INFORMATION ARE LOCATED AT
https://www.khronos.org/registry/
THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
---
Files: include/spirv/spir-v.xml
Copyright (c) 2015-2024 The Khronos Group Inc.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and/or associated documentation files (the
"Materials"), to deal in the Materials without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Materials, and to
permit persons to whom the Materials are furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Materials.
THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
---
Files: tools/buildHeaders/jsoncpp/*
The JsonCpp library's source code, including accompanying documentation,
tests and demonstration applications, are licensed under the following
conditions...
The author (Baptiste Lepilleur) explicitly disclaims copyright in all
jurisdictions which recognize such a disclaimer. In such jurisdictions,
this software is released into the Public Domain.
In jurisdictions which do not recognize Public Domain property (e.g. Germany as of
2010), this software is Copyright (c) 2007-2010 by Baptiste Lepilleur, and is
released under the terms of the MIT License (see below).
In jurisdictions which recognize Public Domain property, the user of this
software may choose to accept it either as 1) Public Domain, 2) under the
conditions of the MIT License (see below), or 3) under the terms of dual
Public Domain/MIT License conditions described here, as they choose.
The MIT License is about as close to Public Domain as a license can get, and is
described in clear, concise terms at:
http://en.wikipedia.org/wiki/MIT_License
The full text of the MIT License follows:
========================================================================
Copyright (c) 2007-2010 Baptiste Lepilleur
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use, copy,
modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
========================================================================
---
</pre>
<h3>Dear ImGui - <a href="https://github.com/ocornut/imgui">https://github.com/ocornut/imgui</a></h3>
<pre>
The MIT License (MIT)

View File

@ -154,17 +154,6 @@ if(ENABLE_OPENGL)
endif()
endif()
if(ENABLE_VULKAN OR APPLE)
target_sources(util PRIVATE
spirv_compiler.cpp
spirv_compiler.h
)
target_link_libraries(util PRIVATE glslang)
if(APPLE)
target_link_libraries(util PRIVATE spirv-cross)
endif()
endif()
if(ENABLE_VULKAN)
target_sources(util PRIVATE
vulkan_builders.cpp
@ -188,6 +177,10 @@ if(ENABLE_VULKAN)
target_link_libraries(util PUBLIC vulkan-headers)
endif()
if(ENABLE_VULKAN OR APPLE)
target_link_libraries(util PUBLIC Shaderc::shaderc_shared)
endif()
if(ENABLE_SDL2)
target_sources(util PRIVATE
sdl_audio_stream.cpp
@ -270,7 +263,7 @@ elseif(APPLE)
find_library(IOK_LIBRARY IOKit REQUIRED)
find_library(METAL_LIBRARY Metal)
find_library(QUARTZCORE_LIBRARY QuartzCore)
target_link_libraries(util PRIVATE ${METAL_LIBRARY} ${QUARTZCORE_LIBRARY} ${IOK_LIBRARY})
target_link_libraries(util PRIVATE ${METAL_LIBRARY} ${QUARTZCORE_LIBRARY} ${IOK_LIBRARY} spirv-cross)
set_source_files_properties(${MAC_SOURCES} PROPERTIES SKIP_PRECOMPILE_HEADERS TRUE)
elseif(NOT ANDROID)
target_sources(util PRIVATE

View File

@ -2,6 +2,7 @@
// SPDX-License-Identifier: (GPL-3.0 OR CC-BY-NC-ND-4.0)
#include "d3d_common.h"
#include "gpu_device.h"
#include "common/assert.h"
#include "common/error.h"
@ -18,8 +19,6 @@
Log_SetChannel(D3DCommon);
static unsigned s_next_bad_shader_id = 1;
const char* D3DCommon::GetFeatureLevelString(D3D_FEATURE_LEVEL feature_level)
{
static constexpr std::array<std::tuple<D3D_FEATURE_LEVEL, const char*>, 11> feature_level_names = {{
@ -424,31 +423,22 @@ std::optional<DynamicHeapArray<u8>> D3DCommon::CompileShader(D3D_FEATURE_LEVEL f
D3DCompile(source.data(), source.size(), "0", nullptr, nullptr, entry_point, target,
debug_device ? flags_debug : flags_non_debug, 0, blob.GetAddressOf(), error_blob.GetAddressOf());
std::string error_string;
std::string_view error_string;
if (error_blob)
{
error_string.append(static_cast<const char*>(error_blob->GetBufferPointer()), error_blob->GetBufferSize());
error_blob.Reset();
}
error_string =
std::string_view(static_cast<const char*>(error_blob->GetBufferPointer()), error_blob->GetBufferSize());
if (FAILED(hr))
{
Log_ErrorPrintf("Failed to compile '%s':\n%s", target, error_string.c_str());
auto fp = FileSystem::OpenManagedCFile(
GPUDevice::GetShaderDumpPath(fmt::format("bad_shader_{}.txt", s_next_bad_shader_id++)).c_str(), "wb");
if (fp)
{
std::fwrite(source.data(), source.size(), 1, fp.get());
std::fprintf(fp.get(), "\n\nCompile as %s failed: %08X\n", target, static_cast<unsigned>(hr));
std::fwrite(error_string.c_str(), error_string.size(), 1, fp.get());
}
Log_ErrorFmt("Failed to compile '{}':\n{}", target, error_string);
GPUDevice::DumpBadShader(source, error_string);
return {};
}
if (!error_string.empty())
Log_WarningPrintf("'%s' compiled with warnings:\n%s", target, error_string.c_str());
Log_WarningFmt("'{}' compiled with warnings:\n{}", target, error_string);
error_blob.Reset();
return DynamicHeapArray<u8>(static_cast<const u8*>(blob->GetBufferPointer()), blob->GetBufferSize());
}

View File

@ -736,6 +736,22 @@ std::string GPUDevice::GetShaderDumpPath(const std::string_view& name)
return Path::Combine(EmuFolders::Dumps, name);
}
void GPUDevice::DumpBadShader(std::string_view code, std::string_view errors)
{
static u32 next_bad_shader_id = 0;
const std::string filename = GetShaderDumpPath(fmt::format("bad_shader_{}.txt", ++next_bad_shader_id));
auto fp = FileSystem::OpenManagedCFile(filename.c_str(), "wb");
if (fp)
{
if (!code.empty())
std::fwrite(code.data(), code.size(), 1, fp.get());
std::fputs("\n\n**** ERRORS ****\n", fp.get());
if (!errors.empty())
std::fwrite(errors.data(), errors.size(), 1, fp.get());
}
}
std::array<float, 4> GPUDevice::RGBA8ToFloat(u32 rgba)
{
return std::array<float, 4>{static_cast<float>(rgba & UINT32_C(0xFF)) * (1.0f / 255.0f),

View File

@ -518,6 +518,9 @@ public:
/// Returns the directory bad shaders are saved to.
static std::string GetShaderDumpPath(const std::string_view& name);
/// Dumps out a shader that failed compilation.
static void DumpBadShader(std::string_view code, std::string_view errors);
/// Converts a RGBA8 value to 4 floating-point values.
static std::array<float, 4> RGBA8ToFloat(u32 rgba);

View File

@ -2,7 +2,6 @@
// SPDX-License-Identifier: (GPL-3.0 OR CC-BY-NC-ND-4.0)
#include "metal_device.h"
#include "spirv_compiler.h"
#include "common/align.h"
#include "common/assert.h"
@ -16,6 +15,10 @@
#define FMT_EXCEPTIONS 0
#include "fmt/format.h"
#include "shaderc/shaderc.hpp"
#include "spirv-cross/spirv_cross.hpp"
#include "spirv-cross/spirv_msl.hpp"
#include <array>
#include <pthread.h>
@ -56,7 +59,7 @@ static constexpr std::array<MTLPixelFormat, static_cast<u32>(GPUTexture::Format:
MTLPixelFormatBGR10A2Unorm, // RGB10A2
};
static unsigned s_next_bad_shader_id = 1;
static std::unique_ptr<shaderc::Compiler> s_shaderc_compiler;
static NSString* StringViewToNSString(const std::string_view& str)
{
@ -615,18 +618,8 @@ std::unique_ptr<GPUShader> MetalDevice::CreateShaderFromMSL(GPUShaderStage stage
{
LogNSError(error, "Failed to compile %s shader", GPUShader::GetStageName(stage));
auto fp = FileSystem::OpenManagedCFile(
Path::Combine(EmuFolders::DataRoot, fmt::format("bad_shader_{}.txt", s_next_bad_shader_id++)).c_str(), "wb");
if (fp)
{
std::fwrite(source.data(), source.size(), 1, fp.get());
std::fprintf(fp.get(), "\n\nCompile %s failed: %u\n", GPUShader::GetStageName(stage),
static_cast<u32>(error.code));
const char* utf_error = [error.description UTF8String];
std::fwrite(utf_error, std::strlen(utf_error), 1, fp.get());
}
const char* utf_error = [error.description UTF8String];
DumpBadShader(source, fmt::format("Error {}: {}", static_cast<u32>(error.code), utf_error ? utf_error : ""));
return {};
}
@ -651,42 +644,90 @@ std::unique_ptr<GPUShader> MetalDevice::CreateShaderFromSource(GPUShaderStage st
const char* entry_point,
DynamicHeapArray<u8>* out_binary /* = nullptr */)
{
const u32 options = (m_debug_device ? SPIRVCompiler::DebugInfo : 0) | SPIRVCompiler::VulkanRules;
static constexpr bool dump_shaders = false;
if (std::strcmp(entry_point, "main") != 0)
static constexpr const std::array<shaderc_shader_kind, static_cast<size_t>(GPUShaderStage::MaxCount)> stage_kinds = {{
shaderc_glsl_vertex_shader,
shaderc_glsl_fragment_shader,
shaderc_glsl_geometry_shader,
shaderc_glsl_compute_shader,
}};
// TODO: NOT thread safe, yet.
if (!s_shaderc_compiler)
s_shaderc_compiler = std::make_unique<shaderc::Compiler>();
shaderc::CompileOptions spv_options;
spv_options.SetSourceLanguage(shaderc_source_language_glsl);
spv_options.SetTargetEnvironment(shaderc_target_env_vulkan, 0);
if (m_debug_device)
{
Log_ErrorPrintf("Entry point must be 'main', but got '%s' instead.", entry_point);
return {};
spv_options.SetOptimizationLevel(shaderc_optimization_level_zero);
spv_options.SetGenerateDebugInfo();
}
else
{
spv_options.SetOptimizationLevel(shaderc_optimization_level_performance);
}
std::optional<SPIRVCompiler::SPIRVCodeVector> spirv = SPIRVCompiler::CompileShader(stage, source, options);
if (!spirv.has_value())
const shaderc::SpvCompilationResult result = s_shaderc_compiler->CompileGlslToSpv(
source.data(), source.length(), stage_kinds[static_cast<size_t>(stage)], "source", entry_point, spv_options);
if (result.GetCompilationStatus() != shaderc_compilation_status_success)
{
Log_ErrorPrintf("Failed to compile shader to SPIR-V.");
const std::string errors = result.GetErrorMessage();
DumpBadShader(source, errors);
Log_ErrorFmt("Failed to compile shader to SPIR-V:\n{}", errors);
return {};
}
else if (result.GetNumWarnings() > 0)
{
Log_WarningFmt("Shader compiled with warnings:\n{}", result.GetErrorMessage());
}
std::optional<std::string> msl = SPIRVCompiler::CompileSPIRVToMSL(stage, spirv.value());
if (!msl.has_value())
spirv_cross::CompilerMSL compiler(result.cbegin(), std::distance(result.cbegin(), result.cend()));
spirv_cross::CompilerMSL::Options msl_options = compiler.get_msl_options();
msl_options.pad_fragment_output_components = true;
if (stage == GPUShaderStage::Fragment)
{
for (u32 i = 0; i < MAX_TEXTURE_SAMPLERS; i++)
{
spirv_cross::MSLResourceBinding rb;
rb.stage = spv::ExecutionModelFragment;
rb.desc_set = 1;
rb.binding = i;
rb.count = 1;
rb.msl_texture = i;
rb.msl_sampler = i;
rb.msl_buffer = i;
compiler.add_msl_resource_binding(rb);
}
}
compiler.set_msl_options(msl_options);
const std::string msl = compiler.compile();
if (msl.empty())
{
Log_ErrorPrintf("Failed to compile SPIR-V to MSL.");
return {};
}
if constexpr (dump_shaders)
{
DumpShader(s_next_bad_shader_id, "_input", source);
DumpShader(s_next_bad_shader_id, "_msl", msl.value());
s_next_bad_shader_id++;
static unsigned s_next_id = 0;
++s_next_id;
DumpShader(s_next_id, "_input", source);
DumpShader(s_next_id, "_msl", msl);
}
if (out_binary)
{
out_binary->resize(msl->size());
std::memcpy(out_binary->data(), msl->data(), msl->size());
out_binary->resize(msl.size());
std::memcpy(out_binary->data(), msl.data(), msl.size());
}
return CreateShaderFromMSL(stage, msl.value(), "main0");
return CreateShaderFromMSL(stage, msl, "main0");
}
MetalPipeline::MetalPipeline(id<MTLRenderPipelineState> pipeline, id<MTLDepthStencilState> depth, MTLCullMode cull_mode,

View File

@ -43,8 +43,6 @@ struct PipelineDiskCacheIndexEntry
};
static_assert(sizeof(PipelineDiskCacheIndexEntry) == 112); // No padding
static unsigned s_next_bad_shader_id = 1;
static GLenum GetGLShaderType(GPUShaderStage stage)
{
static constexpr std::array<GLenum, static_cast<u32>(GPUShaderStage::MaxCount)> mapping = {{
@ -138,17 +136,8 @@ bool OpenGLShader::Compile()
}
else
{
Log_ErrorPrintf("Shader failed to compile:\n%s", info_log.c_str());
auto fp = FileSystem::OpenManagedCFile(
GPUDevice::GetShaderDumpPath(fmt::format("bad_shader_{}.txt", s_next_bad_shader_id++)).c_str(), "wb");
if (fp)
{
std::fwrite(m_source.data(), m_source.size(), 1, fp.get());
std::fprintf(fp.get(), "\n\nCompile %s shader failed\n", GPUShader::GetStageName(m_stage));
std::fwrite(info_log.c_str(), info_log_length, 1, fp.get());
}
Log_ErrorFmt("Shader failed to compile:\n{}", info_log);
GPUDevice::DumpBadShader(m_source, info_log);
glDeleteShader(shader);
return false;
}

View File

@ -1,205 +0,0 @@
// SPDX-FileCopyrightText: 2023 Connor McLaughlin <stenzek@gmail.com>
// SPDX-License-Identifier: (GPL-3.0 OR CC-BY-NC-ND-4.0)
#include "spirv_compiler.h"
#include "gpu_device.h"
#include "core/settings.h" // TODO: Remove me
#include "common/assert.h"
#include "common/file_system.h"
#include "common/log.h"
#include "common/path.h"
#include "common/string_util.h"
#include "fmt/format.h"
#include <cstring>
#include <memory>
Log_SetChannel(SPIRVCompiler);
// glslang includes
#include "SPIRV/GlslangToSpv.h"
#include "StandAlone/ResourceLimits.h"
#include "glslang/Public/ShaderLang.h"
#ifdef __APPLE__
#include "spirv-cross/spirv_cross.hpp"
#include "spirv-cross/spirv_msl.hpp"
#endif
namespace SPIRVCompiler {
static std::optional<SPIRVCodeVector> CompileShaderToSPV(EShLanguage stage, const char* stage_filename,
std::string_view source, u32 options);
static unsigned s_next_bad_shader_id = 1;
} // namespace SPIRVCompiler
std::optional<SPIRVCompiler::SPIRVCodeVector>
SPIRVCompiler::CompileShaderToSPV(EShLanguage stage, const char* stage_filename, std::string_view source, u32 options)
{
static bool glslang_initialized = false;
if (!glslang_initialized)
{
if (!glslang::InitializeProcess())
{
Panic("Failed to initialize glslang shader compiler");
return std::nullopt;
}
std::atexit(&glslang::FinalizeProcess);
glslang_initialized = true;
}
std::unique_ptr<glslang::TShader> shader = std::make_unique<glslang::TShader>(stage);
std::unique_ptr<glslang::TProgram> program;
glslang::TShader::ForbidIncluder includer;
const EProfile profile = ECoreProfile;
const EShMessages messages =
static_cast<EShMessages>(EShMsgDefault | EShMsgSpvRules | ((options & VulkanRules) ? EShMsgVulkanRules : 0) |
((options & DebugInfo) ? EShMsgDebugInfo : 0));
const int default_version = 450;
std::string full_source_code;
const char* pass_source_code = source.data();
int pass_source_code_length = static_cast<int>(source.size());
shader->setStringsWithLengths(&pass_source_code, &pass_source_code_length, 1);
auto DumpBadShader = [&](const char* msg) {
const std::string filename =
Path::Combine(EmuFolders::DataRoot, fmt::format("bad_shader_{}.txt", s_next_bad_shader_id++));
Log_ErrorPrintf("CompileShaderToSPV: %s, writing to %s", msg, filename.c_str());
auto fp = FileSystem::OpenManagedCFile(filename.c_str(), "wb");
if (fp)
{
std::fwrite(source.data(), source.size(), 1, fp.get());
std::fprintf(fp.get(), "\n\n%s\n", msg);
std::fprintf(fp.get(), "Shader Info Log:\n%s\n%s\n", shader->getInfoLog(), shader->getInfoDebugLog());
if (program)
std::fprintf(fp.get(), "Program Info Log:%s\n%s\n", program->getInfoLog(), program->getInfoDebugLog());
}
};
if (!shader->parse(&glslang::DefaultTBuiltInResource, default_version, profile, false, true, messages, includer))
{
DumpBadShader("Failed to parse shader");
return std::nullopt;
}
// Even though there's only a single shader, we still need to link it to generate SPV
program = std::make_unique<glslang::TProgram>();
program->addShader(shader.get());
if (!program->link(messages))
{
DumpBadShader("Failed to link program");
return std::nullopt;
}
glslang::TIntermediate* intermediate = program->getIntermediate(static_cast<EShLanguage>(stage));
if (!intermediate)
{
DumpBadShader("Failed to generate SPIR-V");
return std::nullopt;
}
SPIRVCodeVector out_code;
spv::SpvBuildLogger logger;
glslang::SpvOptions spvoptions;
spvoptions.generateDebugInfo = (options & DebugInfo) != 0;
glslang::GlslangToSpv(*intermediate, out_code, &logger, &spvoptions);
// Write out messages
if (std::strlen(shader->getInfoLog()) > 0)
Log_WarningPrintf("Shader info log: %s", shader->getInfoLog());
if (std::strlen(shader->getInfoDebugLog()) > 0)
Log_WarningPrintf("Shader debug info log: %s", shader->getInfoDebugLog());
if (std::strlen(program->getInfoLog()) > 0)
Log_WarningPrintf("Program info log: %s", program->getInfoLog());
if (std::strlen(program->getInfoDebugLog()) > 0)
Log_WarningPrintf("Program debug info log: %s", program->getInfoDebugLog());
std::string spv_messages = logger.getAllMessages();
if (!spv_messages.empty())
Log_WarningPrintf("SPIR-V conversion messages: %s", spv_messages.c_str());
return out_code;
}
std::optional<SPIRVCompiler::SPIRVCodeVector> SPIRVCompiler::CompileVertexShader(std::string_view source_code,
u32 options)
{
return CompileShaderToSPV(EShLangVertex, "vs", source_code, options);
}
std::optional<SPIRVCompiler::SPIRVCodeVector> SPIRVCompiler::CompileFragmentShader(std::string_view source_code,
u32 options)
{
return CompileShaderToSPV(EShLangFragment, "ps", source_code, options);
}
std::optional<SPIRVCompiler::SPIRVCodeVector> SPIRVCompiler::CompileGeometryShader(std::string_view source_code,
u32 options)
{
return CompileShaderToSPV(EShLangGeometry, "gs", source_code, options);
}
std::optional<SPIRVCompiler::SPIRVCodeVector> SPIRVCompiler::CompileComputeShader(std::string_view source_code,
u32 options)
{
return CompileShaderToSPV(EShLangCompute, "cs", source_code, options);
}
std::optional<SPIRVCompiler::SPIRVCodeVector> SPIRVCompiler::CompileShader(GPUShaderStage type,
std::string_view source_code, u32 options)
{
switch (type)
{
case GPUShaderStage::Vertex:
return CompileShaderToSPV(EShLangVertex, "vs", source_code, options);
case GPUShaderStage::Fragment:
return CompileShaderToSPV(EShLangFragment, "ps", source_code, options);
case GPUShaderStage::Geometry:
return CompileShaderToSPV(EShLangGeometry, "gs", source_code, options);
case GPUShaderStage::Compute:
return CompileShaderToSPV(EShLangCompute, "cs", source_code, options);
default:
return std::nullopt;
}
}
#ifdef __APPLE__
std::optional<std::string> SPIRVCompiler::CompileSPIRVToMSL(GPUShaderStage stage, std::span<const SPIRVCodeType> spv)
{
spirv_cross::CompilerMSL compiler(spv.data(), spv.size());
spirv_cross::CompilerMSL::Options options = compiler.get_msl_options();
options.pad_fragment_output_components = true;
if (stage == GPUShaderStage::Fragment)
{
for (u32 i = 0; i < GPUDevice::MAX_TEXTURE_SAMPLERS; i++)
{
spirv_cross::MSLResourceBinding rb;
rb.stage = spv::ExecutionModelFragment;
rb.desc_set = 1;
rb.binding = i;
rb.count = 1;
rb.msl_texture = i;
rb.msl_sampler = i;
rb.msl_buffer = i;
compiler.add_msl_resource_binding(rb);
}
}
compiler.set_msl_options(options);
std::string msl = compiler.compile();
return (msl.empty()) ? std::optional<std::string>() : std::optional<std::string>(std::move(msl));
}
#endif

View File

@ -1,49 +0,0 @@
// SPDX-FileCopyrightText: 2023 Connor McLaughlin <stenzek@gmail.com>
// SPDX-License-Identifier: (GPL-3.0 OR CC-BY-NC-ND-4.0)
#pragma once
#include "common/types.h"
#include <optional>
#include <span>
#include <string>
#include <string_view>
#include <vector>
enum class GPUShaderStage : u8;
namespace SPIRVCompiler {
enum CompileOptions
{
DebugInfo = (1 << 0),
VulkanRules = (1 << 1),
};
// SPIR-V compiled code type
using SPIRVCodeType = u32;
using SPIRVCodeVector = std::vector<SPIRVCodeType>;
// Compile a vertex shader to SPIR-V.
std::optional<SPIRVCodeVector> CompileVertexShader(std::string_view source_code, u32 options);
// Compile a fragment shader to SPIR-V.
std::optional<SPIRVCodeVector> CompileFragmentShader(std::string_view source_code, u32 options);
// Compile a geometry shader to SPIR-V.
std::optional<SPIRVCodeVector> CompileGeometryShader(std::string_view source_code, u32 options);
// Compile a compute shader to SPIR-V.
std::optional<SPIRVCodeVector> CompileComputeShader(std::string_view source_code, u32 options);
std::optional<SPIRVCodeVector> CompileShader(GPUShaderStage stage, std::string_view source_code, u32 options);
#ifdef __APPLE__
// Converts a SPIR-V shader into MSL.
std::optional<std::string> CompileSPIRVToMSL(GPUShaderStage stage, std::span<const SPIRVCodeType> spv);
#endif
} // namespace SPIRVCompiler

View File

@ -4,7 +4,7 @@
<ItemDefinitionGroup>
<ClCompile>
<PreprocessorDefinitions>%(PreprocessorDefinitions);SOUNDTOUCH_FLOAT_SAMPLES;SOUNDTOUCH_ALLOW_SSE;ST_NO_EXCEPTION_HANDLING=1</PreprocessorDefinitions>
<PreprocessorDefinitions>%(PreprocessorDefinitions);SOUNDTOUCH_FLOAT_SAMPLES;SOUNDTOUCH_ALLOW_SSE;ST_NO_EXCEPTION_HANDLING=1;SHADERC_SHAREDLIB</PreprocessorDefinitions>
<PreprocessorDefinitions>ENABLE_CUBEB=1;ENABLE_SDL2=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PreprocessorDefinitions Condition="'$(Platform)'!='ARM64'">%(PreprocessorDefinitions);ENABLE_OPENGL=1;ENABLE_VULKAN=1</PreprocessorDefinitions>
<PreprocessorDefinitions Condition="'$(Platform)'=='ARM64'">%(PreprocessorDefinitions);SOUNDTOUCH_USE_NEON</PreprocessorDefinitions>
@ -28,7 +28,7 @@
<AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(DepsIncludeDir)SDL2</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<AdditionalDependencies>%(AdditionalDependencies);freetype.lib;libjpeg.lib;libpng16.lib;libwebp.lib;SDL2.lib;zlib.lib;zstd.lib</AdditionalDependencies>
<AdditionalDependencies>%(AdditionalDependencies);freetype.lib;libjpeg.lib;libpng16.lib;libwebp.lib;SDL2.lib;shaderc_shared.lib;zlib.lib;zstd.lib</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
@ -39,6 +39,7 @@
<DepsDLLs Include="$(DepsBinDir)libsharpyuv.dll" />
<DepsDLLs Include="$(DepsBinDir)libwebp.dll" />
<DepsDLLs Include="$(DepsBinDir)SDL2.dll" />
<DepsDLLs Include="$(DepsBinDir)shaderc_shared.dll" />
<DepsDLLs Include="$(DepsBinDir)zlib1.dll" />
<DepsDLLs Include="$(DepsBinDir)zstd.dll" />
</ItemGroup>

View File

@ -88,9 +88,6 @@
<ClInclude Include="sdl_input_source.h" />
<ClInclude Include="shadergen.h" />
<ClInclude Include="shiftjis.h" />
<ClInclude Include="spirv_compiler.h">
<ExcludedFromBuild Condition="'$(Platform)'=='ARM64'">true</ExcludedFromBuild>
</ClInclude>
<ClInclude Include="state_wrapper.h" />
<ClInclude Include="cd_xa.h" />
<ClInclude Include="vulkan_builders.h">
@ -208,9 +205,6 @@
<ClCompile Include="shadergen.cpp" />
<ClCompile Include="shiftjis.cpp" />
<ClCompile Include="page_fault_handler.cpp" />
<ClCompile Include="spirv_compiler.cpp">
<ExcludedFromBuild Condition="'$(Platform)'=='ARM64'">true</ExcludedFromBuild>
</ClCompile>
<ClCompile Include="state_wrapper.cpp" />
<ClCompile Include="cd_xa.cpp" />
<ClCompile Include="vulkan_builders.cpp">
@ -263,9 +257,6 @@
<ProjectReference Include="..\..\dep\glad\glad.vcxproj" Condition="'$(Platform)'!='ARM64'">
<Project>{43540154-9e1e-409c-834f-b84be5621388}</Project>
</ProjectReference>
<ProjectReference Include="..\..\dep\glslang\glslang.vcxproj" Condition="'$(Platform)'!='ARM64'">
<Project>{7f909e29-4808-4bd9-a60c-56c51a3aaec2}</Project>
</ProjectReference>
<ProjectReference Include="..\common\common.vcxproj">
<Project>{ee054e08-3799-4a59-a422-18259c105ffd}</Project>
</ProjectReference>

View File

@ -32,7 +32,6 @@
<ClInclude Include="opengl_pipeline.h" />
<ClInclude Include="opengl_stream_buffer.h" />
<ClInclude Include="opengl_texture.h" />
<ClInclude Include="spirv_compiler.h" />
<ClInclude Include="vulkan_builders.h" />
<ClInclude Include="vulkan_device.h" />
<ClInclude Include="vulkan_entry_points.h" />
@ -117,7 +116,6 @@
<ClCompile Include="opengl_pipeline.cpp" />
<ClCompile Include="opengl_stream_buffer.cpp" />
<ClCompile Include="opengl_texture.cpp" />
<ClCompile Include="spirv_compiler.cpp" />
<ClCompile Include="vulkan_builders.cpp" />
<ClCompile Include="vulkan_device.cpp" />
<ClCompile Include="vulkan_loader.cpp" />

View File

@ -1,16 +1,19 @@
// SPDX-FileCopyrightText: 2019-2023 Connor McLaughlin <stenzek@gmail.com>
// SPDX-FileCopyrightText: 2019-2024 Connor McLaughlin <stenzek@gmail.com>
// SPDX-License-Identifier: (GPL-3.0 OR CC-BY-NC-ND-4.0)
#include "vulkan_pipeline.h"
#include "spirv_compiler.h"
#include "vulkan_builders.h"
#include "vulkan_device.h"
#include "common/assert.h"
#include "common/log.h"
#include "shaderc/shaderc.hpp"
Log_SetChannel(VulkanDevice);
static std::unique_ptr<shaderc::Compiler> s_shaderc_compiler;
VulkanShader::VulkanShader(GPUShaderStage stage, VkShaderModule mod) : GPUShader(stage), m_module(mod)
{
}
@ -45,29 +48,54 @@ std::unique_ptr<GPUShader> VulkanDevice::CreateShaderFromSource(GPUShaderStage s
const char* entry_point,
DynamicHeapArray<u8>* out_binary)
{
if (std::strcmp(entry_point, "main") != 0)
static constexpr const std::array<shaderc_shader_kind, static_cast<size_t>(GPUShaderStage::MaxCount)> stage_kinds = {{
shaderc_glsl_vertex_shader,
shaderc_glsl_fragment_shader,
shaderc_glsl_geometry_shader,
shaderc_glsl_compute_shader,
}};
// TODO: NOT thread safe, yet.
if (!s_shaderc_compiler)
s_shaderc_compiler = std::make_unique<shaderc::Compiler>();
shaderc::CompileOptions options;
options.SetSourceLanguage(shaderc_source_language_glsl);
options.SetTargetEnvironment(shaderc_target_env_vulkan, 0);
if (m_debug_device)
{
Log_ErrorPrintf("Entry point must be 'main', but got '%s' instead.", entry_point);
return {};
options.SetOptimizationLevel(shaderc_optimization_level_zero);
options.SetGenerateDebugInfo();
}
else
{
options.SetOptimizationLevel(shaderc_optimization_level_performance);
}
const u32 options = (m_debug_device ? SPIRVCompiler::DebugInfo : 0) | SPIRVCompiler::VulkanRules;
std::optional<SPIRVCompiler::SPIRVCodeVector> spirv = SPIRVCompiler::CompileShader(stage, source, options);
if (!spirv.has_value())
const shaderc::SpvCompilationResult result = s_shaderc_compiler->CompileGlslToSpv(
source.data(), source.length(), stage_kinds[static_cast<size_t>(stage)], "source", entry_point, options);
if (result.GetCompilationStatus() != shaderc_compilation_status_success)
{
Log_ErrorPrintf("Failed to compile shader to SPIR-V.");
const std::string errors = result.GetErrorMessage();
DumpBadShader(source, errors);
Log_ErrorFmt("Failed to compile shader to SPIR-V:\n{}", errors);
return {};
}
else if (result.GetNumWarnings() > 0)
{
Log_WarningFmt("Shader compiled with warnings:\n{}", result.GetErrorMessage());
}
const size_t spirv_size = spirv->size() * sizeof(SPIRVCompiler::SPIRVCodeType);
const size_t spirv_size = std::distance(result.cbegin(), result.cend()) * sizeof(*result.cbegin());
DebugAssert(spirv_size > 0);
if (out_binary)
{
out_binary->resize(spirv_size);
std::memcpy(out_binary->data(), spirv->data(), spirv_size);
std::copy(result.cbegin(), result.cend(), reinterpret_cast<uint32_t*>(out_binary->data()));
}
return CreateShaderFromBinary(stage, std::span<const u8>(reinterpret_cast<const u8*>(spirv->data()), spirv_size));
return CreateShaderFromBinary(stage, std::span<const u8>(reinterpret_cast<const u8*>(result.cbegin()), spirv_size));
}
//////////////////////////////////////////////////////////////////////////