Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 90 additions & 0 deletions .github/workflows/wgsl.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
name: WGSL backend

on:
pull_request:
paths:
- .github/workflows/wgsl.yml
- CMakeLists.txt
- core/shader/recompiler/**
- tools/wgsl-check/**
push:
branches: [main]
paths:
- .github/workflows/wgsl.yml
- CMakeLists.txt
- core/shader/recompiler/**
- tools/wgsl-check/**

permissions:
contents: read

jobs:
native-compatibility-and-wgsl:
runs-on: ubuntu-latest
timeout-minutes: 25
env:
ANYPS5_REQUIRE_VULKAN: '1'
ANYPS5_NO_SHADER_CACHE: '1'
VK_INSTANCE_LAYERS: VK_LAYER_KHRONOS_validation
VK_LOADER_DEBUG: layer
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
ref: ${{ github.event.pull_request.head.sha || github.sha }}
fetch-depth: 0
- name: Select native compatibility baseline
id: native-base
env:
NATIVE_BASE_REF: ${{ github.event.pull_request.base.sha || github.event.before }}
run: |
git fetch --no-tags --no-recurse-submodules origin "$NATIVE_BASE_REF"
native_base_commit=$(git merge-base HEAD "$NATIVE_BASE_REF")
echo "sha=$native_base_commit" >> "$GITHUB_OUTPUT"
echo "Native baseline: $native_base_commit; candidate: $(git rev-parse HEAD)"
git submodule update --init 3rdparty/SPIRV-Headers
- uses: actions/checkout@v7
with:
repository: boykopovar/AnyPS5
ref: ${{ steps.native-base.outputs.sha }}
path: native-main
persist-credentials: false
- name: Install software Vulkan and validation layers
run: sudo apt-get update && sudo apt-get install -y mesa-vulkan-drivers vulkan-validationlayers
- name: Build and check native shader compatibility
shell: bash
run: |
cmake -S . -B build-shaders -DCMAKE_BUILD_TYPE=Release -DANYPS5_BUILD_SHADER_TOOLS=ON -DBUILD_TESTING=ON
cmake --build build-shaders --parallel 2
cmake -S core/shader/recompiler/tests/native_snapshot -B build-native-main -DCMAKE_BUILD_TYPE=Release -DANYPS5_NATIVE_SOURCE="$GITHUB_WORKSPACE/native-main"
cmake --build build-native-main --parallel 2
ctest --test-dir build-native-main -R '^shader_native_snapshot$' -V | tee main-validation.log
ctest --test-dir build-shaders -R '^(wgsl_native_compat|shader_native_snapshot)$' -V | tee native-validation.log
python3 - <<'PY'
from pathlib import Path
baseline = Path('build-native-main/native-snapshots')
candidate = Path('build-shaders/core/shader/recompiler/WgslBackend/tools/native-snapshots')
assert len(list(baseline.iterdir())) == 9
for source in baseline.iterdir():
assert source.read_bytes() == (candidate / source.name).read_bytes(), source.name
PY
build-shaders/core/shader/recompiler/WgslBackend/tools/wgsl_native_compat_tests --emit-wgsl shader-fixtures
- uses: actions/setup-node@v6
with:
node-version: '26'
- name: Check generated WGSL with browser WebGPU
shell: bash
run: |
node tools/wgsl-check/check.cjs shader-fixtures/program-{0,1,2} 2>&1 | tee wgsl-validation.log
printf 'not valid wgsl' > "$RUNNER_TEMP/invalid.cs.wgsl"
if node tools/wgsl-check/check.cjs "$RUNNER_TEMP/invalid" > invalid-wgsl.log 2>&1; then exit 1; fi
grep -q 'shader 0:' invalid-wgsl.log
python3 - <<'PY'
from pathlib import Path
assert 'Insert instance layer "VK_LAYER_KHRONOS_validation"' in Path('wgsl-validation.log').read_text()
for name in ('main-validation.log', 'native-validation.log', 'wgsl-validation.log'):
text = Path(name).read_text()
assert 'VUID-' not in text, name
assert 'was not found but was requested by env var VK_INSTANCE_LAYERS' not in text, name
assert 'SKIP ' not in text, name
PY
10 changes: 10 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,16 @@ option(BUILD_TESTING "Build and register relinker tests" OFF)
option(ANYPS5_RELINKER_ONLY "Build the relinker without system libraries or third-party dependencies" OFF)
option(ANYPS5_BUILD_WASM "Build the browser relinker" OFF)
option(ANYPS5_RELINKER_CLI "Build the native relinker command line" ON)
option(ANYPS5_BUILD_SHADER_TOOLS "Build the native shader recompiler tools without the system libraries" OFF)
if(ANYPS5_BUILD_SHADER_TOOLS)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
if(BUILD_TESTING)
enable_testing()
endif()
add_subdirectory(core/shader/recompiler/WgslBackend/tools)
return()
endif()
if(ANYPS5_BUILD_WASM)
if(NOT EMSCRIPTEN)
message(FATAL_ERROR "ANYPS5_BUILD_WASM requires emcmake and Emscripten")
Expand Down
4 changes: 4 additions & 0 deletions core/shader/recompiler/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,9 @@ function(add_shader_recompiler target runtimeTarget)
${CMAKE_CURRENT_FUNCTION_LIST_DIR}/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp
${CMAKE_CURRENT_FUNCTION_LIST_DIR}/SpirvBackend/src/SpirvMemory/SpirvMemoryInstructions.cpp

${CMAKE_CURRENT_FUNCTION_LIST_DIR}/WgslBackend/src/WgslEmitter.cpp
${CMAKE_CURRENT_FUNCTION_LIST_DIR}/WgslBackend/src/WgslTarget.cpp

${CMAKE_CURRENT_FUNCTION_LIST_DIR}/tests/DummyShaders.cpp
)

Expand All @@ -182,6 +185,7 @@ function(add_shader_recompiler target runtimeTarget)
${CMAKE_CURRENT_FUNCTION_LIST_DIR}/Translation/include
${CMAKE_CURRENT_FUNCTION_LIST_DIR}/Optimization/include
${CMAKE_CURRENT_FUNCTION_LIST_DIR}/SpirvBackend/include
${CMAKE_CURRENT_FUNCTION_LIST_DIR}/WgslBackend/include
${ANYPS5_SPIRV_HEADERS_INCLUDE_DIR}
${ANYPS5_GLSLANG_INCLUDE_DIRS}
)
Expand Down
1 change: 1 addition & 0 deletions core/shader/recompiler/CacheKey.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -406,6 +406,7 @@ class RecompileCacheKey {
append(key, value.spannedShuffleThroughMemory);
append(key, value.spannedUnreachableStays);
append(key, value.spannedUnreachableVerify);
if (value.wgsl) append(key, std::uint64_t{1});
}
};

Expand Down
2 changes: 2 additions & 0 deletions core/shader/recompiler/CompiledVariant.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,15 @@ class BufferSubstituteTable {
mutable std::mutex mutex;
std::vector<BufferSubstitute> slots;
};
class WgslSource;

struct CompiledVariant {
BindingLayout layout;
CompiledShaderInfo info;
CompiledBindingLayout bindings;
CompiledShaderArtifact artifact;
std::shared_ptr<BufferSubstituteTable> substitutes;
std::shared_ptr<const WgslSource> wgsl;
};

}
Expand Down
63 changes: 53 additions & 10 deletions core/shader/recompiler/Recompiler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
#include "Optimization/include/Optimization/SsaBuilder.hpp"
#include "Optimization/include/Optimization/TessellationLowering.hpp"
#include "SpirvBackend/include/SpirvBackend/SpirvEmitter.hpp"
#include "WgslBackend/WgslEmitter.hpp"
#if ANYPS5_ENABLE_SPIRV_TOOLS
#include "SpirvBackend/SpirvOptimizer.hpp"
#endif
Expand Down Expand Up @@ -925,12 +926,14 @@ CompiledVariant emitVariant(const RecompileRequest& request, IrProgram& program)
CompiledShaderArtifact result;
result.variantId = nextVariantId();
SpirvEmitInfo emitted;
try {
result.spirv = spirvEmitter.Emit(program, inputInfo, bindings, targetOptions, &emitted);
} catch (const SpannedWaveUnsupported& error) {
std::fprintf(stderr, "[spanned-wave] 0x%llx falls back to two lanes per invocation: %s\n", static_cast<unsigned long long>(request.shader.codeAddress), error.what());
targetOptions.spannedWaves = false;
result.spirv = spirvEmitter.Emit(program, inputInfo, bindings, targetOptions, &emitted);
if (!request.target.wgsl) {
try {
result.spirv = spirvEmitter.Emit(program, inputInfo, bindings, targetOptions, &emitted);
} catch (const SpannedWaveUnsupported& error) {
std::fprintf(stderr, "[spanned-wave] 0x%llx falls back to two lanes per invocation: %s\n", static_cast<unsigned long long>(request.shader.codeAddress), error.what());
targetOptions.spannedWaves = false;
result.spirv = spirvEmitter.Emit(program, inputInfo, bindings, targetOptions, &emitted);
}
}
if (registration && result.spirv.size() > request.target.registrationWordLimit) {
registration = false;
Expand Down Expand Up @@ -997,6 +1000,7 @@ CompiledVariant emitVariant(const RecompileRequest& request, IrProgram& program)
}

const bool embedded = !result.vertexInputs.empty() && inputInfo.vertex != nullptr && inputInfo.vertex->fetchEmbedded;
if (request.target.wgsl) return {request.layout, {}, std::move(static_cast<CompiledBindingLayout&>(bindings)), std::move(result)};
if (embedded) PrepareVertexInputSpecialization(result);
#if ANYPS5_ENABLE_SPIRV_TOOLS
result.spirv = ValidateAndOptimizeSpirv(result.spirv, request.target.vulkanVersion, request.target.spirvVersion, request.target.nonConstantImageOffsets, !embedded);
Expand Down Expand Up @@ -1037,6 +1041,11 @@ CompiledVariant compileVariant(const RecompileRequest& request, IrProgram progra
prepareInterface(request, program);
auto variant = emitVariant(request, program);
throwInjectedNanFailure(request);
if (request.target.wgsl) {
variant.info = program.CompiledInfo();
variant.wgsl = std::make_shared<const WgslSource>(std::move(program));
return variant;
}
variant.info = std::move(program).TakeCompiledInfo();
return variant;
});
Expand Down Expand Up @@ -1577,6 +1586,7 @@ RecompileResult materializeResult(const CompiledVariant& variant, const Recompil
}
const auto plan = preparedBindingPlan(variant, snapshot, request.context.pixel ? std::span<const std::uint8_t>(request.context.pixel->targetExportMapping) : std::span<const std::uint8_t>{}, request.target.registrationModules, substitutes, request.target.shaderImageMinLod, request.target.storageReadFormats);
const DescriptorBindingPlan* bindingPlan = &plan->bindings;
DescriptorBindingPlan wgslPlan;
std::shared_ptr<PreparedModuleEntry> entry;
struct LocalModuleKeyStorage {};
auto& moduleKey = HostThreadLocal<std::vector<std::uint32_t>, LocalModuleKeyStorage>();
Expand All @@ -1597,6 +1607,8 @@ RecompileResult materializeResult(const CompiledVariant& variant, const Recompil
}
moduleKey.push_back(request.context.vertex->depthRemapMode);
}
const bool wgsl = variant.wgsl != nullptr;
const bool vertexSelectors = !artifact.vertexInputPatches.empty() || (wgsl && request.context.vertex && request.context.vertex->fetchEmbedded);
result.vertexAttributes.reserve(result.vertexInputs.size());
std::array<std::uint32_t, ShaderVertexStageInfo::MaxResources> vertexClasses{};
std::array<std::uint32_t, ShaderVertexStageInfo::MaxResources / RuntimeAbi::VertexSelectorsPerDword> runtimeSelectors{};
Expand All @@ -1606,7 +1618,7 @@ RecompileResult materializeResult(const CompiledVariant& variant, const Recompil
const auto& resource = vertex.resources[input.location];
const auto fetchIndex = vertex.fetchEmbedded ? vertex.resourcesDst[input.location].fetchIndex : input.fetchIndex;
result.vertexAttributes.push_back({input.location, input.components, resource, fetchIndex});
if (!artifact.vertexInputPatches.empty()) {
if (vertexSelectors) {
const auto format = static_cast<IrBufferFormat>((resource.fields[3] >> 12u) & 0x7fu);
const auto numeric = registrationDefaults && format == IrBufferFormat::Invalid ? IrTextureNumericClass::Float : VertexInputNumericClass(format);
if (numeric == IrTextureNumericClass::Unsupported) throw std::runtime_error("unsupported prepared vertex format");
Expand All @@ -1631,7 +1643,38 @@ RecompileResult materializeResult(const CompiledVariant& variant, const Recompil
if (artifact.registrationModule) runtimeSelectors.at(input.location / RuntimeAbi::VertexSelectorsPerDword) |= (selectors & 0xfffu) << (input.location % RuntimeAbi::VertexSelectorsPerDword * 16u);
}
}
if (!plan->bindings.specialization.empty() || variant.bindings.layout.UsesPushData() || !artifact.vertexInputPatches.empty() || request.context.pixel || depthRemap || request.shader.stage == ShaderStage::Mesh) {
if (wgsl) {
auto constants = plan->bindings.specialization;
std::size_t index = 0;
if (variant.bindings.layout.UsesPushData()) constants.push_back({PipelineSpecialization::PushDataOffset, moduleKey[index++]});
if (!artifact.stencilReferences.empty()) constants.push_back({PipelineSpecialization::StencilReferenceOffset, moduleKey[index++]});
if (request.context.pixel) {
for (std::uint32_t target = 0; target < request.context.pixel->targetExportPacking.size(); ++target) constants.push_back({PipelineSpecialization::ExportPackingBase + target, moduleKey[index++]});
constants.push_back({PipelineSpecialization::DualSourceBlend, moduleKey[index++]});
constants.push_back({PipelineSpecialization::ReversedBlend, moduleKey[index++]});
if (variant.info.info.rasterPrimitive) constants.push_back({PipelineSpecialization::RasterPrimitive, moduleKey[index++]});
if (variant.info.info.layerExported) constants.push_back({PipelineSpecialization::LayerExported, moduleKey[index++]});
}
if (depthRemap) {
for (std::uint32_t word = 0; word < PipelineSpecialization::DepthRemapWords; ++word) constants.push_back({PipelineSpecialization::DepthRemapBase + word, moduleKey[index++]});
}
for (const auto& input : result.vertexInputs) {
if (!vertexSelectors) break;
const auto selectors = moduleKey[index++];
const auto first = PipelineSpecialization::VertexBase + input.location * PipelineSpecialization::VertexWords;
for (std::uint32_t component = 0; component < 4u; ++component) constants.push_back({first + component, (selectors >> (component * 3u)) & 7u});
const auto kind = selectors >> 12u;
constants.push_back({first + 4u, kind == 0u ? 0x3f800000u : 1u});
constants.push_back({first + 5u, kind});
}
std::vector<WgslPlanBinding> planBindings;
planBindings.reserve(plan->bindings.bindings.size());
for (const auto& binding : plan->bindings.bindings) planBindings.push_back({binding.descriptor.binding, binding.descriptor.count});
const auto module = variant.wgsl->Module(RequestInputInfo(request), constants, planBindings);
result.wgsl = module->source;
wgslPlan = DescriptorBindingBuilder{}.Select(plan->bindings, module->bindings);
bindingPlan = &wgslPlan;
} else if (!plan->bindings.specialization.empty() || variant.bindings.layout.UsesPushData() || !artifact.vertexInputPatches.empty() || request.context.pixel || depthRemap || request.shader.stage == ShaderStage::Mesh) {
{
std::shared_lock lock(plan->mutex);
if (const auto found = plan->modules.find(moduleKey); found != plan->modules.end()) entry = found->second;
Expand Down Expand Up @@ -1894,7 +1937,7 @@ std::shared_ptr<const CompiledVariant> findOrCompileVariant(SourceEntry& source,
if (failure.codeAddress == request.shader.codeAddress && sameLayout(failure.layout, request.layout)) std::rethrow_exception(failure.failure);
}
cacheHit = false;
const bool disk = ShaderDiskCache::Enabled() && !DebugProbeActive();
const bool disk = ShaderDiskCache::Enabled() && !DebugProbeActive() && !request.target.wgsl;
std::vector<std::byte> diskKey;
std::shared_ptr<const CompiledVariant> variant;
if (disk) {
Expand All @@ -1918,7 +1961,7 @@ std::shared_ptr<const CompiledVariant> findOrCompileVariant(SourceEntry& source,
std::exception_ptr emissionFailure;
try {
auto compiled = [&] {
if (layoutPair && preparation != nullptr) return CountedCompile([&] { return PreparedInterface::Compile(source, request, *preparation, &emissionFailure); });
if (layoutPair && preparation != nullptr && !request.target.wgsl) return CountedCompile([&] { return PreparedInterface::Compile(source, request, *preparation, &emissionFailure); });
auto program = source.program != nullptr ? std::move(*source.program) : PrepareResourceProgram(request, preparation);
source.program.reset();
return CountedCompile([&] { return compileVariant(request, std::move(program), &emissionFailure); });
Expand Down
3 changes: 3 additions & 0 deletions core/shader/recompiler/Recompiler.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
#include <stdexcept>
#include <functional>
#include <utility>
#include <string>
#include <string_view>
#include <vector>

Expand Down Expand Up @@ -405,6 +406,7 @@ struct SpirvTarget {
bool spannedShuffleThroughMemory = false;
bool spannedUnreachableStays = false;
bool spannedUnreachableVerify = false;
bool wgsl = false;
};

struct BindingLayout {
Expand Down Expand Up @@ -927,6 +929,7 @@ struct VertexInputPatch {
struct CompiledShaderArtifact {
std::vector<VertexInputPatch> vertexInputPatches;
SharedSpirv spirv;
std::string wgsl;
std::uint32_t memoryOffsetDword = 0;
std::uint32_t shaderDataDwords = 0;
std::uint32_t imageMetadataDword = 0;
Expand Down
9 changes: 6 additions & 3 deletions core/shader/recompiler/ShaderDiskCache.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,9 @@ namespace ShaderRecompiler {
std::filesystem::path ShaderCacheDirectory() {
const char* disabled = std::getenv("ANYPS5_NO_SHADER_CACHE");
if (disabled != nullptr && *disabled != '\0' && std::strcmp(disabled, "0") != 0) return {};
#ifdef _WIN32
#if defined(__EMSCRIPTEN__)
return {};
#elif defined(_WIN32)
const wchar_t* directory = _wgetenv(L"ANYPS5_SHADER_CACHE_DIR");
if (directory != nullptr && *directory != L'\0') return std::filesystem::path(directory);
std::wstring executable(MAX_PATH, L'\0');
Expand Down Expand Up @@ -88,10 +90,10 @@ std::filesystem::path ShaderCacheDirectory() {
namespace ShaderRecompiler::ShaderDiskCache {

#if defined(__linux__) && defined(__x86_64__) && defined(__GLIBCXX__)
static_assert(sizeof(CompiledShaderArtifact) == 296, "CompiledShaderArtifact changed: update the artifact encoder");
static_assert(sizeof(CompiledShaderArtifact) == 328, "CompiledShaderArtifact changed: update the artifact encoder");
static_assert(sizeof(ShaderInvocation) == 216, "ShaderInvocation changed: update the invocation encoder");
#if defined(__cpp_lib_atomic_shared_ptr)
static_assert(sizeof(RecompileResult) == 568, "RecompileResult changed: update EncodeResult and DecodeResult");
static_assert(sizeof(RecompileResult) == 600, "RecompileResult changed: update EncodeResult and DecodeResult");
#endif
static_assert(sizeof(DescriptorBinding) == 944, "DescriptorBinding changed: update the binding encoder");
static_assert(sizeof(VertexAttribute) == 32, "VertexAttribute changed: update the attribute encoder");
Expand Down Expand Up @@ -631,6 +633,7 @@ void encodeArtifact(Writer& writer, const CompiledShaderArtifact& result) {
void decodeArtifact(Reader& reader, CompiledShaderArtifact& result) {
reader.Value(result.runtimeAbiVersion);
result.spirv = reader.Spirv();
result.wgsl.clear();
reader.Value(result.bdaAbiVersion);
reader.Value(result.windowLaneGuards);
reader.Value(result.descriptorFaults);
Expand Down
Loading
Loading