graphics: prototype native GPU PerVertex replay and shader caches #715

Closed
github-bot wants to merge 22 commits from gh-pr/715/head into gh-pr/715/base
Owner

@⁠carbonimax on GitHub · 2026-09-19 10:28 UTC · original
carbonimax:codex/native-pervertex-cache → main · +6233 −1397 · 60 files · 22 commits · closed without merging

Current status — draft (2026-10-01)

This is the historical opt-in Kyty-side prototype. The current integration work uses generic PerVertexKHR support in an isolated MoltenVK/SPIRV-Cross build, with the public extension still closed and a restricted experimental contract. The Kyty prototype is disabled in that integration. This PR is retained as a draft for its implementation and regression evidence; it is not currently proposed for merging. The evidence below applies to the historical prototype and does not establish complete Vulkan support or qualify the new integration.


The opt-in PerVertex path lowers vertex/fragment shaders in native C++, unpacks and captures vertices on the GPU, and replays per-corner values. Transformed SPIR-V and Vulkan driver pipelines are cached persistently. Rebuilt entry-point interfaces preserve descriptor arrays, OpArrayLength, push constants, and private globals when moving to SPIR-V 1.5.

This update handles two input layouts encountered during startup of the game: more than eight attributes, and an unsigned integer attribute previously receiving a float OpStore. The unpack descriptor now fits twelve attributes in the same 128-byte push-constant block. Signed/unsigned 8/16/32-bit components retain their bits, integer defaults and sign extension; capture stores use the original scalar/vector type. The observed failing format was k16_16_16_16UInt.

Scope

  • Disabled by default; enable with KYTY_PER_VERTEX_PROTOTYPE=1.
  • GPU vertex/index unpacking, dynamic capture/replay layouts, descriptor/push-constant integration, and checksummed persistent caches with corruption recovery.
  • Restricted draw contract: triangle lists, one vertex buffer, up to twelve attributes. Capture currently expects contiguous emitted attribute inputs matching the buffer layout; sparse/pruned inputs remain outside the validated contract. Float32, Float16x4, UNORM, SNORM16x4 and supported integer formats are checked explicitly.
  • No Python subprocess or CPU vertex readback in the render path.

Validation

The isolated branch includes upstream main at 8b095ca. On macOS x86_64/Rosetta:

  • kyty_emulator, shader_cfg_tests, per_vertex_transform_tests, and per_vertex_gpu_execution_tests build.
  • per_vertex_transform_tests: exit 0.
  • shader_cfg_tests --per-vertex: exit 0, including CPU integer decoding and defaults.
  • per_vertex_gpu_execution_tests: exit 0 on Apple M4 Pro with the mesh-capable MoltenVK build. Covers ten/twelve attributes, signed/unsigned widths 1–4, 8/16/32-bit components, out-of-bounds defaults, typed capture SPIR-V, full synthetic capture/replay, and cache checks.
  • The full shader_cfg_tests suite stops earlier at the existing wide-buffer SPIR-V size budget: 923 words / 233 instructions versus limits of 807 / 211. A full-suite pass on the updated isolated branch is not claimed.
  • Repository formatting hooks pass. Cross-platform CI results are tracked on this PR.

Integration evidence and limits

An integration checkout containing other pending fixes passes the intro and title screen, accepts input, and displays the save-slot selection screen. The previously failing integer-input shader now validates and submits draws. After selecting New Game, execution stops at a separate image-view minimum-LOD requirement unsupported by the current MoltenVK build. Two save-card models also show black horizontal stripes; visual correctness and playability are not confirmed.

These integration observations do not establish that this PR alone boots the game. Related integration fixes include #633, #640, #643, #685, #721, #727, #735, #741, and #761. This PR does not add a minimum-LOD workaround or include local storage-backing diagnostics.

**@⁠carbonimax** on GitHub · 2026-09-19 10:28 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/715) `carbonimax:codex/native-pervertex-cache` → `main` · +6233 −1397 · 60 files · 22 commits · closed without merging ## Current status — draft (2026-10-01) This is the historical opt-in Kyty-side prototype. The current integration work uses generic PerVertexKHR support in an isolated MoltenVK/SPIRV-Cross build, with the public extension still closed and a restricted experimental contract. The Kyty prototype is disabled in that integration. This PR is retained as a draft for its implementation and regression evidence; it is not currently proposed for merging. The evidence below applies to the historical prototype and does not establish complete Vulkan support or qualify the new integration. --- The opt-in PerVertex path lowers vertex/fragment shaders in native C++, unpacks and captures vertices on the GPU, and replays per-corner values. Transformed SPIR-V and Vulkan driver pipelines are cached persistently. Rebuilt entry-point interfaces preserve descriptor arrays, `OpArrayLength`, push constants, and private globals when moving to SPIR-V 1.5. This update handles two input layouts encountered during startup of the game: more than eight attributes, and an unsigned integer attribute previously receiving a float `OpStore`. The unpack descriptor now fits twelve attributes in the same 128-byte push-constant block. Signed/unsigned 8/16/32-bit components retain their bits, integer defaults and sign extension; capture stores use the original scalar/vector type. The observed failing format was `k16_16_16_16UInt`. ### Scope - Disabled by default; enable with `KYTY_PER_VERTEX_PROTOTYPE=1`. - GPU vertex/index unpacking, dynamic capture/replay layouts, descriptor/push-constant integration, and checksummed persistent caches with corruption recovery. - Restricted draw contract: triangle lists, one vertex buffer, up to twelve attributes. Capture currently expects contiguous emitted attribute inputs matching the buffer layout; sparse/pruned inputs remain outside the validated contract. Float32, Float16x4, UNORM, SNORM16x4 and supported integer formats are checked explicitly. - No Python subprocess or CPU vertex readback in the render path. ### Validation The isolated branch includes upstream `main` at `8b095ca`. On macOS x86_64/Rosetta: - `kyty_emulator`, `shader_cfg_tests`, `per_vertex_transform_tests`, and `per_vertex_gpu_execution_tests` build. - `per_vertex_transform_tests`: exit 0. - `shader_cfg_tests --per-vertex`: exit 0, including CPU integer decoding and defaults. - `per_vertex_gpu_execution_tests`: exit 0 on Apple M4 Pro with the mesh-capable MoltenVK build. Covers ten/twelve attributes, signed/unsigned widths 1–4, 8/16/32-bit components, out-of-bounds defaults, typed capture SPIR-V, full synthetic capture/replay, and cache checks. - The full `shader_cfg_tests` suite stops earlier at the existing `wide-buffer` SPIR-V size budget: 923 words / 233 instructions versus limits of 807 / 211. A full-suite pass on the updated isolated branch is **not** claimed. - Repository formatting hooks pass. Cross-platform CI results are tracked on this PR. ### Integration evidence and limits An integration checkout containing other pending fixes passes the intro and title screen, accepts input, and displays the save-slot selection screen. The previously failing integer-input shader now validates and submits draws. After selecting New Game, execution stops at a separate image-view minimum-LOD requirement unsupported by the current MoltenVK build. Two save-card models also show black horizontal stripes; visual correctness and playability are not confirmed. These integration observations do not establish that this PR alone boots the game. Related integration fixes include #633, #640, #643, #685, #721, #727, #735, #741, and #761. This PR does not add a minimum-LOD workaround or include local storage-backing diagnostics.
Add opt-in C++ capture/replay transformations and GPU attribute unpacking
with dynamic layouts and bounded vertex/index reads. Wire the native
pipelines into draw submission without Python or CPU vertex readback.

Persist transformed bytecode with checksummed layouts and source signatures,
and keep the Vulkan driver cache usable in development builds. Include GPU
and cache corruption tests, plus test compatibility fixes after the main merge.

Full working-tree builds, per_vertex_gpu_execution_tests on Apple Silicon,
and shader_cfg_tests passed. Staged translation units also pass isolated
compiler checks. The path remains experimental and format-limited.
Rebuild the capture and fragment entry-point interfaces after lowering:
SPIR-V 1.5 requires globals that the original 1.3 interfaces did not list.
Their omission produced undeclared buffers and buffersBufferSize in MSL.
Validate assembled modules before caching them and exercise descriptor
arrays, buffer lengths and push constants in the GPU regression test.

The test fails before the fix and passes bit-for-bit on Apple Silicon.
The previously failing pair compiles in the game; the run reaches 802
recorded PerVertex submissions before a separate unsupported attribute
format. Visual correctness and playability remain unconfirmed.
Use std::regex_constants::multiline throughout the PerVertex transforms. MSVC STL does not expose std::regex::multiline, which failed the Windows CI build. The regex behavior is unchanged.

Validation: macOS emulator/test builds, shader_cfg_tests and the PerVertex GPU harness pass. Windows validation is delegated to CI.
# Conflicts:
#	src/libs/audio.cpp
# Conflicts:
#	src/graphics/host_gpu/renderer/pipeline/descriptors.cpp
#	src/graphics/host_gpu/renderer/render.h
#	src/graphics/host_gpu/renderer/renderCompute.cpp
#	src/graphics/host_gpu/renderer/renderDraw.cpp
#	src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp
#	src/graphics/shader/recompiler/ir/ShaderIR.h
#	src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp
#	src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:30:28 +00:00
github-bot closed this pull request 2026-11-26 09:30:28 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-19 20:41 UTC · original · edited 2026-10-01 16:05 UTC

Review Change StackReview Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds a GPU-native per-vertex rendering prototype. The change transforms vertex and fragment shaders, embeds unpack and replay SPIR-V, executes supported draws through compute and graphics pipelines, and adds disk and driver-cache handling. Pipeline descriptors and draw routing support prototype programs. CPU, GPU, cache, shader-detection, CMake, and CI test coverage is added.

Suggested reviewers: nmzik

Priority: ➖ Normal

Change: Feature

Merge Risk: 🟡 Moderate · up to 54855

The optional rendering path still fails on reachable shaders and draw configurations. These issues should be fixed or explicitly accepted before merge.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 6.98% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 86 functions across 15 files. (4 skipped: … Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly identifies the main changes: an experimental native GPU PerVertex replay path and shader-cache support.
Description check ✅ Passed The description directly explains the opt-in PerVertex prototype, shader caches, supported scope, tests, and known limitations.
Full details: Docstring Coverage

Explanation

Docstring coverage is 6.98% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 86 functions across 15 files. (4 skipped: 3 unsupported, 1 too large.)


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-19 20:41 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/715#issuecomment-5745148232) · edited 2026-10-01 16:05 UTC <!-- This is an auto-generated comment: summarize by coderabbit.ai --> <!-- review_stack_entry_start --> <a href="https://app.coderabbit.ai/change-stack/KytyPS5/KytyPS5/pull/715#gh-light-mode-only"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg" alt="Review Change Stack" width="202" height="32"></a><a href="https://app.coderabbit.ai/change-stack/KytyPS5/KytyPS5/pull/715#gh-dark-mode-only"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui-dark.svg" alt="Review Change Stack" width="202" height="32"></a> <!-- review_stack_entry_end --> <!-- This is an auto-generated comment: review paused by coderabbit.ai --> > [!NOTE] > ## Reviews paused > > It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the `reviews.auto_review.auto_pause_after_reviewed_commits` setting. > > Use the following commands to manage reviews: > - `@coderabbitai resume` to resume automatic reviews. > - `@coderabbitai review` to trigger a single review. > > Use the checkboxes below for quick actions: > - [ ] <!-- {"checkboxId":"7f6cc2e2-2e4e-497a-8c31-c9e4573e93d1"} --> ▶️ Resume reviews > - [ ] <!-- {"checkboxId":"e9bb8d72-00e8-4f67-9cb2-caf3b22574fe"} --> 🔍 Trigger review <!-- end of auto-generated comment: review paused by coderabbit.ai --> <!-- walkthrough_start --> <details> <summary>📝 Walkthrough</summary> ## Walkthrough Adds a GPU-native per-vertex rendering prototype. The change transforms vertex and fragment shaders, embeds unpack and replay SPIR-V, executes supported draws through compute and graphics pipelines, and adds disk and driver-cache handling. Pipeline descriptors and draw routing support prototype programs. CPU, GPU, cache, shader-detection, CMake, and CI test coverage is added. **Suggested reviewers:** `nmzik` </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ➖ Normal <!-- change_assessment_commit:"548553ae5cb3ed2efeefcccae88d7670860c95b5" --> **Change:** Feature <!-- change_assessment_end --> <!-- final_review_risk_start --> **Merge Risk:** _🟡 Moderate_ · up to `54855` <!-- final_review_risk_coverage:{"sourceCommitId":"548553ae5cb3ed2efeefcccae88d7670860c95b5","coveredCommitId":"548553ae5cb3ed2efeefcccae88d7670860c95b5","kind":"reviewed"} --> The optional rendering path still fails on reachable shaders and draw configurations. These issues should be fixed or explicitly accepted before merge. <!-- final_review_risk_end --> <!-- pre_merge_checks_walkthrough_start --> <details> <summary>🚥 Pre-merge checks | ✅ 4 | ❌ 1</summary> ### ❌ Failed checks (1 warning) | Check name | Status | Explanation | Resolution | | :----------------: | :--------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------- | | Docstring Coverage | ⚠️ Warning | Docstring coverage is 6.98% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 86 functions across 15 files. (4 skipped: … | Write docstrings for the functions missing them to satisfy the coverage threshold. | <details> <summary>✅ Passed checks (4 passed)</summary> | Check name | Status | Explanation | | :------------------------: | :------- | :------------------------------------------------------------------------------------------------------------------------------ | | Linked Issues check | ✅ Passed | Check skipped because no linked issues were found for this pull request. | | Out of Scope Changes check | ✅ Passed | Check skipped because no linked issues were found for this pull request. | | Title check | ✅ Passed | The title clearly identifies the main changes: an experimental native GPU PerVertex replay path and shader-cache support. | | Description check | ✅ Passed | The description directly explains the opt-in PerVertex prototype, shader caches, supported scope, tests, and known limitations. | </details> <details> <summary>Full details: Docstring Coverage</summary> **Explanation** Docstring coverage is 6.98% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 86 functions across 15 files. (4 skipped: 3 unsupported, 1 too large.) </details> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- tips_start --> --- Thanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=KytyPS5/KytyPS5&utm_content=715)! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. <details> <summary>❤️ Share</summary> - [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai) - [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai) - [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai) - [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code) </details> <sub>Comment `@coderabbitai help` to get the list of available commands.</sub> <!-- tips_end -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-19 20:41 UTC · original
On CMakeLists.txt line 390 (outdated):

@@ -375,6 +375,20 @@ endfunction()
 
 add_kyty_full_emulator_test(shader_cfg_tests "${KYTY_TESTS_DIR}/shaderCfgTests.cpp")
 
+add_executable(per_vertex_transform_tests EXCLUDE_FROM_ALL
+	"${KYTY_TESTS_DIR}/PerVertexTransformTests.cpp"
+	"${KYTY_SOURCE_DIR}/graphics/host_gpu/renderer/perVertexTransform.cpp"
+)
+target_include_directories(per_vertex_transform_tests PRIVATE ${inc_headers})
+target_link_libraries(per_vertex_transform_tests common fmt::fmt xxhash)
+
+add_executable(per_vertex_gpu_execution_tests EXCLUDE_FROM_ALL
+	"${KYTY_TESTS_DIR}/PerVertexGpuExecutionTests.cpp"
+	"${KYTY_SOURCE_DIR}/graphics/host_gpu/renderer/perVertexTransform.cpp"
+)
+target_include_directories(per_vertex_gpu_execution_tests PRIVATE ${inc_headers})
+target_link_libraries(per_vertex_gpu_execution_tests Vulkan::Headers spirv-tools common fmt::fmt xxhash)

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '1,180p' tests/PerVertexGpuExecutionTests.cpp
sed -n '365,400p' CMakeLists.txt
rg -n 'EXCLUDE_FROM_ALL|if\(APPLE\)|dlfcn|MoltenVK' CMakeLists.txt tests .github/workflows/build.yml

Repository: KytyPS5/KytyPS5

Length of output: 13292


🏁 Script executed:

#!/bin/bash
set -u
printf '%s\n' '--- platform and project guidance ---'
rg -n -i 'windows|linux|macos|mac os|apple|platform|supported|cmake|build' README.md CONTRIBUTING.md docs .github 2>/dev/null | head -220
printf '%s\n' '--- CMake platform and test conventions ---'
sed -n '1,135p' CMakeLists.txt
sed -n '330,510p' CMakeLists.txt
sed -n '600,695p' CMakeLists.txt
printf '%s\n' '--- workflow platform/build matrix and target use ---'
rg -n -C 5 'runs-on|cmake|build|target|ctest|per_vertex|EXCLUDE_FROM_ALL' .github/workflows/build.yml
printf '%s\n' '--- test registration ---'
sed -n '510,565p' CMakeLists.txt

Repository: KytyPS5/KytyPS5

Length of output: 48655


🏁 Script executed:

#!/bin/bash
set -u
printf '%s\n' '--- documented regression build scope ---'
sed -n '268,284p' README.md
printf '%s\n' '--- CMake test target and dependencies ---'
sed -n '500,555p' CMakeLists.txt
printf '%s\n' '--- all platform-conditional executable/test definitions ---'
rg -n -C 4 'if\((APPLE|WIN32|LINUX)|add_executable\(' CMakeLists.txt | sed -n '1,260p'

Repository: KytyPS5/KytyPS5

Length of output: 13028


🏁 Script executed:

#!/bin/bash
set -u
printf '%s\n' '--- kyty_tests definitions and dependencies ---'
rg -n -C 8 'kyty_tests|add_dependencies\(' CMakeLists.txt src tests
printf '%s\n' '--- common target and dynamic-loader linkage ---'
rg -n -C 8 'add_library\(common|target_link_libraries\(common|CMAKE_DL_LIBS|dlopen|dlsym' CMakeLists.txt src tests

Repository: KytyPS5/KytyPS5

Length of output: 13849


Guard per_vertex_gpu_execution_tests on Apple platforms.

EXCLUDE_FROM_ALL does not make an explicitly requested target portable. The supported Windows toolchain cannot compile PerVertexGpuExecutionTests.cpp because it includes POSIX-only <dlfcn.h>. Define this Apple/MoltenVK test only when APPLE is true.

♻️ Proposed guard
-add_executable(per_vertex_gpu_execution_tests EXCLUDE_FROM_ALL
-	"${KYTY_TESTS_DIR}/PerVertexGpuExecutionTests.cpp"
-	"${KYTY_SOURCE_DIR}/graphics/host_gpu/renderer/perVertexTransform.cpp"
-)
-target_include_directories(per_vertex_gpu_execution_tests PRIVATE ${inc_headers})
-target_link_libraries(per_vertex_gpu_execution_tests Vulkan::Headers spirv-tools common fmt::fmt xxhash)
+if(APPLE)
+	add_executable(per_vertex_gpu_execution_tests EXCLUDE_FROM_ALL
+		"${KYTY_TESTS_DIR}/PerVertexGpuExecutionTests.cpp"
+		"${KYTY_SOURCE_DIR}/graphics/host_gpu/renderer/perVertexTransform.cpp"
+	)
+	target_include_directories(per_vertex_gpu_execution_tests PRIVATE ${inc_headers})
+	target_link_libraries(per_vertex_gpu_execution_tests Vulkan::Headers spirv-tools common fmt::fmt xxhash)
+endif()
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

if(APPLE)
	add_executable(per_vertex_gpu_execution_tests EXCLUDE_FROM_ALL
		"${KYTY_TESTS_DIR}/PerVertexGpuExecutionTests.cpp"
		"${KYTY_SOURCE_DIR}/graphics/host_gpu/renderer/perVertexTransform.cpp"
	)
	target_include_directories(per_vertex_gpu_execution_tests PRIVATE ${inc_headers})
	target_link_libraries(per_vertex_gpu_execution_tests Vulkan::Headers spirv-tools common fmt::fmt xxhash)
endif()
**@⁠coderabbitai[bot]** on GitHub · 2026-09-19 20:41 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/715#discussion_r4054644809) On `CMakeLists.txt` line 390 (outdated): ```diff @@ -375,6 +375,20 @@ endfunction() add_kyty_full_emulator_test(shader_cfg_tests "${KYTY_TESTS_DIR}/shaderCfgTests.cpp") +add_executable(per_vertex_transform_tests EXCLUDE_FROM_ALL + "${KYTY_TESTS_DIR}/PerVertexTransformTests.cpp" + "${KYTY_SOURCE_DIR}/graphics/host_gpu/renderer/perVertexTransform.cpp" +) +target_include_directories(per_vertex_transform_tests PRIVATE ${inc_headers}) +target_link_libraries(per_vertex_transform_tests common fmt::fmt xxhash) + +add_executable(per_vertex_gpu_execution_tests EXCLUDE_FROM_ALL + "${KYTY_TESTS_DIR}/PerVertexGpuExecutionTests.cpp" + "${KYTY_SOURCE_DIR}/graphics/host_gpu/renderer/perVertexTransform.cpp" +) +target_include_directories(per_vertex_gpu_execution_tests PRIVATE ${inc_headers}) +target_link_libraries(per_vertex_gpu_execution_tests Vulkan::Headers spirv-tools common fmt::fmt xxhash) ``` _🎯 Functional Correctness_ | _🟡 Minor_ | _⚡ Quick win_ <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash sed -n '1,180p' tests/PerVertexGpuExecutionTests.cpp sed -n '365,400p' CMakeLists.txt rg -n 'EXCLUDE_FROM_ALL|if\(APPLE\)|dlfcn|MoltenVK' CMakeLists.txt tests .github/workflows/build.yml ``` Repository: KytyPS5/KytyPS5 Length of output: 13292 --- 🏁 Script executed: ```bash #!/bin/bash set -u printf '%s\n' '--- platform and project guidance ---' rg -n -i 'windows|linux|macos|mac os|apple|platform|supported|cmake|build' README.md CONTRIBUTING.md docs .github 2>/dev/null | head -220 printf '%s\n' '--- CMake platform and test conventions ---' sed -n '1,135p' CMakeLists.txt sed -n '330,510p' CMakeLists.txt sed -n '600,695p' CMakeLists.txt printf '%s\n' '--- workflow platform/build matrix and target use ---' rg -n -C 5 'runs-on|cmake|build|target|ctest|per_vertex|EXCLUDE_FROM_ALL' .github/workflows/build.yml printf '%s\n' '--- test registration ---' sed -n '510,565p' CMakeLists.txt ``` Repository: KytyPS5/KytyPS5 Length of output: 48655 --- 🏁 Script executed: ```bash #!/bin/bash set -u printf '%s\n' '--- documented regression build scope ---' sed -n '268,284p' README.md printf '%s\n' '--- CMake test target and dependencies ---' sed -n '500,555p' CMakeLists.txt printf '%s\n' '--- all platform-conditional executable/test definitions ---' rg -n -C 4 'if\((APPLE|WIN32|LINUX)|add_executable\(' CMakeLists.txt | sed -n '1,260p' ``` Repository: KytyPS5/KytyPS5 Length of output: 13028 --- 🏁 Script executed: ```bash #!/bin/bash set -u printf '%s\n' '--- kyty_tests definitions and dependencies ---' rg -n -C 8 'kyty_tests|add_dependencies\(' CMakeLists.txt src tests printf '%s\n' '--- common target and dynamic-loader linkage ---' rg -n -C 8 'add_library\(common|target_link_libraries\(common|CMAKE_DL_LIBS|dlopen|dlsym' CMakeLists.txt src tests ``` Repository: KytyPS5/KytyPS5 Length of output: 13849 --- </details> **Guard `per_vertex_gpu_execution_tests` on Apple platforms.** `EXCLUDE_FROM_ALL` does not make an explicitly requested target portable. The supported Windows toolchain cannot compile `PerVertexGpuExecutionTests.cpp` because it includes POSIX-only `<dlfcn.h>`. Define this Apple/MoltenVK test only when `APPLE` is true. <details> <summary>♻️ Proposed guard</summary> ```diff -add_executable(per_vertex_gpu_execution_tests EXCLUDE_FROM_ALL - "${KYTY_TESTS_DIR}/PerVertexGpuExecutionTests.cpp" - "${KYTY_SOURCE_DIR}/graphics/host_gpu/renderer/perVertexTransform.cpp" -) -target_include_directories(per_vertex_gpu_execution_tests PRIVATE ${inc_headers}) -target_link_libraries(per_vertex_gpu_execution_tests Vulkan::Headers spirv-tools common fmt::fmt xxhash) +if(APPLE) + add_executable(per_vertex_gpu_execution_tests EXCLUDE_FROM_ALL + "${KYTY_TESTS_DIR}/PerVertexGpuExecutionTests.cpp" + "${KYTY_SOURCE_DIR}/graphics/host_gpu/renderer/perVertexTransform.cpp" + ) + target_include_directories(per_vertex_gpu_execution_tests PRIVATE ${inc_headers}) + target_link_libraries(per_vertex_gpu_execution_tests Vulkan::Headers spirv-tools common fmt::fmt xxhash) +endif() ``` </details> <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion if(APPLE) add_executable(per_vertex_gpu_execution_tests EXCLUDE_FROM_ALL "${KYTY_TESTS_DIR}/PerVertexGpuExecutionTests.cpp" "${KYTY_SOURCE_DIR}/graphics/host_gpu/renderer/perVertexTransform.cpp" ) target_include_directories(per_vertex_gpu_execution_tests PRIVATE ${inc_headers}) target_link_libraries(per_vertex_gpu_execution_tests Vulkan::Headers spirv-tools common fmt::fmt xxhash) endif() ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:quokka --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:6e2e3a1b48d574ce4c5710f7 --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -0,0 +61,4 @@
std::map<uint64_t, Original> originals;
std::map<std::pair<uint64_t, uint64_t>, PerVertexPrototypePrograms> variants;
PerVertexUnpackPipeline s_unpack_pipeline {};
bool s_unpack_initialized = false;
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-19 20:41 UTC · original

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '1,165p' src/graphics/host_gpu/renderer/perVertexPrototype.cpp
sed -n '235,315p' src/graphics/host_gpu/renderer/perVertexPrototype.cpp
rg -n 'GraphicContext|PipelineCache::~|destroyDevice|CreateDevice|DeleteDevice|RememberPerVertexPrototypeShader|GetPerVertexPrototypePrograms' src/graphics/host_gpu

Repository: KytyPS5/KytyPS5

Length of output: 21204


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- perVertexPrototype.cpp: 90-280 ---'
sed -n '90,280p' src/graphics/host_gpu/renderer/perVertexPrototype.cpp
printf '%s\n' '--- pipeline cache lifecycle ---'
sed -n '235,430p' src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp
printf '%s\n' '--- GraphicContext declarations and lifecycle references ---'
sed -n '1,180p' src/graphics/host_gpu/graphicContext.h
rg -n -C 5 'GraphicContext::|CreateDevice|destroyDevice|DeviceWaitIdle|waitIdle|PipelineCache::~|RenderContext::|std::thread|jthread|CreateThread|Thread|worker|Submit' src/graphics/host_gpu src | head -n 500
printf '%s\n' '--- per-vertex callers ---'
sed -n '1040,1100p' src/graphics/host_gpu/renderer/renderDraw.cpp
cat -n src/graphics/host_gpu/renderer/perVertexPrototypeDraw.inc

Repository: KytyPS5/KytyPS5

Length of output: 50371


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- per-vertex types ---'
cat -n src/graphics/host_gpu/renderer/perVertexPrototype.h
printf '%s\n' '--- exact per-vertex call sites ---'
rg -n -C 8 'GetPerVertexUnpackPipeline|GetPerVertexPrototypePrograms|RememberPerVertexPrototypeShader' src
printf '%s\n' '--- device API calls and GraphicContext construction ---'
rg -n -C 5 'createDevice|destroy\(\)|destroyDevice|vk::Device|GraphicContext[ (]' src/graphics src/emulator src 2>/dev/null | grep -E 'createDevice|destroyDevice|destroy\(\)|GraphicContext|vk::Device' | head -n 400
printf '%s\n' '--- renderer member order and teardown ---'
cat -n src/graphics/host_gpu/renderer/render.h | sed -n '100,180p'
cat -n src/graphics/host_gpu/renderer/renderContext.h | sed -n '1,130p'
cat -n src/graphics/host_gpu/renderer/renderContext.cpp | sed -n '1,55p'
printf '%s\n' '--- thread assertions and shader/pipeline entrypoints ---'
rg -n -C 6 'IsMainThread|CompileShader|GetGraphicsPrograms|CreatePipeline|GetPerVertex' src/graphics/host_gpu/renderer src/graphics/host_gpu | head -n 500

Repository: KytyPS5/KytyPS5

Length of output: 50371


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- per-vertex declarations ---'
cat -n src/graphics/host_gpu/renderer/perVertexPrototype.h
printf '%s\n' '--- per-vertex callers ---'
rg -n -C 6 'GetPerVertexUnpackPipeline|GetPerVertexPrototypePrograms|RememberPerVertexPrototypeShader' src
printf '%s\n' '--- device creation/destruction and context construction ---'
rg -n -C 4 'createDevice|destroyDevice|destroy\(\)|GraphicContext[[:space:]]*[({]|make_unique<.*GraphicContext|new GraphicContext' src/graphics src 2>/dev/null | head -n 500
printf '%s\n' '--- render context ownership and teardown ---'
cat -n src/graphics/host_gpu/renderer/render.h | sed -n '105,180p'
cat -n src/graphics/host_gpu/renderer/renderContext.h | sed -n '1,125p'
cat -n src/graphics/host_gpu/renderer/renderContext.cpp | sed -n '1,50p'

Repository: KytyPS5/KytyPS5

Length of output: 28760


Bind the per-vertex caches to the GraphicContext lifetime. When KYTY_PER_VERTEX_PROTOTYPE is enabled, a qualifying draw populates the process-global variants and s_unpack_pipeline caches. These values contain Vulkan handles, but RenderContext and PipelineCache teardown does not destroy them. The handles therefore remain allocated after context teardown and can leak until device or process teardown. Add a lifecycle reset that destroys all cached handles with the owning GraphicContext::device, clears both maps, and resets s_unpack_initialized before device teardown. The cache keys also contain no device identity, so they must not be reused across devices.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-19 20:41 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/715#discussion_r4054644813) _🩺 Stability & Availability_ | _🟡 Minor_ | _⚡ Quick win_ <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash sed -n '1,165p' src/graphics/host_gpu/renderer/perVertexPrototype.cpp sed -n '235,315p' src/graphics/host_gpu/renderer/perVertexPrototype.cpp rg -n 'GraphicContext|PipelineCache::~|destroyDevice|CreateDevice|DeleteDevice|RememberPerVertexPrototypeShader|GetPerVertexPrototypePrograms' src/graphics/host_gpu ``` Repository: KytyPS5/KytyPS5 Length of output: 21204 --- 🏁 Script executed: ```bash #!/bin/bash set -e printf '%s\n' '--- perVertexPrototype.cpp: 90-280 ---' sed -n '90,280p' src/graphics/host_gpu/renderer/perVertexPrototype.cpp printf '%s\n' '--- pipeline cache lifecycle ---' sed -n '235,430p' src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp printf '%s\n' '--- GraphicContext declarations and lifecycle references ---' sed -n '1,180p' src/graphics/host_gpu/graphicContext.h rg -n -C 5 'GraphicContext::|CreateDevice|destroyDevice|DeviceWaitIdle|waitIdle|PipelineCache::~|RenderContext::|std::thread|jthread|CreateThread|Thread|worker|Submit' src/graphics/host_gpu src | head -n 500 printf '%s\n' '--- per-vertex callers ---' sed -n '1040,1100p' src/graphics/host_gpu/renderer/renderDraw.cpp cat -n src/graphics/host_gpu/renderer/perVertexPrototypeDraw.inc ``` Repository: KytyPS5/KytyPS5 Length of output: 50371 --- 🏁 Script executed: ```bash #!/bin/bash set -e printf '%s\n' '--- per-vertex types ---' cat -n src/graphics/host_gpu/renderer/perVertexPrototype.h printf '%s\n' '--- exact per-vertex call sites ---' rg -n -C 8 'GetPerVertexUnpackPipeline|GetPerVertexPrototypePrograms|RememberPerVertexPrototypeShader' src printf '%s\n' '--- device API calls and GraphicContext construction ---' rg -n -C 5 'createDevice|destroy\(\)|destroyDevice|vk::Device|GraphicContext[ (]' src/graphics src/emulator src 2>/dev/null | grep -E 'createDevice|destroyDevice|destroy\(\)|GraphicContext|vk::Device' | head -n 400 printf '%s\n' '--- renderer member order and teardown ---' cat -n src/graphics/host_gpu/renderer/render.h | sed -n '100,180p' cat -n src/graphics/host_gpu/renderer/renderContext.h | sed -n '1,130p' cat -n src/graphics/host_gpu/renderer/renderContext.cpp | sed -n '1,55p' printf '%s\n' '--- thread assertions and shader/pipeline entrypoints ---' rg -n -C 6 'IsMainThread|CompileShader|GetGraphicsPrograms|CreatePipeline|GetPerVertex' src/graphics/host_gpu/renderer src/graphics/host_gpu | head -n 500 ``` Repository: KytyPS5/KytyPS5 Length of output: 50371 --- 🏁 Script executed: ```bash #!/bin/bash set -e printf '%s\n' '--- per-vertex declarations ---' cat -n src/graphics/host_gpu/renderer/perVertexPrototype.h printf '%s\n' '--- per-vertex callers ---' rg -n -C 6 'GetPerVertexUnpackPipeline|GetPerVertexPrototypePrograms|RememberPerVertexPrototypeShader' src printf '%s\n' '--- device creation/destruction and context construction ---' rg -n -C 4 'createDevice|destroyDevice|destroy\(\)|GraphicContext[[:space:]]*[({]|make_unique<.*GraphicContext|new GraphicContext' src/graphics src 2>/dev/null | head -n 500 printf '%s\n' '--- render context ownership and teardown ---' cat -n src/graphics/host_gpu/renderer/render.h | sed -n '105,180p' cat -n src/graphics/host_gpu/renderer/renderContext.h | sed -n '1,125p' cat -n src/graphics/host_gpu/renderer/renderContext.cpp | sed -n '1,50p' ``` Repository: KytyPS5/KytyPS5 Length of output: 28760 --- </details> **Bind the per-vertex caches to the `GraphicContext` lifetime.** When `KYTY_PER_VERTEX_PROTOTYPE` is enabled, a qualifying draw populates the process-global `variants` and `s_unpack_pipeline` caches. These values contain Vulkan handles, but `RenderContext` and `PipelineCache` teardown does not destroy them. The handles therefore remain allocated after context teardown and can leak until device or process teardown. Add a lifecycle reset that destroys all cached handles with the owning `GraphicContext::device`, clears both maps, and resets `s_unpack_initialized` before device teardown. The cache keys also contain no device identity, so they must not be reused across devices. <!-- fingerprinting:phantom:medusa:quokka --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:00092e6995ea4e96228a3507 --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -0,0 +300,4 @@
static_cast<unsigned long long>(key.first),
static_cast<unsigned long long>(key.second));
return nullptr;
}
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-19 20:41 UTC · original

🚀 Performance & Scalability | 🟠 Major | ⚡ Quick win

Cache the rejection so an unsupported pair is analysed only once.

When DerivePerVertexLayout fails, the function returns nullptr without recording anything in variants. ExecutePreparedDraw calls GetPerVertexPrototypePrograms on every draw whose first vertex stage is a logical vertex stage. Each of those calls re-runs two spvtools::SpirvTools::Disassemble passes over the full vertex and pixel modules, then the regex scans in DerivePerVertexLayout.

For a title whose per-vertex pixel shader is not supported, this repeats per draw call, per frame.

Record the rejection in a negative-result set keyed by the same {vs.id, ps.id} pair and return nullptr immediately on later calls.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-19 20:41 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/715#discussion_r4054644820) _🚀 Performance & Scalability_ | _🟠 Major_ | _⚡ Quick win_ **Cache the rejection so an unsupported pair is analysed only once.** When `DerivePerVertexLayout` fails, the function returns `nullptr` without recording anything in `variants`. `ExecutePreparedDraw` calls `GetPerVertexPrototypePrograms` on every draw whose first vertex stage is a logical vertex stage. Each of those calls re-runs two `spvtools::SpirvTools::Disassemble` passes over the full vertex and pixel modules, then the regex scans in `DerivePerVertexLayout`. For a title whose per-vertex pixel shader is not supported, this repeats per draw call, per frame. Record the rejection in a negative-result set keyed by the same `{vs.id, ps.id}` pair and return `nullptr` immediately on later calls. <!-- fingerprinting:phantom:medusa:komodo --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:c0b90dbf1562986fc2b823cd --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -0,0 +44,4 @@
// Obtain vertex buffer from GPU cache without host readback
const uint64_t vtx_total_bytes = static_cast<uint64_t>(input.stride) * input.num_records;
auto [vtx_buf_ptr, vtx_offset] = cache.ObtainBuffer(input.addr, vtx_total_bytes, false);
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-19 20:41 UTC · original

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Clamp the vertex-buffer range before obtaining the buffer.

Line 44 computes vtx_total_bytes directly from the guest descriptor fields input.stride and input.num_records, then passes it to cache.ObtainBuffer. A guest descriptor can declare a record count far larger than the mapped region.

The standard vertex path guards this. AcquireVertexBuffers in renderDraw.cpp passes every range through Libs::LibKernel::Memory::ClampRangeSize before calling ObtainBuffer. This prototype path skips that step, so a malformed or simply large descriptor requests an oversized host allocation.

Apply the same clamp here.

🛡️ Proposed fix
-	const uint64_t vtx_total_bytes    = static_cast<uint64_t>(input.stride) * input.num_records;
+	const uint64_t vtx_requested_bytes = static_cast<uint64_t>(input.stride) * input.num_records;
+	const uint64_t vtx_total_bytes =
+	    Libs::LibKernel::Memory::ClampRangeSize(input.addr, vtx_requested_bytes);
 	auto [vtx_buf_ptr, vtx_offset]    = cache.ObtainBuffer(input.addr, vtx_total_bytes, false);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

	const uint64_t vtx_requested_bytes = static_cast<uint64_t>(input.stride) * input.num_records;
	const uint64_t vtx_total_bytes =
	    Libs::LibKernel::Memory::ClampRangeSize(input.addr, vtx_requested_bytes);
	auto [vtx_buf_ptr, vtx_offset]    = cache.ObtainBuffer(input.addr, vtx_total_bytes, false);
**@⁠coderabbitai[bot]** on GitHub · 2026-09-19 20:41 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/715#discussion_r4054644821) _🩺 Stability & Availability_ | _🟠 Major_ | _⚡ Quick win_ **Clamp the vertex-buffer range before obtaining the buffer.** Line 44 computes `vtx_total_bytes` directly from the guest descriptor fields `input.stride` and `input.num_records`, then passes it to `cache.ObtainBuffer`. A guest descriptor can declare a record count far larger than the mapped region. The standard vertex path guards this. `AcquireVertexBuffers` in `renderDraw.cpp` passes every range through `Libs::LibKernel::Memory::ClampRangeSize` before calling `ObtainBuffer`. This prototype path skips that step, so a malformed or simply large descriptor requests an oversized host allocation. Apply the same clamp here. <details> <summary>🛡️ Proposed fix</summary> ```diff - const uint64_t vtx_total_bytes = static_cast<uint64_t>(input.stride) * input.num_records; + const uint64_t vtx_requested_bytes = static_cast<uint64_t>(input.stride) * input.num_records; + const uint64_t vtx_total_bytes = + Libs::LibKernel::Memory::ClampRangeSize(input.addr, vtx_requested_bytes); auto [vtx_buf_ptr, vtx_offset] = cache.ObtainBuffer(input.addr, vtx_total_bytes, false); ``` </details> <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion const uint64_t vtx_requested_bytes = static_cast<uint64_t>(input.stride) * input.num_records; const uint64_t vtx_total_bytes = Libs::LibKernel::Memory::ClampRangeSize(input.addr, vtx_requested_bytes); auto [vtx_buf_ptr, vtx_offset] = cache.ObtainBuffer(input.addr, vtx_total_bytes, false); ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:komodo --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:fdbd9593e76142946824a327 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-19 20:41 UTC · original
On src/graphics/host_gpu/renderer/perVertexPrototypeDraw.inc line 239 (outdated):

@@ -0,0 +1,290 @@
+// Live PerVertex execution with GPU compute unpack and native C++ pipeline.
+void RenderExecutor::ExecutePerVertexPrototype(uint64_t submit_id, CommandBuffer& buffer,
+                                               const DrawCallInfo& draw, DrawRenderState& state,
+                                               vk::PrimitiveTopology        topology,
+                                               const DrawEmitInfo&          emit,
+                                               const DrawIndexBufferSource& index_source,
+                                               bool primitive_restart_enable) {
+	const auto& vs       = state.vertex_info[0];
+	const auto* programs = GetPerVertexPrototypePrograms(
+	    m_context.GetGraphics(), state.programs, vs, m_context.GetPipelineCache().DriverCache());
+	EXIT_IF(programs == nullptr || !state.ps_active ||
+	        topology != vk::PrimitiveTopology::eTriangleList || primitive_restart_enable ||
+	        draw.index_count % 3 != 0);
+	EXIT_IF(vs.logical_stage != ShaderType::Vertex || vs.buffers_num != 1 ||
+	        vs.resources_num == 0 || vs.resources_num > 8 || HasShaderBufferWrites(vs.stage));
+	const auto&    input     = vs.buffers[0];
+	const uint32_t num_attrs = vs.resources_num;
+	EXIT_IF(input.stride == 0 || input.fetch_index != 0 ||
+	        input.attr_num != static_cast<int>(num_attrs) || input.addr == 0);
+
+	for (uint32_t i = 0; i < num_attrs; ++i) {
+		EXIT_IF(input.attr_indices[i] != static_cast<int>(i));
+		const auto& descriptor = vs.resources[i];
+		const auto  format     = ShaderRecompiler::Format::GetFormatInfo(descriptor.Format());
+		EXIT_IF(format.byte_size > input.stride ||
+		        input.attr_offsets[i] > input.stride - format.byte_size ||
+		        descriptor.SwizzleEnabled() || descriptor.AddTid());
+		std::array<uint8_t, 16> bytes {};
+		std::array<uint32_t, 4> decoded {};
+		EXIT_IF(!DecodePerVertexPrototypeAttribute(descriptor.Format(), bytes, decoded));
+	}
+
+	const uint64_t count64 = static_cast<uint64_t>(draw.index_count) * draw.instance_count;
+	EXIT_IF(count64 == 0 || count64 > 65535);
+	const auto count     = static_cast<uint32_t>(count64);
+	auto&      graphics  = m_context.GetGraphics();
+	auto&      scheduler = m_context.GetCommandScheduler();
+	auto&      cache     = m_context.GetBufferCache();
+	scheduler.EndRendering();
+
+	const auto alignment = graphics.StorageMinAlignment();
+
+	// Obtain vertex buffer from GPU cache without host readback
+	const uint64_t vtx_total_bytes    = static_cast<uint64_t>(input.stride) * input.num_records;
+	auto [vtx_buf_ptr, vtx_offset]    = cache.ObtainBuffer(input.addr, vtx_total_bytes, false);
+	const uint64_t vtx_aligned_offset = Common::AlignDown(vtx_offset, alignment);
+	const uint32_t vertex_byte_adjust = static_cast<uint32_t>(vtx_offset - vtx_aligned_offset);
+
+	vk::Buffer idx_vk_buf         = nullptr;
+	uint64_t   idx_aligned_offset = 0;
+	uint32_t   index_byte_adjust  = 0;
+	uint64_t   idx_buf_available  = 0;
+	if (draw.IsIndexed()) {
+		EXIT_IF(index_source.guest_element_size != 1 && index_source.guest_element_size != 2 &&
+		        index_source.guest_element_size != 4);
+		const uint64_t idx_total_bytes =
+		    static_cast<uint64_t>(draw.index_count) * index_source.guest_element_size;
+		if (index_source.host_data != nullptr) {
+			auto&      stream  = cache.GetUtilityBuffer(MemoryUsage::Stream);
+			const auto offset  = stream.Copy(index_source.host_data, idx_total_bytes, 16);
+			idx_vk_buf         = stream.Handle();
+			idx_aligned_offset = Common::AlignDown(offset, alignment);
+			index_byte_adjust  = static_cast<uint32_t>(offset - idx_aligned_offset);
+			idx_buf_available =
+			    stream.Size() > idx_aligned_offset ? (stream.Size() - idx_aligned_offset) : 0;
+		} else {
+			auto [idx_buf_ptr, offset] =
+			    cache.ObtainBuffer(index_source.address, idx_total_bytes, false);
+			idx_vk_buf         = idx_buf_ptr->Handle();
+			idx_aligned_offset = Common::AlignDown(offset, alignment);
+			index_byte_adjust  = static_cast<uint32_t>(offset - idx_aligned_offset);
+			idx_buf_available  = idx_buf_ptr->Size() > idx_aligned_offset
+			                         ? (idx_buf_ptr->Size() - idx_aligned_offset)
+			                         : 0;
+		}
+	} else {
+		idx_vk_buf         = vtx_buf_ptr->Handle();
+		idx_aligned_offset = 0;
+		index_byte_adjust  = 0;
+		idx_buf_available  = vtx_buf_ptr->Size();
+	}
+
+	PreparedBindings  vertex_bindings = PrepareBindings(vs.stage);
+	PreparedBindings  pixel_bindings  = PrepareBindings(state.ps_input_info.stage);
+	PreparedBindings* stages[] {&vertex_bindings, &pixel_bindings};
+	PrepareGraphicsBindings(stages, {state.color_info, state.color_count});
+
+	// GPU-side intermediate buffers for unpack and capture
+	auto id_buffer =
+	    std::make_unique<Buffer>(graphics, scheduler, MemoryUsage::Stream, 0, AllFlags, count * 8);
+	auto attribute_buffer = std::make_unique<Buffer>(graphics, scheduler, MemoryUsage::Stream, 0,
+	                                                 AllFlags, count * num_attrs * 16);
+	auto captured = std::make_unique<Buffer>(graphics, scheduler, MemoryUsage::Stream, 0, AllFlags,
+	                                         count64 * programs->layout.record_stride_vec4 * 16);
+
+	const auto* unpack_pipeline =
+	    GetPerVertexUnpackPipeline(graphics, m_context.GetPipelineCache().DriverCache());
+
+	// Descriptor pool for unpack set (4 storage buffers) + extra set (3 storage buffers)
+	vk::DescriptorPool           pool;
+	const vk::DescriptorPoolSize pool_size(vk::DescriptorType::eStorageBuffer, 7);
+	vk::DescriptorPoolCreateInfo pool_info {};
+	pool_info.maxSets       = 2;
+	pool_info.poolSizeCount = 1;
+	pool_info.pPoolSizes    = &pool_size;
+	EXIT_IF(graphics.device.createDescriptorPool(&pool_info, nullptr, &pool) !=
+	        vk::Result::eSuccess);
+
+	// Allocate and update unpack descriptor set
+	vk::DescriptorSet             unpack_set;
+	vk::DescriptorSetAllocateInfo unpack_alloc {};
+	unpack_alloc.descriptorPool     = pool;
+	unpack_alloc.descriptorSetCount = 1;
+	unpack_alloc.pSetLayouts        = &unpack_pipeline->set_layout;
+	EXIT_IF(graphics.device.allocateDescriptorSets(&unpack_alloc, &unpack_set) !=
+	        vk::Result::eSuccess);
+
+	const uint64_t idx_bytes_raw =
+	    draw.IsIndexed()
+	        ? (static_cast<uint64_t>(draw.index_count) * index_source.guest_element_size +
+	           index_byte_adjust)
+	        : (vtx_total_bytes + vertex_byte_adjust);
+	const uint64_t idx_size_bounded =
+	    std::min(Common::AlignUp(idx_bytes_raw, 4), idx_buf_available);
+
+	const uint64_t vtx_bytes_raw = vtx_total_bytes + vertex_byte_adjust;
+	const uint64_t vtx_buf_available =
+	    vtx_buf_ptr->Size() > vtx_aligned_offset ? (vtx_buf_ptr->Size() - vtx_aligned_offset) : 0;
+	const uint64_t vtx_size_bounded =
+	    std::min(Common::AlignUp(vtx_bytes_raw, 4) + 4, vtx_buf_available);
+
+	const vk::DescriptorBufferInfo unpack_data[] {
+	    {idx_vk_buf, idx_aligned_offset, idx_size_bounded},
+	    {vtx_buf_ptr->Handle(), vtx_aligned_offset, vtx_size_bounded},
+	    {id_buffer->Handle(), 0, id_buffer->Size()},
+	    {attribute_buffer->Handle(), 0, attribute_buffer->Size()}};
+	std::array<vk::WriteDescriptorSet, 4> unpack_writes;
+	for (uint32_t i = 0; i < 4; ++i) {
+		unpack_writes[i].dstSet          = unpack_set;
+		unpack_writes[i].dstBinding      = i;
+		unpack_writes[i].descriptorCount = 1;
+		unpack_writes[i].descriptorType  = vk::DescriptorType::eStorageBuffer;
+		unpack_writes[i].pBufferInfo     = &unpack_data[i];
+	}
+	graphics.device.updateDescriptorSets(4, unpack_writes.data(), 0, nullptr);
+
+	// Allocate and update extra descriptor set (shared between capture compute & graphics replay)
+	vk::DescriptorSet             extra_set;
+	vk::DescriptorSetAllocateInfo extra_alloc {};
+	extra_alloc.descriptorPool     = pool;
+	extra_alloc.descriptorSetCount = 1;
+	extra_alloc.pSetLayouts        = &programs->extra_layout;
+	EXIT_IF(graphics.device.allocateDescriptorSets(&extra_alloc, &extra_set) !=
+	        vk::Result::eSuccess);
+
+	const vk::DescriptorBufferInfo extra_data[] {
+	    {attribute_buffer->Handle(), 0, attribute_buffer->Size()},
+	    {captured->Handle(), 0, captured->Size()},
+	    {id_buffer->Handle(), 0, id_buffer->Size()}};
+	std::array<vk::WriteDescriptorSet, 3> extra_writes;
+	for (uint32_t i = 0; i < 3; ++i) {
+		extra_writes[i].dstSet          = extra_set;
+		extra_writes[i].dstBinding      = i;
+		extra_writes[i].descriptorCount = 1;
+		extra_writes[i].descriptorType  = vk::DescriptorType::eStorageBuffer;
+		extra_writes[i].pBufferInfo     = &extra_data[i];
+	}
+	graphics.device.updateDescriptorSets(3, extra_writes.data(), 0, nullptr);
+
+	// Prepare Unpack push constants
+	UnpackPushConstants unpack_push {};
+	unpack_push.total_invocations = count;
+	unpack_push.index_count       = draw.index_count;
+	unpack_push.first_vertex      = emit.first_vertex;
+	unpack_push.vertex_offset     = emit.vertex_offset;
+	unpack_push.first_instance    = emit.first_instance;
+	unpack_push.vertex_stride     = input.stride;
+	unpack_push.num_records       = input.num_records;
+
+	uint32_t idx_flag = 0;
+	if (draw.IsIndexed()) {
+		idx_flag = 1u;
+		if (index_source.guest_element_size == 2) {
+			idx_flag |= (1u << 1u);
+		} else if (index_source.guest_element_size == 4) {
+			idx_flag |= (2u << 1u);
+		}
+	}
+	unpack_push.packed_flags =
+	    (index_byte_adjust & 0xffffu) | (idx_flag << 16u) | ((num_attrs & 0x0fu) << 19u);
+
+	for (uint32_t i = 0; i < num_attrs; ++i) {
+		const auto&    descriptor  = vs.resources[i];
+		const auto     format_info = ShaderRecompiler::Format::GetFormatInfo(descriptor.Format());
+		const uint32_t byte_offset = vertex_byte_adjust + input.attr_offsets[i];
+		const uint32_t is_float =
+		    format_info.type == ShaderRecompiler::Format::ComponentType::Float ? 1u : 0u;
+		const uint32_t comp_count = format_info.component_count;
+		unpack_push.attrs[i].meta =
+		    (byte_offset & 0xffffu) | (is_float << 16u) | (comp_count << 17u);
+
+		uint32_t bit_counts  = 0;
+		uint32_t bit_offsets = 0;
+		for (uint32_t c = 0; c < 4; ++c) {
+			bit_counts |= (format_info.component_bits[c] & 0xffu) << (c * 8u);
+			bit_offsets |= (format_info.component_bit_offset[c] & 0xffu) << (c * 8u);
+		}
+		unpack_push.attrs[i].bit_counts  = bit_counts;
+		unpack_push.attrs[i].bit_offsets = bit_offsets;
+	}
+
+	auto cmd = buffer.Handle();
+
+	// Step 1: GPU unpack compute pass
+	cmd.bindPipeline(vk::PipelineBindPoint::eCompute, unpack_pipeline->pipeline);
+	cmd.bindDescriptorSets(vk::PipelineBindPoint::eCompute, unpack_pipeline->pipeline_layout, 0, 1,
+	                       &unpack_set, 0, nullptr);
+	cmd.pushConstants(unpack_pipeline->pipeline_layout, vk::ShaderStageFlagBits::eCompute, 0,
+	                  sizeof(unpack_push), &unpack_push);
+	cmd.dispatch((count + 63) / 64, 1, 1);
+
+	// Barrier: Unpack -> Capture compute
+	vk::MemoryBarrier unpack_barrier {};
+	unpack_barrier.srcAccessMask = vk::AccessFlagBits::eShaderWrite;
+	unpack_barrier.dstAccessMask = vk::AccessFlagBits::eShaderRead;
+	cmd.pipelineBarrier(vk::PipelineStageFlagBits::eComputeShader,
+	                    vk::PipelineStageFlagBits::eComputeShader, {}, 1, &unpack_barrier, 0,
+	                    nullptr, 0, nullptr);
+
+	// Step 2: Capture compute pass
+	PreparedBindings* vertex_stage[] {&vertex_bindings};
+	CommitBindings(buffer, vk::PipelineBindPoint::eCompute, programs->capture_pipeline,
+	               vertex_stage);
+	cmd = buffer.Handle();
+	cmd.bindDescriptorSets(vk::PipelineBindPoint::eCompute,
+	                       programs->capture_pipeline.pipeline_layout, 1, 1, &extra_set, 0,
+	                       nullptr);
+	cmd.bindPipeline(vk::PipelineBindPoint::eCompute, programs->capture_pipeline.pipeline);
+	cmd.dispatch(count, 1, 1);

🚀 Performance & Scalability | 🟡 Minor | ⚡ Quick win

The capture pass dispatches one invocation per workgroup.

LowerVertexToCompute emits OpExecutionMode <main> LocalSize 1 1 1, so this dispatch creates count workgroups that each run a single invocation. With count bounded at 65535 by line 34, that is up to 65535 workgroups per draw. GPUs schedule at wavefront granularity, so 63 of every 64 lanes idle.

The unpack pass at line 220 already uses LocalSize 64 1 1 with (count + 63) / 64 groups. Apply the same shape to the capture shader: emit LocalSize 64 1 1, derive the invocation index from gl_GlobalInvocationID.x, and add an early return when the index reaches total_invocations.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-19 20:41 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/715#discussion_r4054644825) On `src/graphics/host_gpu/renderer/perVertexPrototypeDraw.inc` line 239 (outdated): ```diff @@ -0,0 +1,290 @@ +// Live PerVertex execution with GPU compute unpack and native C++ pipeline. +void RenderExecutor::ExecutePerVertexPrototype(uint64_t submit_id, CommandBuffer& buffer, + const DrawCallInfo& draw, DrawRenderState& state, + vk::PrimitiveTopology topology, + const DrawEmitInfo& emit, + const DrawIndexBufferSource& index_source, + bool primitive_restart_enable) { + const auto& vs = state.vertex_info[0]; + const auto* programs = GetPerVertexPrototypePrograms( + m_context.GetGraphics(), state.programs, vs, m_context.GetPipelineCache().DriverCache()); + EXIT_IF(programs == nullptr || !state.ps_active || + topology != vk::PrimitiveTopology::eTriangleList || primitive_restart_enable || + draw.index_count % 3 != 0); + EXIT_IF(vs.logical_stage != ShaderType::Vertex || vs.buffers_num != 1 || + vs.resources_num == 0 || vs.resources_num > 8 || HasShaderBufferWrites(vs.stage)); + const auto& input = vs.buffers[0]; + const uint32_t num_attrs = vs.resources_num; + EXIT_IF(input.stride == 0 || input.fetch_index != 0 || + input.attr_num != static_cast<int>(num_attrs) || input.addr == 0); + + for (uint32_t i = 0; i < num_attrs; ++i) { + EXIT_IF(input.attr_indices[i] != static_cast<int>(i)); + const auto& descriptor = vs.resources[i]; + const auto format = ShaderRecompiler::Format::GetFormatInfo(descriptor.Format()); + EXIT_IF(format.byte_size > input.stride || + input.attr_offsets[i] > input.stride - format.byte_size || + descriptor.SwizzleEnabled() || descriptor.AddTid()); + std::array<uint8_t, 16> bytes {}; + std::array<uint32_t, 4> decoded {}; + EXIT_IF(!DecodePerVertexPrototypeAttribute(descriptor.Format(), bytes, decoded)); + } + + const uint64_t count64 = static_cast<uint64_t>(draw.index_count) * draw.instance_count; + EXIT_IF(count64 == 0 || count64 > 65535); + const auto count = static_cast<uint32_t>(count64); + auto& graphics = m_context.GetGraphics(); + auto& scheduler = m_context.GetCommandScheduler(); + auto& cache = m_context.GetBufferCache(); + scheduler.EndRendering(); + + const auto alignment = graphics.StorageMinAlignment(); + + // Obtain vertex buffer from GPU cache without host readback + const uint64_t vtx_total_bytes = static_cast<uint64_t>(input.stride) * input.num_records; + auto [vtx_buf_ptr, vtx_offset] = cache.ObtainBuffer(input.addr, vtx_total_bytes, false); + const uint64_t vtx_aligned_offset = Common::AlignDown(vtx_offset, alignment); + const uint32_t vertex_byte_adjust = static_cast<uint32_t>(vtx_offset - vtx_aligned_offset); + + vk::Buffer idx_vk_buf = nullptr; + uint64_t idx_aligned_offset = 0; + uint32_t index_byte_adjust = 0; + uint64_t idx_buf_available = 0; + if (draw.IsIndexed()) { + EXIT_IF(index_source.guest_element_size != 1 && index_source.guest_element_size != 2 && + index_source.guest_element_size != 4); + const uint64_t idx_total_bytes = + static_cast<uint64_t>(draw.index_count) * index_source.guest_element_size; + if (index_source.host_data != nullptr) { + auto& stream = cache.GetUtilityBuffer(MemoryUsage::Stream); + const auto offset = stream.Copy(index_source.host_data, idx_total_bytes, 16); + idx_vk_buf = stream.Handle(); + idx_aligned_offset = Common::AlignDown(offset, alignment); + index_byte_adjust = static_cast<uint32_t>(offset - idx_aligned_offset); + idx_buf_available = + stream.Size() > idx_aligned_offset ? (stream.Size() - idx_aligned_offset) : 0; + } else { + auto [idx_buf_ptr, offset] = + cache.ObtainBuffer(index_source.address, idx_total_bytes, false); + idx_vk_buf = idx_buf_ptr->Handle(); + idx_aligned_offset = Common::AlignDown(offset, alignment); + index_byte_adjust = static_cast<uint32_t>(offset - idx_aligned_offset); + idx_buf_available = idx_buf_ptr->Size() > idx_aligned_offset + ? (idx_buf_ptr->Size() - idx_aligned_offset) + : 0; + } + } else { + idx_vk_buf = vtx_buf_ptr->Handle(); + idx_aligned_offset = 0; + index_byte_adjust = 0; + idx_buf_available = vtx_buf_ptr->Size(); + } + + PreparedBindings vertex_bindings = PrepareBindings(vs.stage); + PreparedBindings pixel_bindings = PrepareBindings(state.ps_input_info.stage); + PreparedBindings* stages[] {&vertex_bindings, &pixel_bindings}; + PrepareGraphicsBindings(stages, {state.color_info, state.color_count}); + + // GPU-side intermediate buffers for unpack and capture + auto id_buffer = + std::make_unique<Buffer>(graphics, scheduler, MemoryUsage::Stream, 0, AllFlags, count * 8); + auto attribute_buffer = std::make_unique<Buffer>(graphics, scheduler, MemoryUsage::Stream, 0, + AllFlags, count * num_attrs * 16); + auto captured = std::make_unique<Buffer>(graphics, scheduler, MemoryUsage::Stream, 0, AllFlags, + count64 * programs->layout.record_stride_vec4 * 16); + + const auto* unpack_pipeline = + GetPerVertexUnpackPipeline(graphics, m_context.GetPipelineCache().DriverCache()); + + // Descriptor pool for unpack set (4 storage buffers) + extra set (3 storage buffers) + vk::DescriptorPool pool; + const vk::DescriptorPoolSize pool_size(vk::DescriptorType::eStorageBuffer, 7); + vk::DescriptorPoolCreateInfo pool_info {}; + pool_info.maxSets = 2; + pool_info.poolSizeCount = 1; + pool_info.pPoolSizes = &pool_size; + EXIT_IF(graphics.device.createDescriptorPool(&pool_info, nullptr, &pool) != + vk::Result::eSuccess); + + // Allocate and update unpack descriptor set + vk::DescriptorSet unpack_set; + vk::DescriptorSetAllocateInfo unpack_alloc {}; + unpack_alloc.descriptorPool = pool; + unpack_alloc.descriptorSetCount = 1; + unpack_alloc.pSetLayouts = &unpack_pipeline->set_layout; + EXIT_IF(graphics.device.allocateDescriptorSets(&unpack_alloc, &unpack_set) != + vk::Result::eSuccess); + + const uint64_t idx_bytes_raw = + draw.IsIndexed() + ? (static_cast<uint64_t>(draw.index_count) * index_source.guest_element_size + + index_byte_adjust) + : (vtx_total_bytes + vertex_byte_adjust); + const uint64_t idx_size_bounded = + std::min(Common::AlignUp(idx_bytes_raw, 4), idx_buf_available); + + const uint64_t vtx_bytes_raw = vtx_total_bytes + vertex_byte_adjust; + const uint64_t vtx_buf_available = + vtx_buf_ptr->Size() > vtx_aligned_offset ? (vtx_buf_ptr->Size() - vtx_aligned_offset) : 0; + const uint64_t vtx_size_bounded = + std::min(Common::AlignUp(vtx_bytes_raw, 4) + 4, vtx_buf_available); + + const vk::DescriptorBufferInfo unpack_data[] { + {idx_vk_buf, idx_aligned_offset, idx_size_bounded}, + {vtx_buf_ptr->Handle(), vtx_aligned_offset, vtx_size_bounded}, + {id_buffer->Handle(), 0, id_buffer->Size()}, + {attribute_buffer->Handle(), 0, attribute_buffer->Size()}}; + std::array<vk::WriteDescriptorSet, 4> unpack_writes; + for (uint32_t i = 0; i < 4; ++i) { + unpack_writes[i].dstSet = unpack_set; + unpack_writes[i].dstBinding = i; + unpack_writes[i].descriptorCount = 1; + unpack_writes[i].descriptorType = vk::DescriptorType::eStorageBuffer; + unpack_writes[i].pBufferInfo = &unpack_data[i]; + } + graphics.device.updateDescriptorSets(4, unpack_writes.data(), 0, nullptr); + + // Allocate and update extra descriptor set (shared between capture compute & graphics replay) + vk::DescriptorSet extra_set; + vk::DescriptorSetAllocateInfo extra_alloc {}; + extra_alloc.descriptorPool = pool; + extra_alloc.descriptorSetCount = 1; + extra_alloc.pSetLayouts = &programs->extra_layout; + EXIT_IF(graphics.device.allocateDescriptorSets(&extra_alloc, &extra_set) != + vk::Result::eSuccess); + + const vk::DescriptorBufferInfo extra_data[] { + {attribute_buffer->Handle(), 0, attribute_buffer->Size()}, + {captured->Handle(), 0, captured->Size()}, + {id_buffer->Handle(), 0, id_buffer->Size()}}; + std::array<vk::WriteDescriptorSet, 3> extra_writes; + for (uint32_t i = 0; i < 3; ++i) { + extra_writes[i].dstSet = extra_set; + extra_writes[i].dstBinding = i; + extra_writes[i].descriptorCount = 1; + extra_writes[i].descriptorType = vk::DescriptorType::eStorageBuffer; + extra_writes[i].pBufferInfo = &extra_data[i]; + } + graphics.device.updateDescriptorSets(3, extra_writes.data(), 0, nullptr); + + // Prepare Unpack push constants + UnpackPushConstants unpack_push {}; + unpack_push.total_invocations = count; + unpack_push.index_count = draw.index_count; + unpack_push.first_vertex = emit.first_vertex; + unpack_push.vertex_offset = emit.vertex_offset; + unpack_push.first_instance = emit.first_instance; + unpack_push.vertex_stride = input.stride; + unpack_push.num_records = input.num_records; + + uint32_t idx_flag = 0; + if (draw.IsIndexed()) { + idx_flag = 1u; + if (index_source.guest_element_size == 2) { + idx_flag |= (1u << 1u); + } else if (index_source.guest_element_size == 4) { + idx_flag |= (2u << 1u); + } + } + unpack_push.packed_flags = + (index_byte_adjust & 0xffffu) | (idx_flag << 16u) | ((num_attrs & 0x0fu) << 19u); + + for (uint32_t i = 0; i < num_attrs; ++i) { + const auto& descriptor = vs.resources[i]; + const auto format_info = ShaderRecompiler::Format::GetFormatInfo(descriptor.Format()); + const uint32_t byte_offset = vertex_byte_adjust + input.attr_offsets[i]; + const uint32_t is_float = + format_info.type == ShaderRecompiler::Format::ComponentType::Float ? 1u : 0u; + const uint32_t comp_count = format_info.component_count; + unpack_push.attrs[i].meta = + (byte_offset & 0xffffu) | (is_float << 16u) | (comp_count << 17u); + + uint32_t bit_counts = 0; + uint32_t bit_offsets = 0; + for (uint32_t c = 0; c < 4; ++c) { + bit_counts |= (format_info.component_bits[c] & 0xffu) << (c * 8u); + bit_offsets |= (format_info.component_bit_offset[c] & 0xffu) << (c * 8u); + } + unpack_push.attrs[i].bit_counts = bit_counts; + unpack_push.attrs[i].bit_offsets = bit_offsets; + } + + auto cmd = buffer.Handle(); + + // Step 1: GPU unpack compute pass + cmd.bindPipeline(vk::PipelineBindPoint::eCompute, unpack_pipeline->pipeline); + cmd.bindDescriptorSets(vk::PipelineBindPoint::eCompute, unpack_pipeline->pipeline_layout, 0, 1, + &unpack_set, 0, nullptr); + cmd.pushConstants(unpack_pipeline->pipeline_layout, vk::ShaderStageFlagBits::eCompute, 0, + sizeof(unpack_push), &unpack_push); + cmd.dispatch((count + 63) / 64, 1, 1); + + // Barrier: Unpack -> Capture compute + vk::MemoryBarrier unpack_barrier {}; + unpack_barrier.srcAccessMask = vk::AccessFlagBits::eShaderWrite; + unpack_barrier.dstAccessMask = vk::AccessFlagBits::eShaderRead; + cmd.pipelineBarrier(vk::PipelineStageFlagBits::eComputeShader, + vk::PipelineStageFlagBits::eComputeShader, {}, 1, &unpack_barrier, 0, + nullptr, 0, nullptr); + + // Step 2: Capture compute pass + PreparedBindings* vertex_stage[] {&vertex_bindings}; + CommitBindings(buffer, vk::PipelineBindPoint::eCompute, programs->capture_pipeline, + vertex_stage); + cmd = buffer.Handle(); + cmd.bindDescriptorSets(vk::PipelineBindPoint::eCompute, + programs->capture_pipeline.pipeline_layout, 1, 1, &extra_set, 0, + nullptr); + cmd.bindPipeline(vk::PipelineBindPoint::eCompute, programs->capture_pipeline.pipeline); + cmd.dispatch(count, 1, 1); ``` _🚀 Performance & Scalability_ | _🟡 Minor_ | _⚡ Quick win_ **The capture pass dispatches one invocation per workgroup.** `LowerVertexToCompute` emits `OpExecutionMode <main> LocalSize 1 1 1`, so this dispatch creates `count` workgroups that each run a single invocation. With `count` bounded at 65535 by line 34, that is up to 65535 workgroups per draw. GPUs schedule at wavefront granularity, so 63 of every 64 lanes idle. The unpack pass at line 220 already uses `LocalSize 64 1 1` with `(count + 63) / 64` groups. Apply the same shape to the capture shader: emit `LocalSize 64 1 1`, derive the invocation index from `gl_GlobalInvocationID.x`, and add an early return when the index reaches `total_invocations`. <!-- fingerprinting:phantom:medusa:komodo --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:4329b073228b16d8d0585e99 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-19 20:41 UTC · original
On src/graphics/host_gpu/renderer/perVertexTransform.cpp line 283 (outdated):

@@ -0,0 +1,967 @@
+#include "graphics/host_gpu/renderer/perVertexTransform.h"
+
+#include "common/file.h"
+#include "common/threads.h"
+#include "kytyGitVersion.h"
+
+#include <algorithm>
+#include <atomic>
+#include <cstdint>
+#include <cstring>
+#include <fmt/format.h>
+#include <map>
+#include <regex>
+#include <set>
+#include <spirv/unified1/spirv.hpp>
+#include <sstream>
+#include <string>
+#include <vector>
+#include <xxhash.h>
+
+namespace Libs::Graphics {
+
+// Older MSVC STL always matches ^/$ at line boundaries, but has no multiline
+// flag. The macro arrived with the implementation of the standard option.
+#if defined(_MSVC_STL_VERSION) && !defined(_REGEX_LEGACY_MULTILINE_MODE)
+static constexpr auto kMultilineRegex = std::regex_constants::ECMAScript;
+#else
+static constexpr auto kMultilineRegex =
+    std::regex_constants::ECMAScript | std::regex_constants::multiline;
+#endif
+
+// The transformed modules are assembled as SPIR-V 1.5. Since 1.4, the entry
+// interface must include all used globals, including resources and Private I/O.
+// Source shaders can be 1.3, whose interfaces only list Input/Output variables.
+static std::string CompleteEntryPointInterface(const std::string& source) {
+	std::istringstream lines(source);
+	std::string        line, interfaces;
+	while (std::getline(lines, line)) {
+		std::istringstream tokens(line);
+		std::string        id, equals, opcode;
+		tokens >> id >> equals >> opcode;
+		if (opcode == "OpFunction") break;
+		if (equals == "=" && opcode == "OpVariable") interfaces += " " + id;
+	}
+	const std::regex entry_re(R"((OpEntryPoint\s+\S+\s+%\S+\s+"[^"]*")[^\r\n]*)");
+	return std::regex_replace(source, entry_re, "$1" + interfaces);
+}
+
+bool DerivePerVertexLayout(const std::string& vs_source, const std::string& ps_source,
+                           PerVertexLayout&                 layout,
+                           std::map<uint32_t, std::string>& vs_param_vars) {
+	std::regex var_re(R"(^\s*(%\S+)\s*=\s*OpVariable\s+%\S+\s+Output\s*$)", kMultilineRegex);
+	std::set<std::string> vs_outputs;
+	for (auto it = std::sregex_iterator(vs_source.begin(), vs_source.end(), var_re);
+	     it != std::sregex_iterator(); ++it) {
+		vs_outputs.insert((*it)[1]);
+	}
+	if (vs_outputs.empty()) return false;
+
+	bool has_clip = vs_outputs.find("%gl_ClipDistance") != vs_outputs.end();
+
+	vs_param_vars.clear();
+	for (const auto& var: vs_outputs) {
+		if (var == "%outPerVertex" || var == "%gl_ClipDistance" || var == "%gl_PointSize") continue;
+		std::regex  loc_re(R"(^\s*OpDecorate\s+)" + var + R"(\s+Location\s+(\d+)\s*$)",
+		                   kMultilineRegex);
+		std::smatch m;
+		if (std::regex_search(vs_source, m, loc_re)) {
+			uint32_t loc       = static_cast<uint32_t>(std::stoul(m[1]));
+			vs_param_vars[loc] = var;
+		}
+	}
+
+	layout.has_clip   = has_clip;
+	layout.num_params = static_cast<uint32_t>(vs_param_vars.size());
+	layout.param_locations_and_slots.clear();
+	layout.location_to_slot.clear();
+
+	uint32_t current_slot = 1;
+	for (const auto& [loc, var_name]: vs_param_vars) {
+		layout.location_to_slot[loc] = current_slot;
+		layout.param_locations_and_slots.push_back({loc, current_slot});
+		current_slot++;
+	}
+
+	if (has_clip) {
+		layout.clip_slot          = current_slot;
+		layout.record_stride_vec4 = current_slot + 1;
+	} else {
+		layout.clip_slot          = UINT32_MAX;
+		layout.record_stride_vec4 = current_slot;
+	}
+
+	std::regex pv_re(R"(^\s*OpDecorate\s+(%\S+)\s+PerVertexKHR\s*$)", kMultilineRegex);
+	std::vector<std::string> pv_vars;
+	for (auto it = std::sregex_iterator(ps_source.begin(), ps_source.end(), pv_re);
+	     it != std::sregex_iterator(); ++it) {
+		pv_vars.push_back((*it)[1]);
+	}
+	if (pv_vars.empty()) return false;
+
+	for (const auto& pv_var: pv_vars) {
+		std::regex  loc_re(R"(^\s*OpDecorate\s+)" + pv_var + R"(\s+Location\s+(\d+)\s*$)",
+		                   kMultilineRegex);
+		std::smatch m;
+		if (!std::regex_search(ps_source, m, loc_re)) {
+			return false;
+		}
+		uint32_t loc = static_cast<uint32_t>(std::stoul(m[1]));
+		auto     it  = layout.location_to_slot.find(loc);
+		if (it == layout.location_to_slot.end()) {
+			return false;
+		}
+		uint32_t slot = it->second;
+		if (slot >= layout.clip_slot) {
+			return false;
+		}
+		if (slot >= layout.record_stride_vec4) {
+			return false;
+		}
+	}
+	return true;
+}
+
+std::string GenerateReplayVertexSpvasm(const PerVertexLayout& layout) {
+	std::vector<std::string> entry_interfaces = {"%gl_VertexIndex", "%_", "%capture_output"};
+	for (const auto& [loc, _]: layout.param_locations_and_slots) {
+		entry_interfaces.push_back("%out_param_" + std::to_string(loc));
+	}
+	entry_interfaces.push_back("%out_primitive_id");
+
+	std::string entry_iface_str;
+	for (size_t i = 0; i < entry_interfaces.size(); ++i) {
+		if (i > 0) entry_iface_str += " ";
+		entry_iface_str += entry_interfaces[i];
+	}
+
+	std::ostringstream ss;
+	ss << "OpCapability Shader\n";
+	if (layout.has_clip) {
+		ss << "OpCapability ClipDistance\n";
+	}
+	ss << "OpMemoryModel Logical GLSL450\n";
+	ss << "OpEntryPoint Vertex %main \"main\" " << entry_iface_str << "\n";
+	ss << "OpDecorate %gl_VertexIndex BuiltIn VertexIndex\n";
+	ss << "OpDecorate %gl_PerVertex Block\n";
+	ss << "OpMemberDecorate %gl_PerVertex 0 BuiltIn Position\n";
+	ss << "OpMemberDecorate %gl_PerVertex 1 BuiltIn PointSize\n";
+	if (layout.has_clip) {
+		ss << "OpMemberDecorate %gl_PerVertex 2 BuiltIn ClipDistance\n";
+	}
+	ss << "OpDecorate %_runtimearr_v4float ArrayStride 16\n";
+	ss << "OpDecorate %CaptureOutput Block\n";
+	ss << "OpMemberDecorate %CaptureOutput 0 NonWritable\n";
+	ss << "OpMemberDecorate %CaptureOutput 0 Offset 0\n";
+	ss << "OpDecorate %capture_output NonWritable\n";
+	ss << "OpDecorate %capture_output Binding 1\n";
+	ss << "OpDecorate %capture_output DescriptorSet 1\n";
+	for (const auto& [loc, _]: layout.param_locations_and_slots) {
+		ss << "OpDecorate %out_param_" << loc << " Location " << loc << "\n";
+	}
+	ss << "OpDecorate %out_primitive_id Flat\n";
+	ss << "OpDecorate %out_primitive_id Location 31\n";
+	ss << "%void = OpTypeVoid\n";
+	ss << "%fn = OpTypeFunction %void\n";
+	ss << "%uint = OpTypeInt 32 0\n";
+	ss << "%int = OpTypeInt 32 1\n";
+	ss << "%float = OpTypeFloat 32\n";
+	ss << "%v4float = OpTypeVector %float 4\n";
+	ss << "%uint_0 = OpConstant %uint 0\n";
+	ss << "%uint_1 = OpConstant %uint 1\n";
+	ss << "%uint_3 = OpConstant %uint 3\n";
+	ss << "%int_0 = OpConstant %int 0\n";
+	ss << "%int_2 = OpConstant %int 2\n";
+	ss << "%stride_const = OpConstant %uint " << layout.record_stride_vec4 << "\n";
+	for (const auto& [loc, slot]: layout.param_locations_and_slots) {
+		ss << "%slot_const_" << slot << " = OpConstant %uint " << slot << "\n";
+	}
+	if (layout.has_clip) {
+		ss << "%clip_slot_const = OpConstant %uint " << layout.clip_slot << "\n";
+		ss << "%_arr_float_1 = OpTypeArray %float %uint_1\n";
+		ss << "%_ptr_StorageBuffer_float = OpTypePointer StorageBuffer %float\n";
+		ss << "%_ptr_Output_float = OpTypePointer Output %float\n";
+		ss << "%gl_PerVertex = OpTypeStruct %v4float %float %_arr_float_1\n";
+	} else {
+		ss << "%gl_PerVertex = OpTypeStruct %v4float %float\n";
+	}
+	ss << "%_ptr_Output_gl_PerVertex = OpTypePointer Output %gl_PerVertex\n";
+	ss << "%_ = OpVariable %_ptr_Output_gl_PerVertex Output\n";
+	ss << "%_ptr_Input_int = OpTypePointer Input %int\n";
+	ss << "%gl_VertexIndex = OpVariable %_ptr_Input_int Input\n";
+	ss << "%_runtimearr_v4float = OpTypeRuntimeArray %v4float\n";
+	ss << "%CaptureOutput = OpTypeStruct %_runtimearr_v4float\n";
+	ss << "%_ptr_StorageBuffer_CaptureOutput = OpTypePointer StorageBuffer %CaptureOutput\n";
+	ss << "%capture_output = OpVariable %_ptr_StorageBuffer_CaptureOutput StorageBuffer\n";
+	ss << "%_ptr_StorageBuffer_v4float = OpTypePointer StorageBuffer %v4float\n";
+	ss << "%_ptr_Output_v4float = OpTypePointer Output %v4float\n";
+	ss << "%_ptr_Output_uint = OpTypePointer Output %uint\n";
+	ss << "%out_primitive_id = OpVariable %_ptr_Output_uint Output\n";
+	for (const auto& [loc, _]: layout.param_locations_and_slots) {
+		ss << "%out_param_" << loc << " = OpVariable %_ptr_Output_v4float Output\n";
+	}
+
+	ss << "%main = OpFunction %void None %fn\n";
+	ss << "%label = OpLabel\n";
+	ss << "%vidx_i = OpLoad %int %gl_VertexIndex\n";
+	ss << "%vidx = OpBitcast %uint %vidx_i\n";
+	ss << "%base = OpIMul %uint %vidx %stride_const\n";
+	ss << "%pos_ptr = OpAccessChain %_ptr_StorageBuffer_v4float %capture_output %int_0 %base\n";
+	ss << "%pos_val = OpLoad %v4float %pos_ptr\n";
+	ss << "%out_pos_ptr = OpAccessChain %_ptr_Output_v4float %_ %int_0\n";
+	ss << "OpStore %out_pos_ptr %pos_val\n";
+	for (const auto& [loc, slot]: layout.param_locations_and_slots) {
+		ss << "%param_idx_" << slot << " = OpIAdd %uint %base %slot_const_" << slot << "\n";
+		ss << "%param_ptr_" << slot
+		   << " = OpAccessChain %_ptr_StorageBuffer_v4float %capture_output %int_0 %param_idx_"
+		   << slot << "\n";
+		ss << "%param_val_" << slot << " = OpLoad %v4float %param_ptr_" << slot << "\n";
+		ss << "OpStore %out_param_" << loc << " %param_val_" << slot << "\n";
+	}
+	if (layout.has_clip) {
+		ss << "%clip_idx = OpIAdd %uint %base %clip_slot_const\n";
+		ss << "%clip_src_ptr = OpAccessChain %_ptr_StorageBuffer_float %capture_output %int_0 "
+		      "%clip_idx %uint_0\n";
+		ss << "%clip_val = OpLoad %float %clip_src_ptr\n";
+		ss << "%clip_dst_ptr = OpAccessChain %_ptr_Output_float %_ %int_2 %uint_0\n";
+		ss << "OpStore %clip_dst_ptr %clip_val\n";
+	}
+	ss << "%primid = OpUDiv %uint %vidx %uint_3\n";
+	ss << "OpStore %out_primitive_id %primid\n";
+	ss << "OpReturn\n";
+	ss << "OpFunctionEnd\n";
+	return ss.str();
+}
+
+std::string LowerVertexToCompute(const std::string& source, const PerVertexLayout& layout,
+                                 const std::map<uint32_t, std::string>& vs_param_vars) {
+	std::regex            var_re(R"(^\s*(%\S+)\s*=\s*OpVariable\s+%\S+\s+(Input|Output)\s*$)",
+	                             kMultilineRegex);
+	std::set<std::string> inputs, outputs, attr_inputs;
+	for (auto it = std::sregex_iterator(source.begin(), source.end(), var_re);
+	     it != std::sregex_iterator(); ++it) {
+		std::string name    = (*it)[1];
+		std::string storage = (*it)[2];
+		if (storage == "Input") {
+			inputs.insert(name);
+			if (name.rfind("%in_attr_", 0) == 0) attr_inputs.insert(name);
+		} else {
+			outputs.insert(name);
+		}
+	}
+	std::vector<int> attr_indices;
+	for (const auto& a: attr_inputs) {
+		attr_indices.push_back(std::stoi(a.substr(9)));
+	}
+	std::sort(attr_indices.begin(), attr_indices.end());
+	uint32_t num_attrs     = static_cast<uint32_t>(attr_indices.size());
+	uint32_t output_stride = layout.record_stride_vec4;
+	bool     has_clip      = layout.has_clip;
+
+	std::vector<uint32_t> attr_widths(num_attrs, 1);
+	for (uint32_t i = 0; i < num_attrs; ++i) {
+		std::regex  var_decl(R"(^\s*%in_attr_)" + std::to_string(i) +
+		                         R"(\s*=\s*OpVariable\s+(%\S+)\s+Input\s*$)",
+		                     kMultilineRegex);
+		std::smatch m;
+		if (std::regex_search(source, m, var_decl)) {
+			std::string ptr_type = m[1];
+			std::regex ptr_re(R"(^\s*)" + ptr_type + R"(\s*=\s*OpTypePointer\s+Input\s+(%\S+)\s*$)",
+			                  kMultilineRegex);
+			if (std::regex_search(source, m, ptr_re)) {
+				std::string data_type = m[1];
+				std::regex  vec_re(R"(^\s*)" + data_type +
+				                       R"(\s*=\s*OpTypeVector\s+%float\s+(\d+)\s*$)",
+				                   kMultilineRegex);
+				if (std::regex_search(source, m, vec_re)) {
+					attr_widths[i] = std::stoi(m[1]);
+				} else {
+					attr_widths[i] = 1;
+				}
+			}
+		}
+	}

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Attribute widths assume contiguous %in_attr_N indices.

Line 261 sizes attr_widths by num_attrs, and the loop at line 262 probes %in_attr_0 through %in_attr_{num_attrs-1}. The set of indices actually found comes from attr_indices, which is sorted but never checked for contiguity. If the source declares %in_attr_0 and %in_attr_2, num_attrs is 2, %in_attr_1 is not found so attr_widths[1] keeps the default 1, and %in_attr_2 receives no OpStore at all. The capture pass then reads an uninitialized attribute.

The vertex-buffer guard in perVertexPrototypeDraw.inc checks input.attr_indices[i] == i, but that constrains buffer slots, not the shader-side %in_attr_N numbering.

Reject the shader when attr_indices is not exactly 0..num_attrs-1.

🛡️ Proposed guard
 	std::sort(attr_indices.begin(), attr_indices.end());
 	uint32_t num_attrs     = static_cast<uint32_t>(attr_indices.size());
+	for (uint32_t i = 0; i < num_attrs; ++i) {
+		if (attr_indices[i] != static_cast<int>(i)) return {};
+	}
 	uint32_t output_stride = layout.record_stride_vec4;
**@⁠coderabbitai[bot]** on GitHub · 2026-09-19 20:41 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/715#discussion_r4054644826) On `src/graphics/host_gpu/renderer/perVertexTransform.cpp` line 283 (outdated): ```diff @@ -0,0 +1,967 @@ +#include "graphics/host_gpu/renderer/perVertexTransform.h" + +#include "common/file.h" +#include "common/threads.h" +#include "kytyGitVersion.h" + +#include <algorithm> +#include <atomic> +#include <cstdint> +#include <cstring> +#include <fmt/format.h> +#include <map> +#include <regex> +#include <set> +#include <spirv/unified1/spirv.hpp> +#include <sstream> +#include <string> +#include <vector> +#include <xxhash.h> + +namespace Libs::Graphics { + +// Older MSVC STL always matches ^/$ at line boundaries, but has no multiline +// flag. The macro arrived with the implementation of the standard option. +#if defined(_MSVC_STL_VERSION) && !defined(_REGEX_LEGACY_MULTILINE_MODE) +static constexpr auto kMultilineRegex = std::regex_constants::ECMAScript; +#else +static constexpr auto kMultilineRegex = + std::regex_constants::ECMAScript | std::regex_constants::multiline; +#endif + +// The transformed modules are assembled as SPIR-V 1.5. Since 1.4, the entry +// interface must include all used globals, including resources and Private I/O. +// Source shaders can be 1.3, whose interfaces only list Input/Output variables. +static std::string CompleteEntryPointInterface(const std::string& source) { + std::istringstream lines(source); + std::string line, interfaces; + while (std::getline(lines, line)) { + std::istringstream tokens(line); + std::string id, equals, opcode; + tokens >> id >> equals >> opcode; + if (opcode == "OpFunction") break; + if (equals == "=" && opcode == "OpVariable") interfaces += " " + id; + } + const std::regex entry_re(R"((OpEntryPoint\s+\S+\s+%\S+\s+"[^"]*")[^\r\n]*)"); + return std::regex_replace(source, entry_re, "$1" + interfaces); +} + +bool DerivePerVertexLayout(const std::string& vs_source, const std::string& ps_source, + PerVertexLayout& layout, + std::map<uint32_t, std::string>& vs_param_vars) { + std::regex var_re(R"(^\s*(%\S+)\s*=\s*OpVariable\s+%\S+\s+Output\s*$)", kMultilineRegex); + std::set<std::string> vs_outputs; + for (auto it = std::sregex_iterator(vs_source.begin(), vs_source.end(), var_re); + it != std::sregex_iterator(); ++it) { + vs_outputs.insert((*it)[1]); + } + if (vs_outputs.empty()) return false; + + bool has_clip = vs_outputs.find("%gl_ClipDistance") != vs_outputs.end(); + + vs_param_vars.clear(); + for (const auto& var: vs_outputs) { + if (var == "%outPerVertex" || var == "%gl_ClipDistance" || var == "%gl_PointSize") continue; + std::regex loc_re(R"(^\s*OpDecorate\s+)" + var + R"(\s+Location\s+(\d+)\s*$)", + kMultilineRegex); + std::smatch m; + if (std::regex_search(vs_source, m, loc_re)) { + uint32_t loc = static_cast<uint32_t>(std::stoul(m[1])); + vs_param_vars[loc] = var; + } + } + + layout.has_clip = has_clip; + layout.num_params = static_cast<uint32_t>(vs_param_vars.size()); + layout.param_locations_and_slots.clear(); + layout.location_to_slot.clear(); + + uint32_t current_slot = 1; + for (const auto& [loc, var_name]: vs_param_vars) { + layout.location_to_slot[loc] = current_slot; + layout.param_locations_and_slots.push_back({loc, current_slot}); + current_slot++; + } + + if (has_clip) { + layout.clip_slot = current_slot; + layout.record_stride_vec4 = current_slot + 1; + } else { + layout.clip_slot = UINT32_MAX; + layout.record_stride_vec4 = current_slot; + } + + std::regex pv_re(R"(^\s*OpDecorate\s+(%\S+)\s+PerVertexKHR\s*$)", kMultilineRegex); + std::vector<std::string> pv_vars; + for (auto it = std::sregex_iterator(ps_source.begin(), ps_source.end(), pv_re); + it != std::sregex_iterator(); ++it) { + pv_vars.push_back((*it)[1]); + } + if (pv_vars.empty()) return false; + + for (const auto& pv_var: pv_vars) { + std::regex loc_re(R"(^\s*OpDecorate\s+)" + pv_var + R"(\s+Location\s+(\d+)\s*$)", + kMultilineRegex); + std::smatch m; + if (!std::regex_search(ps_source, m, loc_re)) { + return false; + } + uint32_t loc = static_cast<uint32_t>(std::stoul(m[1])); + auto it = layout.location_to_slot.find(loc); + if (it == layout.location_to_slot.end()) { + return false; + } + uint32_t slot = it->second; + if (slot >= layout.clip_slot) { + return false; + } + if (slot >= layout.record_stride_vec4) { + return false; + } + } + return true; +} + +std::string GenerateReplayVertexSpvasm(const PerVertexLayout& layout) { + std::vector<std::string> entry_interfaces = {"%gl_VertexIndex", "%_", "%capture_output"}; + for (const auto& [loc, _]: layout.param_locations_and_slots) { + entry_interfaces.push_back("%out_param_" + std::to_string(loc)); + } + entry_interfaces.push_back("%out_primitive_id"); + + std::string entry_iface_str; + for (size_t i = 0; i < entry_interfaces.size(); ++i) { + if (i > 0) entry_iface_str += " "; + entry_iface_str += entry_interfaces[i]; + } + + std::ostringstream ss; + ss << "OpCapability Shader\n"; + if (layout.has_clip) { + ss << "OpCapability ClipDistance\n"; + } + ss << "OpMemoryModel Logical GLSL450\n"; + ss << "OpEntryPoint Vertex %main \"main\" " << entry_iface_str << "\n"; + ss << "OpDecorate %gl_VertexIndex BuiltIn VertexIndex\n"; + ss << "OpDecorate %gl_PerVertex Block\n"; + ss << "OpMemberDecorate %gl_PerVertex 0 BuiltIn Position\n"; + ss << "OpMemberDecorate %gl_PerVertex 1 BuiltIn PointSize\n"; + if (layout.has_clip) { + ss << "OpMemberDecorate %gl_PerVertex 2 BuiltIn ClipDistance\n"; + } + ss << "OpDecorate %_runtimearr_v4float ArrayStride 16\n"; + ss << "OpDecorate %CaptureOutput Block\n"; + ss << "OpMemberDecorate %CaptureOutput 0 NonWritable\n"; + ss << "OpMemberDecorate %CaptureOutput 0 Offset 0\n"; + ss << "OpDecorate %capture_output NonWritable\n"; + ss << "OpDecorate %capture_output Binding 1\n"; + ss << "OpDecorate %capture_output DescriptorSet 1\n"; + for (const auto& [loc, _]: layout.param_locations_and_slots) { + ss << "OpDecorate %out_param_" << loc << " Location " << loc << "\n"; + } + ss << "OpDecorate %out_primitive_id Flat\n"; + ss << "OpDecorate %out_primitive_id Location 31\n"; + ss << "%void = OpTypeVoid\n"; + ss << "%fn = OpTypeFunction %void\n"; + ss << "%uint = OpTypeInt 32 0\n"; + ss << "%int = OpTypeInt 32 1\n"; + ss << "%float = OpTypeFloat 32\n"; + ss << "%v4float = OpTypeVector %float 4\n"; + ss << "%uint_0 = OpConstant %uint 0\n"; + ss << "%uint_1 = OpConstant %uint 1\n"; + ss << "%uint_3 = OpConstant %uint 3\n"; + ss << "%int_0 = OpConstant %int 0\n"; + ss << "%int_2 = OpConstant %int 2\n"; + ss << "%stride_const = OpConstant %uint " << layout.record_stride_vec4 << "\n"; + for (const auto& [loc, slot]: layout.param_locations_and_slots) { + ss << "%slot_const_" << slot << " = OpConstant %uint " << slot << "\n"; + } + if (layout.has_clip) { + ss << "%clip_slot_const = OpConstant %uint " << layout.clip_slot << "\n"; + ss << "%_arr_float_1 = OpTypeArray %float %uint_1\n"; + ss << "%_ptr_StorageBuffer_float = OpTypePointer StorageBuffer %float\n"; + ss << "%_ptr_Output_float = OpTypePointer Output %float\n"; + ss << "%gl_PerVertex = OpTypeStruct %v4float %float %_arr_float_1\n"; + } else { + ss << "%gl_PerVertex = OpTypeStruct %v4float %float\n"; + } + ss << "%_ptr_Output_gl_PerVertex = OpTypePointer Output %gl_PerVertex\n"; + ss << "%_ = OpVariable %_ptr_Output_gl_PerVertex Output\n"; + ss << "%_ptr_Input_int = OpTypePointer Input %int\n"; + ss << "%gl_VertexIndex = OpVariable %_ptr_Input_int Input\n"; + ss << "%_runtimearr_v4float = OpTypeRuntimeArray %v4float\n"; + ss << "%CaptureOutput = OpTypeStruct %_runtimearr_v4float\n"; + ss << "%_ptr_StorageBuffer_CaptureOutput = OpTypePointer StorageBuffer %CaptureOutput\n"; + ss << "%capture_output = OpVariable %_ptr_StorageBuffer_CaptureOutput StorageBuffer\n"; + ss << "%_ptr_StorageBuffer_v4float = OpTypePointer StorageBuffer %v4float\n"; + ss << "%_ptr_Output_v4float = OpTypePointer Output %v4float\n"; + ss << "%_ptr_Output_uint = OpTypePointer Output %uint\n"; + ss << "%out_primitive_id = OpVariable %_ptr_Output_uint Output\n"; + for (const auto& [loc, _]: layout.param_locations_and_slots) { + ss << "%out_param_" << loc << " = OpVariable %_ptr_Output_v4float Output\n"; + } + + ss << "%main = OpFunction %void None %fn\n"; + ss << "%label = OpLabel\n"; + ss << "%vidx_i = OpLoad %int %gl_VertexIndex\n"; + ss << "%vidx = OpBitcast %uint %vidx_i\n"; + ss << "%base = OpIMul %uint %vidx %stride_const\n"; + ss << "%pos_ptr = OpAccessChain %_ptr_StorageBuffer_v4float %capture_output %int_0 %base\n"; + ss << "%pos_val = OpLoad %v4float %pos_ptr\n"; + ss << "%out_pos_ptr = OpAccessChain %_ptr_Output_v4float %_ %int_0\n"; + ss << "OpStore %out_pos_ptr %pos_val\n"; + for (const auto& [loc, slot]: layout.param_locations_and_slots) { + ss << "%param_idx_" << slot << " = OpIAdd %uint %base %slot_const_" << slot << "\n"; + ss << "%param_ptr_" << slot + << " = OpAccessChain %_ptr_StorageBuffer_v4float %capture_output %int_0 %param_idx_" + << slot << "\n"; + ss << "%param_val_" << slot << " = OpLoad %v4float %param_ptr_" << slot << "\n"; + ss << "OpStore %out_param_" << loc << " %param_val_" << slot << "\n"; + } + if (layout.has_clip) { + ss << "%clip_idx = OpIAdd %uint %base %clip_slot_const\n"; + ss << "%clip_src_ptr = OpAccessChain %_ptr_StorageBuffer_float %capture_output %int_0 " + "%clip_idx %uint_0\n"; + ss << "%clip_val = OpLoad %float %clip_src_ptr\n"; + ss << "%clip_dst_ptr = OpAccessChain %_ptr_Output_float %_ %int_2 %uint_0\n"; + ss << "OpStore %clip_dst_ptr %clip_val\n"; + } + ss << "%primid = OpUDiv %uint %vidx %uint_3\n"; + ss << "OpStore %out_primitive_id %primid\n"; + ss << "OpReturn\n"; + ss << "OpFunctionEnd\n"; + return ss.str(); +} + +std::string LowerVertexToCompute(const std::string& source, const PerVertexLayout& layout, + const std::map<uint32_t, std::string>& vs_param_vars) { + std::regex var_re(R"(^\s*(%\S+)\s*=\s*OpVariable\s+%\S+\s+(Input|Output)\s*$)", + kMultilineRegex); + std::set<std::string> inputs, outputs, attr_inputs; + for (auto it = std::sregex_iterator(source.begin(), source.end(), var_re); + it != std::sregex_iterator(); ++it) { + std::string name = (*it)[1]; + std::string storage = (*it)[2]; + if (storage == "Input") { + inputs.insert(name); + if (name.rfind("%in_attr_", 0) == 0) attr_inputs.insert(name); + } else { + outputs.insert(name); + } + } + std::vector<int> attr_indices; + for (const auto& a: attr_inputs) { + attr_indices.push_back(std::stoi(a.substr(9))); + } + std::sort(attr_indices.begin(), attr_indices.end()); + uint32_t num_attrs = static_cast<uint32_t>(attr_indices.size()); + uint32_t output_stride = layout.record_stride_vec4; + bool has_clip = layout.has_clip; + + std::vector<uint32_t> attr_widths(num_attrs, 1); + for (uint32_t i = 0; i < num_attrs; ++i) { + std::regex var_decl(R"(^\s*%in_attr_)" + std::to_string(i) + + R"(\s*=\s*OpVariable\s+(%\S+)\s+Input\s*$)", + kMultilineRegex); + std::smatch m; + if (std::regex_search(source, m, var_decl)) { + std::string ptr_type = m[1]; + std::regex ptr_re(R"(^\s*)" + ptr_type + R"(\s*=\s*OpTypePointer\s+Input\s+(%\S+)\s*$)", + kMultilineRegex); + if (std::regex_search(source, m, ptr_re)) { + std::string data_type = m[1]; + std::regex vec_re(R"(^\s*)" + data_type + + R"(\s*=\s*OpTypeVector\s+%float\s+(\d+)\s*$)", + kMultilineRegex); + if (std::regex_search(source, m, vec_re)) { + attr_widths[i] = std::stoi(m[1]); + } else { + attr_widths[i] = 1; + } + } + } + } ``` _🎯 Functional Correctness_ | _🟠 Major_ | _⚡ Quick win_ **Attribute widths assume contiguous `%in_attr_N` indices.** Line 261 sizes `attr_widths` by `num_attrs`, and the loop at line 262 probes `%in_attr_0` through `%in_attr_{num_attrs-1}`. The set of indices actually found comes from `attr_indices`, which is sorted but never checked for contiguity. If the source declares `%in_attr_0` and `%in_attr_2`, `num_attrs` is 2, `%in_attr_1` is not found so `attr_widths[1]` keeps the default 1, and `%in_attr_2` receives no `OpStore` at all. The capture pass then reads an uninitialized attribute. The vertex-buffer guard in `perVertexPrototypeDraw.inc` checks `input.attr_indices[i] == i`, but that constrains buffer slots, not the shader-side `%in_attr_N` numbering. Reject the shader when `attr_indices` is not exactly `0..num_attrs-1`. <details> <summary>🛡️ Proposed guard</summary> ```diff std::sort(attr_indices.begin(), attr_indices.end()); uint32_t num_attrs = static_cast<uint32_t>(attr_indices.size()); + for (uint32_t i = 0; i < num_attrs; ++i) { + if (attr_indices[i] != static_cast<int>(i)) return {}; + } uint32_t output_stride = layout.record_stride_vec4; ``` </details> <!-- fingerprinting:phantom:medusa:komodo --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:ed3f43a5a1efa96737775807 --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -0,0 +513,4 @@
}
if (l == "OpReturn" || l == " OpReturn") {
out_lines.insert(out_lines.end(), end.begin(), end.end());
}
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-19 20:41 UTC · original · edited 2026-09-20 11:34 UTC

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '236,515p' src/graphics/host_gpu/renderer/perVertexTransform.cpp
rg -n 'Disassemble|OpFunction|OpReturn' src/graphics/host_gpu/renderer/perVertexPrototype.cpp tests/PerVertexGpuExecutionTests.cpp tests/PerVertexTransformTests.cpp

Repository: KytyPS5/KytyPS5

Length of output: 14116


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- disassembly call and surrounding production path ---'
sed -n '150,230p' src/graphics/host_gpu/renderer/perVertexPrototype.cpp
printf '%s\n' '--- Disassemble declarations/definitions and options ---'
rg -n -C 4 'Disassemble\s*\(' src include tests CMakeLists.txt 2>/dev/null | head -240
printf '%s\n' '--- transformation callers and related helpers ---'
rg -n -C 3 'LowerVertexToCompute|CompleteEntryPointInterface|OpFunctionCall|OpFunctionEnd|OpReturn(Value)?' src/graphics/host_gpu/renderer tests/PerVertexGpuExecutionTests.cpp tests/PerVertexTransformTests.cpp
printf '%s\n' '--- relevant test shader text with line numbers ---'
sed -n '720,835p' tests/PerVertexGpuExecutionTests.cpp
printf '%s\n' '--- all repository-local disassembly option usage ---'
rg -n -C 2 'SPV_BINARY_TO_TEXT_OPTION_(INDENT|FRIENDLY_NAMES)|SPV_BINARY_TO_TEXT_OPTION' .

Repository: KytyPS5/KytyPS5

Length of output: 31410


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- tracked SPIR-V tooling and fixtures ---'
git ls-files | rg '(^|/)(spirv|SPIR-V|shader|shaders|.*spv.*)' | head -240
printf '%s\n' '--- repository-local function declarations in SPIR-V text ---'
rg -n -U '(^|\n)\s*%\S+\s*=\s*OpFunction\b|(^|\n)\s*OpFunction\b' --glob '*.{cpp,h,hpp,txt,spvasm,asm}' . | head -240
printf '%s\n' '--- available SPIR-V disassembler source or headers ---'
rg -n -C 3 'SPV_BINARY_TO_TEXT_OPTION_INDENT|class SpirvTools|Disassemble\(.*uint32|Disassemble\(' third_party external src include 2>/dev/null | head -300
printf '%s\n' '--- all LowerVertexToCompute tests and nearby assertions ---'
rg -n -C 5 'LowerVertexToCompute|assemble capture compute|ValidateSpirv|cap_dis' tests/PerVertexGpuExecutionTests.cpp tests/PerVertexTransformTests.cpp

Repository: KytyPS5/KytyPS5

Length of output: 14346


Scope capture setup and epilogue to main_name.

LowerVertexToCompute inserts start after the first OpLabel and end before every matching OpReturn. If the module contains a helper function, capture instructions can be inserted into that helper. The transformed module can then use function-local IDs across functions and fail assembly or validation. If the helper appears first, main_name can also receive no start block.

Track the enclosing entry function and require that state for both start and end insertion.

🐛 Proposed fix to scope setup and epilogue to the entry function
 	std::vector<std::string> out_lines;
 	bool annotations_done = false, declarations_done = false, entry_label = false,
 	     start_done = false;
+	bool in_entry_function = false;
 	for (const auto& l: lines) {
 		if (!annotations_done && (l.find("= OpType") != std::string::npos ||
 		                          l.find("= OpConstant") != std::string::npos)) {
 			out_lines.insert(out_lines.end(), annotations.begin(), annotations.end());
 			annotations_done = true;
 		}
 		if (!declarations_done && l.find("= OpFunction ") != std::string::npos) {
 			out_lines.insert(out_lines.end(), declarations.begin(), declarations.end());
 			declarations_done = true;
 		}
-		if (entry_label && !start_done && l.find("= OpVariable ") == std::string::npos) {
+		if (l.find(main_name + " = OpFunction ") != std::string::npos) {
+			in_entry_function = true;
+		}
+		if (l.find("OpFunctionEnd") != std::string::npos) {
+			in_entry_function = false;
+		}
+		if (in_entry_function && entry_label && !start_done &&
+		    l.find("= OpVariable ") == std::string::npos) {
 			out_lines.insert(out_lines.end(), start.begin(), start.end());
 			start_done = true;
 		}
-		if (declarations_done && l.find("= OpLabel") != std::string::npos) {
+		if (in_entry_function && declarations_done && l.find("= OpLabel") != std::string::npos) {
 			entry_label = true;
 		}
-		if (l == "OpReturn" || l == "               OpReturn") {
+		if (in_entry_function && l.find("OpReturn") != std::string::npos &&
+		    l.find("OpReturnValue") == std::string::npos) {
 			out_lines.insert(out_lines.end(), end.begin(), end.end());
 		}
 		out_lines.push_back(l);
 	}

✅ Addressed in commit 7fe93a8

**@⁠coderabbitai[bot]** on GitHub · 2026-09-19 20:41 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/715#discussion_r4054644828) · edited 2026-09-20 11:34 UTC _🎯 Functional Correctness_ | _🟠 Major_ | _⚡ Quick win_ <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash sed -n '236,515p' src/graphics/host_gpu/renderer/perVertexTransform.cpp rg -n 'Disassemble|OpFunction|OpReturn' src/graphics/host_gpu/renderer/perVertexPrototype.cpp tests/PerVertexGpuExecutionTests.cpp tests/PerVertexTransformTests.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 14116 --- 🏁 Script executed: ```bash #!/bin/bash set -e printf '%s\n' '--- disassembly call and surrounding production path ---' sed -n '150,230p' src/graphics/host_gpu/renderer/perVertexPrototype.cpp printf '%s\n' '--- Disassemble declarations/definitions and options ---' rg -n -C 4 'Disassemble\s*\(' src include tests CMakeLists.txt 2>/dev/null | head -240 printf '%s\n' '--- transformation callers and related helpers ---' rg -n -C 3 'LowerVertexToCompute|CompleteEntryPointInterface|OpFunctionCall|OpFunctionEnd|OpReturn(Value)?' src/graphics/host_gpu/renderer tests/PerVertexGpuExecutionTests.cpp tests/PerVertexTransformTests.cpp printf '%s\n' '--- relevant test shader text with line numbers ---' sed -n '720,835p' tests/PerVertexGpuExecutionTests.cpp printf '%s\n' '--- all repository-local disassembly option usage ---' rg -n -C 2 'SPV_BINARY_TO_TEXT_OPTION_(INDENT|FRIENDLY_NAMES)|SPV_BINARY_TO_TEXT_OPTION' . ``` Repository: KytyPS5/KytyPS5 Length of output: 31410 --- 🏁 Script executed: ```bash #!/bin/bash set -e printf '%s\n' '--- tracked SPIR-V tooling and fixtures ---' git ls-files | rg '(^|/)(spirv|SPIR-V|shader|shaders|.*spv.*)' | head -240 printf '%s\n' '--- repository-local function declarations in SPIR-V text ---' rg -n -U '(^|\n)\s*%\S+\s*=\s*OpFunction\b|(^|\n)\s*OpFunction\b' --glob '*.{cpp,h,hpp,txt,spvasm,asm}' . | head -240 printf '%s\n' '--- available SPIR-V disassembler source or headers ---' rg -n -C 3 'SPV_BINARY_TO_TEXT_OPTION_INDENT|class SpirvTools|Disassemble\(.*uint32|Disassemble\(' third_party external src include 2>/dev/null | head -300 printf '%s\n' '--- all LowerVertexToCompute tests and nearby assertions ---' rg -n -C 5 'LowerVertexToCompute|assemble capture compute|ValidateSpirv|cap_dis' tests/PerVertexGpuExecutionTests.cpp tests/PerVertexTransformTests.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 14346 --- </details> **Scope capture setup and epilogue to `main_name`.** `LowerVertexToCompute` inserts `start` after the first `OpLabel` and `end` before every matching `OpReturn`. If the module contains a helper function, capture instructions can be inserted into that helper. The transformed module can then use function-local IDs across functions and fail assembly or validation. If the helper appears first, `main_name` can also receive no `start` block. Track the enclosing entry function and require that state for both `start` and `end` insertion. <details> <summary>🐛 Proposed fix to scope setup and epilogue to the entry function</summary> ```diff std::vector<std::string> out_lines; bool annotations_done = false, declarations_done = false, entry_label = false, start_done = false; + bool in_entry_function = false; for (const auto& l: lines) { if (!annotations_done && (l.find("= OpType") != std::string::npos || l.find("= OpConstant") != std::string::npos)) { out_lines.insert(out_lines.end(), annotations.begin(), annotations.end()); annotations_done = true; } if (!declarations_done && l.find("= OpFunction ") != std::string::npos) { out_lines.insert(out_lines.end(), declarations.begin(), declarations.end()); declarations_done = true; } - if (entry_label && !start_done && l.find("= OpVariable ") == std::string::npos) { + if (l.find(main_name + " = OpFunction ") != std::string::npos) { + in_entry_function = true; + } + if (l.find("OpFunctionEnd") != std::string::npos) { + in_entry_function = false; + } + if (in_entry_function && entry_label && !start_done && + l.find("= OpVariable ") == std::string::npos) { out_lines.insert(out_lines.end(), start.begin(), start.end()); start_done = true; } - if (declarations_done && l.find("= OpLabel") != std::string::npos) { + if (in_entry_function && declarations_done && l.find("= OpLabel") != std::string::npos) { entry_label = true; } - if (l == "OpReturn" || l == " OpReturn") { + if (in_entry_function && l.find("OpReturn") != std::string::npos && + l.find("OpReturnValue") == std::string::npos) { out_lines.insert(out_lines.end(), end.begin(), end.end()); } out_lines.push_back(l); } ``` </details> <!-- fingerprinting:phantom:medusa:quokka --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:a80c0ed88b651f991b5444a6 --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commit 7fe93a8
@ -1042,0 +1053,4 @@
primitive_restart_enable);
return;
}
}
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-19 20:41 UTC · original

🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

🔎 Supported by static analysis

🏁 Script executed:

sed -n '1050,1090p' src/graphics/host_gpu/renderer/renderDraw.cpp
sed -n '1,45p' src/graphics/host_gpu/renderer/perVertexPrototypeDraw.inc
sed -n '157,240p' src/graphics/host_gpu/renderer/perVertexPrototype.cpp
rg -n '`#define` EXIT_IF|void EXIT_IF|EXIT_IF\(' src/common src | head -30

Repository: KytyPS5/KytyPS5

Length of output: 10963


🏁 Script executed:

rg -n --glob '*.{h,hpp,inc,cpp,cxx}' '`#define`[[:space:]]+EXIT_IF|EXIT_IF[[:space:]]*\(' src/graphics/host_gpu src/common src | head -80
sed -n '157,280p' src/graphics/host_gpu/renderer/perVertexPrototype.cpp
nl -ba src/graphics/host_gpu/renderer/perVertexPrototypeDraw.inc | sed -n '1,42p'
nl -ba src/graphics/host_gpu/renderer/renderDraw.cpp | sed -n '1065,1085p'

Repository: KytyPS5/KytyPS5

Length of output: 17899


🏁 Script executed:

#!/bin/bash
set -o pipefail
files=$(rg -l --hidden --glob '!build/**' --glob '!dist/**' '#[[:space:]]*define[[:space:]]+EXIT_IF([[:space:]]|\()' . || true)
printf '%s\n' "$files"
if [ -n "$files" ]; then
  rg -n '#[[:space:]]*define[[:space:]]+EXIT_IF([[:space:]]|\()' $files
fi
nl -ba src/graphics/host_gpu/renderer/perVertexPrototype.cpp | sed -n '300,370p'

Repository: KytyPS5/KytyPS5

Length of output: 1027


🏁 Script executed:

nl -ba src/common/assert.h | sed -n '28,44p'

Repository: KytyPS5/KytyPS5

Length of output: 983


Guard prototype eligibility before routing. ExecutePreparedDraw selects ExecutePerVertexPrototype when the vertex stage is logical Vertex and GetPerVertexPrototypePrograms returns a program. The cached shader pair can then be used by a draw that fails the prototype's checks, including non-eTriangleList topology, primitive restart, multiple vertex buffers, unsupported attributes, or a vertex-instance count above 65535. In non-KYTY_FINAL builds, those checks call EXIT_IF, which invokes the exit handler instead of allowing the standard draw path. In KYTY_FINAL builds, EXIT_IF is disabled, so the prototype path receives unsupported input without these guards. Move the reusable eligibility checks into a boolean predicate and route to the prototype only when it returns true. Keep the EXIT_IF checks in ExecutePerVertexPrototype as defensive checks.

🐛 Proposed structure for the routing decision
 	if (state.vertex_info[0].logical_stage == ShaderType::Vertex) {
-		if (const auto* prototype = GetPerVertexPrototypePrograms(
-		        m_context.GetGraphics(), state.programs, state.vertex_info[0],
-		        m_context.GetPipelineCache().DriverCache())) {
+		if (CanExecutePerVertexPrototype(draw, state, topology, primitive_restart_enable) &&
+		    GetPerVertexPrototypePrograms(m_context.GetGraphics(), state.programs,
+		                                  state.vertex_info[0],
+		                                  m_context.GetPipelineCache().DriverCache()) != nullptr) {
 			ExecutePerVertexPrototype(submit_id, buffer, draw, state, topology, emit, index_source,
 			                          primitive_restart_enable);
 			return;
 		}
 	}

CanExecutePerVertexPrototype should contain the draw-dependent checks currently written as EXIT_IF in perVertexPrototypeDraw.inc lines 11-34 and return false when a check fails.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

	if (state.vertex_info[0].logical_stage == ShaderType::Vertex) {
		if (CanExecutePerVertexPrototype(draw, state, topology, primitive_restart_enable) &&
		    GetPerVertexPrototypePrograms(m_context.GetGraphics(), state.programs,
		                                  state.vertex_info[0],
		                                  m_context.GetPipelineCache().DriverCache()) != nullptr) {
			ExecutePerVertexPrototype(submit_id, buffer, draw, state, topology, emit, index_source,
			                          primitive_restart_enable);
			return;
		}
	}
**@⁠coderabbitai[bot]** on GitHub · 2026-09-19 20:41 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/715#discussion_r4054644829) _🩺 Stability & Availability_ | _🟠 Major_ | _🏗️ Heavy lift_ <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash sed -n '1050,1090p' src/graphics/host_gpu/renderer/renderDraw.cpp sed -n '1,45p' src/graphics/host_gpu/renderer/perVertexPrototypeDraw.inc sed -n '157,240p' src/graphics/host_gpu/renderer/perVertexPrototype.cpp rg -n '`#define` EXIT_IF|void EXIT_IF|EXIT_IF\(' src/common src | head -30 ``` Repository: KytyPS5/KytyPS5 Length of output: 10963 --- 🏁 Script executed: ```bash rg -n --glob '*.{h,hpp,inc,cpp,cxx}' '`#define`[[:space:]]+EXIT_IF|EXIT_IF[[:space:]]*\(' src/graphics/host_gpu src/common src | head -80 sed -n '157,280p' src/graphics/host_gpu/renderer/perVertexPrototype.cpp nl -ba src/graphics/host_gpu/renderer/perVertexPrototypeDraw.inc | sed -n '1,42p' nl -ba src/graphics/host_gpu/renderer/renderDraw.cpp | sed -n '1065,1085p' ``` Repository: KytyPS5/KytyPS5 Length of output: 17899 --- 🏁 Script executed: ```bash #!/bin/bash set -o pipefail files=$(rg -l --hidden --glob '!build/**' --glob '!dist/**' '#[[:space:]]*define[[:space:]]+EXIT_IF([[:space:]]|\()' . || true) printf '%s\n' "$files" if [ -n "$files" ]; then rg -n '#[[:space:]]*define[[:space:]]+EXIT_IF([[:space:]]|\()' $files fi nl -ba src/graphics/host_gpu/renderer/perVertexPrototype.cpp | sed -n '300,370p' ``` Repository: KytyPS5/KytyPS5 Length of output: 1027 --- 🏁 Script executed: ```bash nl -ba src/common/assert.h | sed -n '28,44p' ``` Repository: KytyPS5/KytyPS5 Length of output: 983 --- </details> **Guard prototype eligibility before routing.** `ExecutePreparedDraw` selects `ExecutePerVertexPrototype` when the vertex stage is logical `Vertex` and `GetPerVertexPrototypePrograms` returns a program. The cached shader pair can then be used by a draw that fails the prototype's checks, including non-`eTriangleList` topology, primitive restart, multiple vertex buffers, unsupported attributes, or a vertex-instance count above `65535`. In non-`KYTY_FINAL` builds, those checks call `EXIT_IF`, which invokes the exit handler instead of allowing the standard draw path. In `KYTY_FINAL` builds, `EXIT_IF` is disabled, so the prototype path receives unsupported input without these guards. Move the reusable eligibility checks into a boolean predicate and route to the prototype only when it returns `true`. Keep the `EXIT_IF` checks in `ExecutePerVertexPrototype` as defensive checks. <details> <summary>🐛 Proposed structure for the routing decision</summary> ```diff if (state.vertex_info[0].logical_stage == ShaderType::Vertex) { - if (const auto* prototype = GetPerVertexPrototypePrograms( - m_context.GetGraphics(), state.programs, state.vertex_info[0], - m_context.GetPipelineCache().DriverCache())) { + if (CanExecutePerVertexPrototype(draw, state, topology, primitive_restart_enable) && + GetPerVertexPrototypePrograms(m_context.GetGraphics(), state.programs, + state.vertex_info[0], + m_context.GetPipelineCache().DriverCache()) != nullptr) { ExecutePerVertexPrototype(submit_id, buffer, draw, state, topology, emit, index_source, primitive_restart_enable); return; } } ``` `CanExecutePerVertexPrototype` should contain the draw-dependent checks currently written as `EXIT_IF` in `perVertexPrototypeDraw.inc` lines 11-34 and return `false` when a check fails. </details> <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion if (state.vertex_info[0].logical_stage == ShaderType::Vertex) { if (CanExecutePerVertexPrototype(draw, state, topology, primitive_restart_enable) && GetPerVertexPrototypePrograms(m_context.GetGraphics(), state.programs, state.vertex_info[0], m_context.GetPipelineCache().DriverCache()) != nullptr) { ExecutePerVertexPrototype(submit_id, buffer, draw, state, topology, emit, index_source, primitive_restart_enable); return; } } ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:quokka --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:8b8accd5fe16fce1e86b6e49 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-19 20:41 UTC · original · reviewed

Actionable comments posted: 8

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (1)

🟡 Minor · Keep m_driver_cache alive after periodic saves. · pipelineCache.cpp:560-561

src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp:560-561
🚀 Performance & Scalability | 🟡 Minor | ⚡ Quick win

Keep m_driver_cache alive after periodic saves. SaveInternalLocked() runs from both periodic pipeline paths. After a successful write, it destroys and nulls m_driver_cache. Later pipeline creation passes nullptr to CreatePipelineInternal, and DriverCache() consumers receive no cache. Later saves return immediately, so pipelines created after the first successful periodic save are not added to the persisted cache. Remove the teardown from SaveInternalLocked() and keep destruction in PipelineCache::~PipelineCache. Do not move shutdown destruction into public Save().

🐛 Proposed fix
 	PipelineCacheLog("Vulkan pipeline cache: saved {} bytes to {}", payload.size(),
 	                 Common::PathToString(m_driver_cache_path));
-	m_graphics.device.destroyPipelineCache(m_driver_cache, nullptr);
-	m_driver_cache = nullptr;
 }

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml

Review profile: CHILL

Plan: Advanced

Run ID: 077e0695-fdc9-4a07-8313-b1eeecba40bf

📥 Commits

Reviewing files that changed from the base of the PR and between f100f785da and dd958d02ba.

📒 Files selected for processing (21)
  • .github/workflows/build.yml
  • CMakeLists.txt
  • src/common/threads.cpp
  • src/common/threads.h
  • src/generate_version.cmake
  • src/graphics/host_gpu/renderer/perVertexEmbeddedSpv.h
  • src/graphics/host_gpu/renderer/perVertexPrototype.cpp
  • src/graphics/host_gpu/renderer/perVertexPrototype.h
  • src/graphics/host_gpu/renderer/perVertexPrototypeDraw.inc
  • src/graphics/host_gpu/renderer/perVertexTransform.cpp
  • src/graphics/host_gpu/renderer/perVertexTransform.h
  • src/graphics/host_gpu/renderer/pipeline/descriptors.cpp
  • src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp
  • src/graphics/host_gpu/renderer/pipeline/pipelineCache.h
  • src/graphics/host_gpu/renderer/pipeline/shaders.cpp
  • src/graphics/host_gpu/renderer/render.h
  • src/graphics/host_gpu/renderer/renderDraw.cpp
  • src/kytyGitVersion.h.in
  • tests/PerVertexGpuExecutionTests.cpp
  • tests/PerVertexTransformTests.cpp
  • tests/shaderCfgTests.cpp

Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-19 20:41 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/715#pullrequestreview-5257580540) · **reviewed** **Actionable comments posted: 8** > [!CAUTION] > Some comments are outside the diff and can’t be posted inline due to GitHub limitations. > > **⚠️ Outside diff range comments (1)** > > <details> > <summary><em>🟡 Minor</em> · Keep <code>m_driver_cache</code> alive after periodic saves. · <code>pipelineCache.cpp:560-561</code></summary><blockquote> > > `src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp:560-561` > _🚀 Performance & Scalability_ | _🟡 Minor_ | _⚡ Quick win_ > > **Keep `m_driver_cache` alive after periodic saves.** `SaveInternalLocked()` runs from both periodic pipeline paths. After a successful write, it destroys and nulls `m_driver_cache`. Later pipeline creation passes `nullptr` to `CreatePipelineInternal`, and `DriverCache()` consumers receive no cache. Later saves return immediately, so pipelines created after the first successful periodic save are not added to the persisted cache. Remove the teardown from `SaveInternalLocked()` and keep destruction in `PipelineCache::~PipelineCache`. Do not move shutdown destruction into public `Save()`. > > <details> > <summary>🐛 Proposed fix</summary> > > ```diff > PipelineCacheLog("Vulkan pipeline cache: saved {} bytes to {}", payload.size(), > Common::PathToString(m_driver_cache_path)); > - m_graphics.device.destroyPipelineCache(m_driver_cache, nullptr); > - m_driver_cache = nullptr; > } > ``` > > </details> > > <!-- cr-comment:v1:e23067e82792190cf2243330 --> > > </blockquote></details> --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml **Review profile**: CHILL **Plan**: Advanced **Run ID**: `077e0695-fdc9-4a07-8313-b1eeecba40bf` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between f100f785dafa108bbf5b40ea8e425e08236f981a and dd958d02ba2981ff30a6a6d4a2c28a36ba8ae6d6. </details> <details> <summary>📒 Files selected for processing (21)</summary> * `.github/workflows/build.yml` * `CMakeLists.txt` * `src/common/threads.cpp` * `src/common/threads.h` * `src/generate_version.cmake` * `src/graphics/host_gpu/renderer/perVertexEmbeddedSpv.h` * `src/graphics/host_gpu/renderer/perVertexPrototype.cpp` * `src/graphics/host_gpu/renderer/perVertexPrototype.h` * `src/graphics/host_gpu/renderer/perVertexPrototypeDraw.inc` * `src/graphics/host_gpu/renderer/perVertexTransform.cpp` * `src/graphics/host_gpu/renderer/perVertexTransform.h` * `src/graphics/host_gpu/renderer/pipeline/descriptors.cpp` * `src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp` * `src/graphics/host_gpu/renderer/pipeline/pipelineCache.h` * `src/graphics/host_gpu/renderer/pipeline/shaders.cpp` * `src/graphics/host_gpu/renderer/render.h` * `src/graphics/host_gpu/renderer/renderDraw.cpp` * `src/kytyGitVersion.h.in` * `tests/PerVertexGpuExecutionTests.cpp` * `tests/PerVertexTransformTests.cpp` * `tests/shaderCfgTests.cpp` </details> **Included review availability:** Your plan provides up to 10 included reviews per hour; 8 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
Author
Owner

@⁠carbonimax on GitHub · 2026-09-20 02:34 UTC · original

Follow-up 7d17838 adds the exact PerVertex input format observed in the game: 0x47 (k16_16_16_16Float), four 16-bit components at attribute offset 20 with stride 28.

The change keeps the scope to Float16 only, generates the unpack SPIR-V from checked-in GLSL, and covers signed zero, subnormal, normal, infinity, and NaN conversion on CPU plus finite Float16 fixtures on MoltenVK.

Validation on an isolated checkout of this PR:

  • Release x86_64 build: kyty_emulator, shader_cfg_tests, scalar_provenance_tests, per_vertex_gpu_execution_tests
  • CPU suites: passed
  • MoltenVK GPU suite: passed
  • spirv-val --target-env vulkan1.2: passed

A bounded integration run reached GPU completion of the first PerVertex draw without DeviceLost. That runtime proof also included other open integration changes, so it does not by itself qualify this PR in isolation. The black screen remains and the later subgroup-function failure is a separate issue.

**@⁠carbonimax** on GitHub · 2026-09-20 02:34 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/715#issuecomment-5747076368) Follow-up `7d17838` adds the exact PerVertex input format observed in the game: `0x47` (`k16_16_16_16Float`), four 16-bit components at attribute offset 20 with stride 28. The change keeps the scope to Float16 only, generates the unpack SPIR-V from checked-in GLSL, and covers signed zero, subnormal, normal, infinity, and NaN conversion on CPU plus finite Float16 fixtures on MoltenVK. Validation on an isolated checkout of this PR: - Release x86_64 build: `kyty_emulator`, `shader_cfg_tests`, `scalar_provenance_tests`, `per_vertex_gpu_execution_tests` - CPU suites: passed - MoltenVK GPU suite: passed - `spirv-val --target-env vulkan1.2`: passed A bounded integration run reached GPU completion of the first PerVertex draw without DeviceLost. That runtime proof also included other open integration changes, so it does not by itself qualify this PR in isolation. The black screen remains and the later subgroup-function failure is a separate issue.
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-20 20:24 UTC · original · reviewed

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml

Review profile: CHILL

Plan: Advanced

Run ID: dbe9c80f-b114-483a-8d47-8244e1eedbc7

📥 Commits

Reviewing files that changed from the base of the PR and between 7fe93a8f09 and 548553ae5c.

📒 Files selected for processing (12)
  • .github/workflows/build.yml
  • CMakeLists.txt
  • src/common/threads.h
  • src/graphics/host_gpu/renderer/perVertexPrototypeDraw.inc
  • src/graphics/host_gpu/renderer/perVertexTransform.cpp
  • src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp
  • src/graphics/host_gpu/renderer/pipeline/pipelineCache.h
  • src/graphics/host_gpu/renderer/render.h
  • src/graphics/host_gpu/renderer/renderDraw.cpp
  • tests/PerVertexGpuExecutionTests.cpp
  • tests/PerVertexTransformTests.cpp
  • tests/shaderCfgTests.cpp

Included review availability: Your plan provides up to 10 included reviews per hour; 7 remain after this review.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-20 20:24 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/715#pullrequestreview-5261648477) · **reviewed** **Actionable comments posted: 1** --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml **Review profile**: CHILL **Plan**: Advanced **Run ID**: `dbe9c80f-b114-483a-8d47-8244e1eedbc7` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 7fe93a8f0970a4ac0ee949716b045befdd13cfe5 and 548553ae5cb3ed2efeefcccae88d7670860c95b5. </details> <details> <summary>📒 Files selected for processing (12)</summary> * `.github/workflows/build.yml` * `CMakeLists.txt` * `src/common/threads.h` * `src/graphics/host_gpu/renderer/perVertexPrototypeDraw.inc` * `src/graphics/host_gpu/renderer/perVertexTransform.cpp` * `src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp` * `src/graphics/host_gpu/renderer/pipeline/pipelineCache.h` * `src/graphics/host_gpu/renderer/render.h` * `src/graphics/host_gpu/renderer/renderDraw.cpp` * `tests/PerVertexGpuExecutionTests.cpp` * `tests/PerVertexTransformTests.cpp` * `tests/shaderCfgTests.cpp` </details> **Included review availability:** Your plan provides up to 10 included reviews per hour; 7 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-20 20:24 UTC · original
On src/graphics/host_gpu/renderer/perVertexTransform.cpp line 423 (outdated):

@@ -0,0 +1,972 @@
+#include "graphics/host_gpu/renderer/perVertexTransform.h"
+
+#include "common/file.h"
+#include "common/threads.h"
+#include "kytyGitVersion.h"
+
+#include <algorithm>
+#include <atomic>
+#include <cstdint>
+#include <cstring>
+#include <fmt/format.h>
+#include <map>
+#include <regex>
+#include <set>
+#include <spirv/unified1/spirv.hpp>
+#include <sstream>
+#include <string>
+#include <vector>
+#include <xxhash.h>
+
+namespace Libs::Graphics {
+
+// Older MSVC STL always matches ^/$ at line boundaries, but has no multiline
+// flag. The macro arrived with the implementation of the standard option.
+#if defined(_MSVC_STL_VERSION) && !defined(_REGEX_LEGACY_MULTILINE_MODE)
+static constexpr auto kMultilineRegex = std::regex_constants::ECMAScript;
+#else
+static constexpr auto kMultilineRegex =
+    std::regex_constants::ECMAScript | std::regex_constants::multiline;
+#endif
+
+// The transformed modules are assembled as SPIR-V 1.5. Since 1.4, the entry
+// interface must include all used globals, including resources and Private I/O.
+// Source shaders can be 1.3, whose interfaces only list Input/Output variables.
+static std::string CompleteEntryPointInterface(const std::string& source) {
+	std::istringstream lines(source);
+	std::string        line, interfaces;
+	while (std::getline(lines, line)) {
+		std::istringstream tokens(line);
+		std::string        id, equals, opcode;
+		tokens >> id >> equals >> opcode;
+		if (opcode == "OpFunction") break;
+		if (equals == "=" && opcode == "OpVariable") interfaces += " " + id;
+	}
+	const std::regex entry_re(R"((OpEntryPoint\s+\S+\s+%\S+\s+"[^"]*")[^\r\n]*)");
+	return std::regex_replace(source, entry_re, "$1" + interfaces);
+}
+
+bool DerivePerVertexLayout(const std::string& vs_source, const std::string& ps_source,
+                           PerVertexLayout&                 layout,
+                           std::map<uint32_t, std::string>& vs_param_vars) {
+	std::regex var_re(R"(^\s*(%\S+)\s*=\s*OpVariable\s+%\S+\s+Output\s*$)", kMultilineRegex);
+	std::set<std::string> vs_outputs;
+	for (auto it = std::sregex_iterator(vs_source.begin(), vs_source.end(), var_re);
+	     it != std::sregex_iterator(); ++it) {
+		vs_outputs.insert((*it)[1]);
+	}
+	if (vs_outputs.empty()) return false;
+
+	bool has_clip = vs_outputs.find("%gl_ClipDistance") != vs_outputs.end();
+
+	vs_param_vars.clear();
+	for (const auto& var: vs_outputs) {
+		if (var == "%outPerVertex" || var == "%gl_ClipDistance" || var == "%gl_PointSize") continue;
+		std::regex  loc_re(R"(^\s*OpDecorate\s+)" + var + R"(\s+Location\s+(\d+)\s*$)",
+		                   kMultilineRegex);
+		std::smatch m;
+		if (std::regex_search(vs_source, m, loc_re)) {
+			uint32_t loc       = static_cast<uint32_t>(std::stoul(m[1]));
+			vs_param_vars[loc] = var;
+		}
+	}
+
+	layout.has_clip   = has_clip;
+	layout.num_params = static_cast<uint32_t>(vs_param_vars.size());
+	layout.param_locations_and_slots.clear();
+	layout.location_to_slot.clear();
+
+	uint32_t current_slot = 1;
+	for (const auto& [loc, var_name]: vs_param_vars) {
+		layout.location_to_slot[loc] = current_slot;
+		layout.param_locations_and_slots.push_back({loc, current_slot});
+		current_slot++;
+	}
+
+	if (has_clip) {
+		layout.clip_slot          = current_slot;
+		layout.record_stride_vec4 = current_slot + 1;
+	} else {
+		layout.clip_slot          = UINT32_MAX;
+		layout.record_stride_vec4 = current_slot;
+	}
+	if (layout.location_to_slot.find(31) != layout.location_to_slot.end()) {
+		return false;
+	}
+
+	std::regex pv_re(R"(^\s*OpDecorate\s+(%\S+)\s+PerVertexKHR\s*$)", kMultilineRegex);
+	std::vector<std::string> pv_vars;
+	for (auto it = std::sregex_iterator(ps_source.begin(), ps_source.end(), pv_re);
+	     it != std::sregex_iterator(); ++it) {
+		pv_vars.push_back((*it)[1]);
+	}
+	if (pv_vars.empty()) return false;
+
+	for (const auto& pv_var: pv_vars) {
+		std::regex  loc_re(R"(^\s*OpDecorate\s+)" + pv_var + R"(\s+Location\s+(\d+)\s*$)",
+		                   kMultilineRegex);
+		std::smatch m;
+		if (!std::regex_search(ps_source, m, loc_re)) {
+			return false;
+		}
+		uint32_t loc = static_cast<uint32_t>(std::stoul(m[1]));
+		auto     it  = layout.location_to_slot.find(loc);
+		if (it == layout.location_to_slot.end()) {
+			return false;
+		}
+		uint32_t slot = it->second;
+		if (slot >= layout.clip_slot) {
+			return false;
+		}
+		if (slot >= layout.record_stride_vec4) {
+			return false;
+		}
+	}
+	return true;
+}
+
+std::string GenerateReplayVertexSpvasm(const PerVertexLayout& layout) {
+	std::vector<std::string> entry_interfaces = {"%gl_VertexIndex", "%_", "%capture_output"};
+	for (const auto& [loc, _]: layout.param_locations_and_slots) {
+		entry_interfaces.push_back("%out_param_" + std::to_string(loc));
+	}
+	entry_interfaces.push_back("%out_primitive_id");
+
+	std::string entry_iface_str;
+	for (size_t i = 0; i < entry_interfaces.size(); ++i) {
+		if (i > 0) entry_iface_str += " ";
+		entry_iface_str += entry_interfaces[i];
+	}
+
+	std::ostringstream ss;
+	ss << "OpCapability Shader\n";
+	if (layout.has_clip) {
+		ss << "OpCapability ClipDistance\n";
+	}
+	ss << "OpMemoryModel Logical GLSL450\n";
+	ss << "OpEntryPoint Vertex %main \"main\" " << entry_iface_str << "\n";
+	ss << "OpDecorate %gl_VertexIndex BuiltIn VertexIndex\n";
+	ss << "OpDecorate %gl_PerVertex Block\n";
+	ss << "OpMemberDecorate %gl_PerVertex 0 BuiltIn Position\n";
+	ss << "OpMemberDecorate %gl_PerVertex 1 BuiltIn PointSize\n";
+	if (layout.has_clip) {
+		ss << "OpMemberDecorate %gl_PerVertex 2 BuiltIn ClipDistance\n";
+	}
+	ss << "OpDecorate %_runtimearr_v4float ArrayStride 16\n";
+	ss << "OpDecorate %CaptureOutput Block\n";
+	ss << "OpMemberDecorate %CaptureOutput 0 NonWritable\n";
+	ss << "OpMemberDecorate %CaptureOutput 0 Offset 0\n";
+	ss << "OpDecorate %capture_output NonWritable\n";
+	ss << "OpDecorate %capture_output Binding 1\n";
+	ss << "OpDecorate %capture_output DescriptorSet 1\n";
+	for (const auto& [loc, _]: layout.param_locations_and_slots) {
+		ss << "OpDecorate %out_param_" << loc << " Location " << loc << "\n";
+	}
+	ss << "OpDecorate %out_primitive_id Flat\n";
+	ss << "OpDecorate %out_primitive_id Location 31\n";
+	ss << "%void = OpTypeVoid\n";
+	ss << "%fn = OpTypeFunction %void\n";
+	ss << "%uint = OpTypeInt 32 0\n";
+	ss << "%int = OpTypeInt 32 1\n";
+	ss << "%float = OpTypeFloat 32\n";
+	ss << "%v4float = OpTypeVector %float 4\n";
+	ss << "%uint_0 = OpConstant %uint 0\n";
+	ss << "%uint_1 = OpConstant %uint 1\n";
+	ss << "%uint_3 = OpConstant %uint 3\n";
+	ss << "%int_0 = OpConstant %int 0\n";
+	ss << "%int_2 = OpConstant %int 2\n";
+	ss << "%stride_const = OpConstant %uint " << layout.record_stride_vec4 << "\n";
+	for (const auto& [loc, slot]: layout.param_locations_and_slots) {
+		ss << "%slot_const_" << slot << " = OpConstant %uint " << slot << "\n";
+	}
+	if (layout.has_clip) {
+		ss << "%clip_slot_const = OpConstant %uint " << layout.clip_slot << "\n";
+		ss << "%_arr_float_1 = OpTypeArray %float %uint_1\n";
+		ss << "%_ptr_StorageBuffer_float = OpTypePointer StorageBuffer %float\n";
+		ss << "%_ptr_Output_float = OpTypePointer Output %float\n";
+		ss << "%gl_PerVertex = OpTypeStruct %v4float %float %_arr_float_1\n";
+	} else {
+		ss << "%gl_PerVertex = OpTypeStruct %v4float %float\n";
+	}
+	ss << "%_ptr_Output_gl_PerVertex = OpTypePointer Output %gl_PerVertex\n";
+	ss << "%_ = OpVariable %_ptr_Output_gl_PerVertex Output\n";
+	ss << "%_ptr_Input_int = OpTypePointer Input %int\n";
+	ss << "%gl_VertexIndex = OpVariable %_ptr_Input_int Input\n";
+	ss << "%_runtimearr_v4float = OpTypeRuntimeArray %v4float\n";
+	ss << "%CaptureOutput = OpTypeStruct %_runtimearr_v4float\n";
+	ss << "%_ptr_StorageBuffer_CaptureOutput = OpTypePointer StorageBuffer %CaptureOutput\n";
+	ss << "%capture_output = OpVariable %_ptr_StorageBuffer_CaptureOutput StorageBuffer\n";
+	ss << "%_ptr_StorageBuffer_v4float = OpTypePointer StorageBuffer %v4float\n";
+	ss << "%_ptr_Output_v4float = OpTypePointer Output %v4float\n";
+	ss << "%_ptr_Output_uint = OpTypePointer Output %uint\n";
+	ss << "%out_primitive_id = OpVariable %_ptr_Output_uint Output\n";
+	for (const auto& [loc, _]: layout.param_locations_and_slots) {
+		ss << "%out_param_" << loc << " = OpVariable %_ptr_Output_v4float Output\n";
+	}
+
+	ss << "%main = OpFunction %void None %fn\n";
+	ss << "%label = OpLabel\n";
+	ss << "%vidx_i = OpLoad %int %gl_VertexIndex\n";
+	ss << "%vidx = OpBitcast %uint %vidx_i\n";
+	ss << "%base = OpIMul %uint %vidx %stride_const\n";
+	ss << "%pos_ptr = OpAccessChain %_ptr_StorageBuffer_v4float %capture_output %int_0 %base\n";
+	ss << "%pos_val = OpLoad %v4float %pos_ptr\n";
+	ss << "%out_pos_ptr = OpAccessChain %_ptr_Output_v4float %_ %int_0\n";
+	ss << "OpStore %out_pos_ptr %pos_val\n";
+	for (const auto& [loc, slot]: layout.param_locations_and_slots) {
+		ss << "%param_idx_" << slot << " = OpIAdd %uint %base %slot_const_" << slot << "\n";
+		ss << "%param_ptr_" << slot
+		   << " = OpAccessChain %_ptr_StorageBuffer_v4float %capture_output %int_0 %param_idx_"
+		   << slot << "\n";
+		ss << "%param_val_" << slot << " = OpLoad %v4float %param_ptr_" << slot << "\n";
+		ss << "OpStore %out_param_" << loc << " %param_val_" << slot << "\n";
+	}
+	if (layout.has_clip) {
+		ss << "%clip_idx = OpIAdd %uint %base %clip_slot_const\n";
+		ss << "%clip_src_ptr = OpAccessChain %_ptr_StorageBuffer_float %capture_output %int_0 "
+		      "%clip_idx %uint_0\n";
+		ss << "%clip_val = OpLoad %float %clip_src_ptr\n";
+		ss << "%clip_dst_ptr = OpAccessChain %_ptr_Output_float %_ %int_2 %uint_0\n";
+		ss << "OpStore %clip_dst_ptr %clip_val\n";
+	}
+	ss << "%primid = OpUDiv %uint %vidx %uint_3\n";
+	ss << "OpStore %out_primitive_id %primid\n";
+	ss << "OpReturn\n";
+	ss << "OpFunctionEnd\n";
+	return ss.str();
+}
+
+std::string LowerVertexToCompute(const std::string& source, const PerVertexLayout& layout,
+                                 const std::map<uint32_t, std::string>& vs_param_vars) {
+	std::regex            var_re(R"(^\s*(%\S+)\s*=\s*OpVariable\s+%\S+\s+(Input|Output)\s*$)",
+	                             kMultilineRegex);
+	std::set<std::string> inputs, outputs, attr_inputs;
+	for (auto it = std::sregex_iterator(source.begin(), source.end(), var_re);
+	     it != std::sregex_iterator(); ++it) {
+		std::string name    = (*it)[1];
+		std::string storage = (*it)[2];
+		if (storage == "Input") {
+			inputs.insert(name);
+			if (name.rfind("%in_attr_", 0) == 0) attr_inputs.insert(name);
+		} else {
+			outputs.insert(name);
+		}
+	}
+	std::vector<int> attr_indices;
+	for (const auto& a: attr_inputs) {
+		attr_indices.push_back(std::stoi(a.substr(9)));
+	}
+	std::sort(attr_indices.begin(), attr_indices.end());
+	uint32_t num_attrs     = static_cast<uint32_t>(attr_indices.size());
+	uint32_t output_stride = layout.record_stride_vec4;
+	bool     has_clip      = layout.has_clip;
+
+	std::vector<uint32_t> attr_widths(num_attrs, 1);
+	for (uint32_t i = 0; i < num_attrs; ++i) {
+		std::regex  var_decl(R"(^\s*%in_attr_)" + std::to_string(i) +
+		                         R"(\s*=\s*OpVariable\s+(%\S+)\s+Input\s*$)",
+		                     kMultilineRegex);
+		std::smatch m;
+		if (std::regex_search(source, m, var_decl)) {
+			std::string ptr_type = m[1];
+			std::regex ptr_re(R"(^\s*)" + ptr_type + R"(\s*=\s*OpTypePointer\s+Input\s+(%\S+)\s*$)",
+			                  kMultilineRegex);
+			if (std::regex_search(source, m, ptr_re)) {
+				std::string data_type = m[1];
+				std::regex  vec_re(R"(^\s*)" + data_type +
+				                       R"(\s*=\s*OpTypeVector\s+%float\s+(\d+)\s*$)",
+				                   kMultilineRegex);
+				if (std::regex_search(source, m, vec_re)) {
+					attr_widths[i] = std::stoi(m[1]);
+				} else {
+					attr_widths[i] = 1;
+				}
+			}
+		}
+	}
+
+	std::regex  main_re(R"(^\s*OpEntryPoint\s+Vertex\s+(%\S+)\s+"main".*$)", kMultilineRegex);
+	std::smatch m_main;
+	if (!std::regex_search(source, m_main, main_re)) return {};
+	std::string main_name = m_main[1];
+
+	std::string modified = std::regex_replace(source, main_re,
+	                                          "OpEntryPoint GLCompute " + main_name +
+	                                              " \"main\" %capture_global_id %capture_input "
+	                                              "%capture_output %capture_ids\nOpExecutionMode " +
+	                                              main_name + " LocalSize 1 1 1");
+
+	std::regex ptr_replace(R"((OpTypePointer\s+)(Input|Output)(\s+))");
+	modified = std::regex_replace(modified, ptr_replace, "$1Private$3");
+
+	std::regex var_replace(R"((OpVariable\s+%\S+\s+)(Input|Output)(\s*$))", kMultilineRegex);
+	modified = std::regex_replace(modified, var_replace, "$1Private$3");
+
+	std::istringstream       iss(modified);
+	std::string              line;
+	std::vector<std::string> lines;
+	std::set<std::string>    all_interface = inputs;
+	all_interface.insert(outputs.begin(), outputs.end());
+
+	while (std::getline(iss, line)) {
+		bool skip = false;
+		if (line.find("OpDecorate ") != std::string::npos) {
+			for (const auto& var: all_interface) {
+				if (line.find("OpDecorate " + var) != std::string::npos) {
+					skip = true;
+					break;
+				}
+			}
+		}
+		if (line.find("OpMemberDecorate %gl_PerVertex") != std::string::npos) skip = true;
+		if (line.find("OpDecorate %gl_PerVertex Block") != std::string::npos) skip = true;
+		if (line.find("OpCapability ClipDistance") != std::string::npos) skip = true;
+		if (!skip) lines.push_back(line);
+	}
+
+	std::vector<std::string> annotations = {
+	    "OpDecorate %capture_global_id BuiltIn GlobalInvocationId",
+	    "OpDecorate %capture_array ArrayStride 16",
+	    "OpMemberDecorate %capture_block 0 Offset 0",
+	    "OpDecorate %capture_block Block",
+	    "OpDecorate %capture_input DescriptorSet 1",
+	    "OpDecorate %capture_input Binding 0",
+	    "OpDecorate %capture_input NonWritable",
+	    "OpDecorate %capture_output DescriptorSet 1",
+	    "OpDecorate %capture_output Binding 1",
+	    "OpDecorate %capture_ids_array ArrayStride 8",
+	    "OpMemberDecorate %capture_ids_block 0 Offset 0",
+	    "OpDecorate %capture_ids_block Block",
+	    "OpDecorate %capture_ids DescriptorSet 1",
+	    "OpDecorate %capture_ids Binding 2",
+	    "OpDecorate %capture_ids NonWritable"};
+
+	const char* named_constants[] = {"zero", "one", "two", "three", "four", "five", "six"};
+	auto        get_const         = [&](int k) -> std::string {
+		if (k < 7) return std::string("%capture_") + named_constants[k];
+		return "%capture_const_" + std::to_string(k);
+	};
+
+	std::vector<std::string> declarations = {
+	    "%capture_uvec3 = OpTypeVector %uint 3",
+	    "%capture_id_pointer = OpTypePointer Input %capture_uvec3",
+	    "%capture_global_id = OpVariable %capture_id_pointer Input",
+	    "%capture_array = OpTypeRuntimeArray %v4float",
+	    "%capture_block = OpTypeStruct %capture_array",
+	    "%capture_buffer_pointer = OpTypePointer StorageBuffer %capture_block",
+	    "%capture_input = OpVariable %capture_buffer_pointer StorageBuffer",
+	    "%capture_output = OpVariable %capture_buffer_pointer StorageBuffer",
+	    "%capture_uvec2 = OpTypeVector %uint 2",
+	    "%capture_ids_array = OpTypeRuntimeArray %capture_uvec2",
+	    "%capture_ids_block = OpTypeStruct %capture_ids_array",
+	    "%capture_ids_pointer = OpTypePointer StorageBuffer %capture_ids_block",
+	    "%capture_ids = OpVariable %capture_ids_pointer StorageBuffer",
+	    "%capture_ids_element_pointer = OpTypePointer StorageBuffer %capture_uvec2",
+	    "%capture_element_pointer = OpTypePointer StorageBuffer %v4float",
+	    "%capture_private_element_pointer = OpTypePointer Private %v4float"};
+
+	int max_const = std::max({6u, num_attrs, output_stride + 1u});
+	for (int k = 0; k <= max_const; ++k) {
+		declarations.push_back(get_const(k) + " = OpConstant %uint " + std::to_string(k));
+	}
+
+	std::string clip_pointer = "%capture_clip_pointer";
+	if (has_clip) {
+		std::regex  ptr_priv(R"(^\s*(%\S+)\s*=\s*OpTypePointer\s+Private\s+%float\s*$)",
+		                     kMultilineRegex);
+		std::smatch m_priv;
+		if (std::regex_search(modified, m_priv, ptr_priv)) {
+			clip_pointer = m_priv[1];
+		} else {
+			declarations.push_back(clip_pointer + " = OpTypePointer Private %float");
+		}
+	}
+	declarations.push_back("%capture_zero_float = OpConstant %float 0");
+
+	std::vector<std::string> start = {
+	    "%capture_id = OpLoad %capture_uvec3 %capture_global_id",
+	    "%capture_invocation = OpCompositeExtract %uint %capture_id 0",
+	    "%capture_original_ids_pointer = OpAccessChain %capture_ids_element_pointer %capture_ids "
+	    "%capture_zero %capture_invocation",
+	    "%capture_original_ids = OpLoad %capture_uvec2 %capture_original_ids_pointer",
+	    "%capture_vertex = OpCompositeExtract %uint %capture_original_ids 0",
+	    "%capture_instance = OpCompositeExtract %uint %capture_original_ids 1",
+	    "%capture_vertex_signed = OpBitcast %int %capture_vertex",
+	    "%capture_instance_signed = OpBitcast %int %capture_instance",
+	    "OpStore %gl_VertexIndex %capture_vertex_signed",
+	    "OpStore %gl_InstanceIndex %capture_instance_signed",
+	    "%capture_input_base = OpIMul %uint %capture_invocation " + get_const(num_attrs),
+	    "%capture_output_base = OpIMul %uint %capture_invocation " + get_const(output_stride)};
+
+	for (uint32_t i = 0; i < num_attrs; ++i) {
+		start.push_back("%capture_input_index_" + std::to_string(i) +
+		                " = OpIAdd %uint %capture_input_base " + get_const(i));
+		start.push_back("%capture_input_ptr_" + std::to_string(i) +
+		                " = OpAccessChain %capture_element_pointer %capture_input %capture_zero "
+		                "%capture_input_index_" +
+		                std::to_string(i));
+		start.push_back("%capture_attribute_" + std::to_string(i) +
+		                " = OpLoad %v4float %capture_input_ptr_" + std::to_string(i));
+		uint32_t w = attr_widths[i];
+		if (w == 1) {
+			start.push_back("%capture_decoded_" + std::to_string(i) +
+			                " = OpCompositeExtract %float %capture_attribute_" + std::to_string(i) +
+			                " 0");
+			start.push_back("OpStore %in_attr_" + std::to_string(i) + " %capture_decoded_" +
+			                std::to_string(i));
+		} else if (w < 4) {
+			std::string comps;
+			for (uint32_t c = 0; c < w; ++c)
+				comps += " " + std::to_string(c);
+			start.push_back("%capture_decoded_" + std::to_string(i) + " = OpVectorShuffle %v" +
+			                std::to_string(w) + "float %capture_attribute_" + std::to_string(i) +
+			                " %capture_attribute_" + std::to_string(i) + comps);

🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

Declare the narrow vector result type instead of assuming %v2float/%v3float exists.

OpVectorShuffle needs a result type id. Line 421 builds that id as "%v" + width + "float", which relies on the disassembly friendly name of an OpTypeVector %float 2 or %float 3 declaration in the source module. A vertex shader with only vec4 and scalar attributes declares no 2- or 3-component float vector, so the id is undefined and tools.Assemble fails. In KYTY_FINAL builds the EXIT_IF(!tools.Assemble(...)) guard in perVertexPrototype.cpp is compiled out, so the path continues with empty bytecode.

Emit the needed vector types under %capture_ names, and deduplicate them against the source the same way %capture_uvec2/%capture_uvec3 are handled at lines 502-516.

🐛 Sketch of the fix
+	std::set<uint32_t> needed_widths;
+	for (uint32_t i = 0; i < num_attrs; ++i) {
+		if (attr_widths[i] == 2 || attr_widths[i] == 3) needed_widths.insert(attr_widths[i]);
+	}
+	for (uint32_t w: needed_widths) {
+		declarations.push_back("%capture_vec" + std::to_string(w) +
+		                       " = OpTypeVector %float " + std::to_string(w));
+	}

Then reference %capture_vec<w> in the OpVectorShuffle, and reuse the existing replacement loop pattern to drop the declaration when the source already declares that type.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-20 20:24 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/715#discussion_r4057993493) On `src/graphics/host_gpu/renderer/perVertexTransform.cpp` line 423 (outdated): ```diff @@ -0,0 +1,972 @@ +#include "graphics/host_gpu/renderer/perVertexTransform.h" + +#include "common/file.h" +#include "common/threads.h" +#include "kytyGitVersion.h" + +#include <algorithm> +#include <atomic> +#include <cstdint> +#include <cstring> +#include <fmt/format.h> +#include <map> +#include <regex> +#include <set> +#include <spirv/unified1/spirv.hpp> +#include <sstream> +#include <string> +#include <vector> +#include <xxhash.h> + +namespace Libs::Graphics { + +// Older MSVC STL always matches ^/$ at line boundaries, but has no multiline +// flag. The macro arrived with the implementation of the standard option. +#if defined(_MSVC_STL_VERSION) && !defined(_REGEX_LEGACY_MULTILINE_MODE) +static constexpr auto kMultilineRegex = std::regex_constants::ECMAScript; +#else +static constexpr auto kMultilineRegex = + std::regex_constants::ECMAScript | std::regex_constants::multiline; +#endif + +// The transformed modules are assembled as SPIR-V 1.5. Since 1.4, the entry +// interface must include all used globals, including resources and Private I/O. +// Source shaders can be 1.3, whose interfaces only list Input/Output variables. +static std::string CompleteEntryPointInterface(const std::string& source) { + std::istringstream lines(source); + std::string line, interfaces; + while (std::getline(lines, line)) { + std::istringstream tokens(line); + std::string id, equals, opcode; + tokens >> id >> equals >> opcode; + if (opcode == "OpFunction") break; + if (equals == "=" && opcode == "OpVariable") interfaces += " " + id; + } + const std::regex entry_re(R"((OpEntryPoint\s+\S+\s+%\S+\s+"[^"]*")[^\r\n]*)"); + return std::regex_replace(source, entry_re, "$1" + interfaces); +} + +bool DerivePerVertexLayout(const std::string& vs_source, const std::string& ps_source, + PerVertexLayout& layout, + std::map<uint32_t, std::string>& vs_param_vars) { + std::regex var_re(R"(^\s*(%\S+)\s*=\s*OpVariable\s+%\S+\s+Output\s*$)", kMultilineRegex); + std::set<std::string> vs_outputs; + for (auto it = std::sregex_iterator(vs_source.begin(), vs_source.end(), var_re); + it != std::sregex_iterator(); ++it) { + vs_outputs.insert((*it)[1]); + } + if (vs_outputs.empty()) return false; + + bool has_clip = vs_outputs.find("%gl_ClipDistance") != vs_outputs.end(); + + vs_param_vars.clear(); + for (const auto& var: vs_outputs) { + if (var == "%outPerVertex" || var == "%gl_ClipDistance" || var == "%gl_PointSize") continue; + std::regex loc_re(R"(^\s*OpDecorate\s+)" + var + R"(\s+Location\s+(\d+)\s*$)", + kMultilineRegex); + std::smatch m; + if (std::regex_search(vs_source, m, loc_re)) { + uint32_t loc = static_cast<uint32_t>(std::stoul(m[1])); + vs_param_vars[loc] = var; + } + } + + layout.has_clip = has_clip; + layout.num_params = static_cast<uint32_t>(vs_param_vars.size()); + layout.param_locations_and_slots.clear(); + layout.location_to_slot.clear(); + + uint32_t current_slot = 1; + for (const auto& [loc, var_name]: vs_param_vars) { + layout.location_to_slot[loc] = current_slot; + layout.param_locations_and_slots.push_back({loc, current_slot}); + current_slot++; + } + + if (has_clip) { + layout.clip_slot = current_slot; + layout.record_stride_vec4 = current_slot + 1; + } else { + layout.clip_slot = UINT32_MAX; + layout.record_stride_vec4 = current_slot; + } + if (layout.location_to_slot.find(31) != layout.location_to_slot.end()) { + return false; + } + + std::regex pv_re(R"(^\s*OpDecorate\s+(%\S+)\s+PerVertexKHR\s*$)", kMultilineRegex); + std::vector<std::string> pv_vars; + for (auto it = std::sregex_iterator(ps_source.begin(), ps_source.end(), pv_re); + it != std::sregex_iterator(); ++it) { + pv_vars.push_back((*it)[1]); + } + if (pv_vars.empty()) return false; + + for (const auto& pv_var: pv_vars) { + std::regex loc_re(R"(^\s*OpDecorate\s+)" + pv_var + R"(\s+Location\s+(\d+)\s*$)", + kMultilineRegex); + std::smatch m; + if (!std::regex_search(ps_source, m, loc_re)) { + return false; + } + uint32_t loc = static_cast<uint32_t>(std::stoul(m[1])); + auto it = layout.location_to_slot.find(loc); + if (it == layout.location_to_slot.end()) { + return false; + } + uint32_t slot = it->second; + if (slot >= layout.clip_slot) { + return false; + } + if (slot >= layout.record_stride_vec4) { + return false; + } + } + return true; +} + +std::string GenerateReplayVertexSpvasm(const PerVertexLayout& layout) { + std::vector<std::string> entry_interfaces = {"%gl_VertexIndex", "%_", "%capture_output"}; + for (const auto& [loc, _]: layout.param_locations_and_slots) { + entry_interfaces.push_back("%out_param_" + std::to_string(loc)); + } + entry_interfaces.push_back("%out_primitive_id"); + + std::string entry_iface_str; + for (size_t i = 0; i < entry_interfaces.size(); ++i) { + if (i > 0) entry_iface_str += " "; + entry_iface_str += entry_interfaces[i]; + } + + std::ostringstream ss; + ss << "OpCapability Shader\n"; + if (layout.has_clip) { + ss << "OpCapability ClipDistance\n"; + } + ss << "OpMemoryModel Logical GLSL450\n"; + ss << "OpEntryPoint Vertex %main \"main\" " << entry_iface_str << "\n"; + ss << "OpDecorate %gl_VertexIndex BuiltIn VertexIndex\n"; + ss << "OpDecorate %gl_PerVertex Block\n"; + ss << "OpMemberDecorate %gl_PerVertex 0 BuiltIn Position\n"; + ss << "OpMemberDecorate %gl_PerVertex 1 BuiltIn PointSize\n"; + if (layout.has_clip) { + ss << "OpMemberDecorate %gl_PerVertex 2 BuiltIn ClipDistance\n"; + } + ss << "OpDecorate %_runtimearr_v4float ArrayStride 16\n"; + ss << "OpDecorate %CaptureOutput Block\n"; + ss << "OpMemberDecorate %CaptureOutput 0 NonWritable\n"; + ss << "OpMemberDecorate %CaptureOutput 0 Offset 0\n"; + ss << "OpDecorate %capture_output NonWritable\n"; + ss << "OpDecorate %capture_output Binding 1\n"; + ss << "OpDecorate %capture_output DescriptorSet 1\n"; + for (const auto& [loc, _]: layout.param_locations_and_slots) { + ss << "OpDecorate %out_param_" << loc << " Location " << loc << "\n"; + } + ss << "OpDecorate %out_primitive_id Flat\n"; + ss << "OpDecorate %out_primitive_id Location 31\n"; + ss << "%void = OpTypeVoid\n"; + ss << "%fn = OpTypeFunction %void\n"; + ss << "%uint = OpTypeInt 32 0\n"; + ss << "%int = OpTypeInt 32 1\n"; + ss << "%float = OpTypeFloat 32\n"; + ss << "%v4float = OpTypeVector %float 4\n"; + ss << "%uint_0 = OpConstant %uint 0\n"; + ss << "%uint_1 = OpConstant %uint 1\n"; + ss << "%uint_3 = OpConstant %uint 3\n"; + ss << "%int_0 = OpConstant %int 0\n"; + ss << "%int_2 = OpConstant %int 2\n"; + ss << "%stride_const = OpConstant %uint " << layout.record_stride_vec4 << "\n"; + for (const auto& [loc, slot]: layout.param_locations_and_slots) { + ss << "%slot_const_" << slot << " = OpConstant %uint " << slot << "\n"; + } + if (layout.has_clip) { + ss << "%clip_slot_const = OpConstant %uint " << layout.clip_slot << "\n"; + ss << "%_arr_float_1 = OpTypeArray %float %uint_1\n"; + ss << "%_ptr_StorageBuffer_float = OpTypePointer StorageBuffer %float\n"; + ss << "%_ptr_Output_float = OpTypePointer Output %float\n"; + ss << "%gl_PerVertex = OpTypeStruct %v4float %float %_arr_float_1\n"; + } else { + ss << "%gl_PerVertex = OpTypeStruct %v4float %float\n"; + } + ss << "%_ptr_Output_gl_PerVertex = OpTypePointer Output %gl_PerVertex\n"; + ss << "%_ = OpVariable %_ptr_Output_gl_PerVertex Output\n"; + ss << "%_ptr_Input_int = OpTypePointer Input %int\n"; + ss << "%gl_VertexIndex = OpVariable %_ptr_Input_int Input\n"; + ss << "%_runtimearr_v4float = OpTypeRuntimeArray %v4float\n"; + ss << "%CaptureOutput = OpTypeStruct %_runtimearr_v4float\n"; + ss << "%_ptr_StorageBuffer_CaptureOutput = OpTypePointer StorageBuffer %CaptureOutput\n"; + ss << "%capture_output = OpVariable %_ptr_StorageBuffer_CaptureOutput StorageBuffer\n"; + ss << "%_ptr_StorageBuffer_v4float = OpTypePointer StorageBuffer %v4float\n"; + ss << "%_ptr_Output_v4float = OpTypePointer Output %v4float\n"; + ss << "%_ptr_Output_uint = OpTypePointer Output %uint\n"; + ss << "%out_primitive_id = OpVariable %_ptr_Output_uint Output\n"; + for (const auto& [loc, _]: layout.param_locations_and_slots) { + ss << "%out_param_" << loc << " = OpVariable %_ptr_Output_v4float Output\n"; + } + + ss << "%main = OpFunction %void None %fn\n"; + ss << "%label = OpLabel\n"; + ss << "%vidx_i = OpLoad %int %gl_VertexIndex\n"; + ss << "%vidx = OpBitcast %uint %vidx_i\n"; + ss << "%base = OpIMul %uint %vidx %stride_const\n"; + ss << "%pos_ptr = OpAccessChain %_ptr_StorageBuffer_v4float %capture_output %int_0 %base\n"; + ss << "%pos_val = OpLoad %v4float %pos_ptr\n"; + ss << "%out_pos_ptr = OpAccessChain %_ptr_Output_v4float %_ %int_0\n"; + ss << "OpStore %out_pos_ptr %pos_val\n"; + for (const auto& [loc, slot]: layout.param_locations_and_slots) { + ss << "%param_idx_" << slot << " = OpIAdd %uint %base %slot_const_" << slot << "\n"; + ss << "%param_ptr_" << slot + << " = OpAccessChain %_ptr_StorageBuffer_v4float %capture_output %int_0 %param_idx_" + << slot << "\n"; + ss << "%param_val_" << slot << " = OpLoad %v4float %param_ptr_" << slot << "\n"; + ss << "OpStore %out_param_" << loc << " %param_val_" << slot << "\n"; + } + if (layout.has_clip) { + ss << "%clip_idx = OpIAdd %uint %base %clip_slot_const\n"; + ss << "%clip_src_ptr = OpAccessChain %_ptr_StorageBuffer_float %capture_output %int_0 " + "%clip_idx %uint_0\n"; + ss << "%clip_val = OpLoad %float %clip_src_ptr\n"; + ss << "%clip_dst_ptr = OpAccessChain %_ptr_Output_float %_ %int_2 %uint_0\n"; + ss << "OpStore %clip_dst_ptr %clip_val\n"; + } + ss << "%primid = OpUDiv %uint %vidx %uint_3\n"; + ss << "OpStore %out_primitive_id %primid\n"; + ss << "OpReturn\n"; + ss << "OpFunctionEnd\n"; + return ss.str(); +} + +std::string LowerVertexToCompute(const std::string& source, const PerVertexLayout& layout, + const std::map<uint32_t, std::string>& vs_param_vars) { + std::regex var_re(R"(^\s*(%\S+)\s*=\s*OpVariable\s+%\S+\s+(Input|Output)\s*$)", + kMultilineRegex); + std::set<std::string> inputs, outputs, attr_inputs; + for (auto it = std::sregex_iterator(source.begin(), source.end(), var_re); + it != std::sregex_iterator(); ++it) { + std::string name = (*it)[1]; + std::string storage = (*it)[2]; + if (storage == "Input") { + inputs.insert(name); + if (name.rfind("%in_attr_", 0) == 0) attr_inputs.insert(name); + } else { + outputs.insert(name); + } + } + std::vector<int> attr_indices; + for (const auto& a: attr_inputs) { + attr_indices.push_back(std::stoi(a.substr(9))); + } + std::sort(attr_indices.begin(), attr_indices.end()); + uint32_t num_attrs = static_cast<uint32_t>(attr_indices.size()); + uint32_t output_stride = layout.record_stride_vec4; + bool has_clip = layout.has_clip; + + std::vector<uint32_t> attr_widths(num_attrs, 1); + for (uint32_t i = 0; i < num_attrs; ++i) { + std::regex var_decl(R"(^\s*%in_attr_)" + std::to_string(i) + + R"(\s*=\s*OpVariable\s+(%\S+)\s+Input\s*$)", + kMultilineRegex); + std::smatch m; + if (std::regex_search(source, m, var_decl)) { + std::string ptr_type = m[1]; + std::regex ptr_re(R"(^\s*)" + ptr_type + R"(\s*=\s*OpTypePointer\s+Input\s+(%\S+)\s*$)", + kMultilineRegex); + if (std::regex_search(source, m, ptr_re)) { + std::string data_type = m[1]; + std::regex vec_re(R"(^\s*)" + data_type + + R"(\s*=\s*OpTypeVector\s+%float\s+(\d+)\s*$)", + kMultilineRegex); + if (std::regex_search(source, m, vec_re)) { + attr_widths[i] = std::stoi(m[1]); + } else { + attr_widths[i] = 1; + } + } + } + } + + std::regex main_re(R"(^\s*OpEntryPoint\s+Vertex\s+(%\S+)\s+"main".*$)", kMultilineRegex); + std::smatch m_main; + if (!std::regex_search(source, m_main, main_re)) return {}; + std::string main_name = m_main[1]; + + std::string modified = std::regex_replace(source, main_re, + "OpEntryPoint GLCompute " + main_name + + " \"main\" %capture_global_id %capture_input " + "%capture_output %capture_ids\nOpExecutionMode " + + main_name + " LocalSize 1 1 1"); + + std::regex ptr_replace(R"((OpTypePointer\s+)(Input|Output)(\s+))"); + modified = std::regex_replace(modified, ptr_replace, "$1Private$3"); + + std::regex var_replace(R"((OpVariable\s+%\S+\s+)(Input|Output)(\s*$))", kMultilineRegex); + modified = std::regex_replace(modified, var_replace, "$1Private$3"); + + std::istringstream iss(modified); + std::string line; + std::vector<std::string> lines; + std::set<std::string> all_interface = inputs; + all_interface.insert(outputs.begin(), outputs.end()); + + while (std::getline(iss, line)) { + bool skip = false; + if (line.find("OpDecorate ") != std::string::npos) { + for (const auto& var: all_interface) { + if (line.find("OpDecorate " + var) != std::string::npos) { + skip = true; + break; + } + } + } + if (line.find("OpMemberDecorate %gl_PerVertex") != std::string::npos) skip = true; + if (line.find("OpDecorate %gl_PerVertex Block") != std::string::npos) skip = true; + if (line.find("OpCapability ClipDistance") != std::string::npos) skip = true; + if (!skip) lines.push_back(line); + } + + std::vector<std::string> annotations = { + "OpDecorate %capture_global_id BuiltIn GlobalInvocationId", + "OpDecorate %capture_array ArrayStride 16", + "OpMemberDecorate %capture_block 0 Offset 0", + "OpDecorate %capture_block Block", + "OpDecorate %capture_input DescriptorSet 1", + "OpDecorate %capture_input Binding 0", + "OpDecorate %capture_input NonWritable", + "OpDecorate %capture_output DescriptorSet 1", + "OpDecorate %capture_output Binding 1", + "OpDecorate %capture_ids_array ArrayStride 8", + "OpMemberDecorate %capture_ids_block 0 Offset 0", + "OpDecorate %capture_ids_block Block", + "OpDecorate %capture_ids DescriptorSet 1", + "OpDecorate %capture_ids Binding 2", + "OpDecorate %capture_ids NonWritable"}; + + const char* named_constants[] = {"zero", "one", "two", "three", "four", "five", "six"}; + auto get_const = [&](int k) -> std::string { + if (k < 7) return std::string("%capture_") + named_constants[k]; + return "%capture_const_" + std::to_string(k); + }; + + std::vector<std::string> declarations = { + "%capture_uvec3 = OpTypeVector %uint 3", + "%capture_id_pointer = OpTypePointer Input %capture_uvec3", + "%capture_global_id = OpVariable %capture_id_pointer Input", + "%capture_array = OpTypeRuntimeArray %v4float", + "%capture_block = OpTypeStruct %capture_array", + "%capture_buffer_pointer = OpTypePointer StorageBuffer %capture_block", + "%capture_input = OpVariable %capture_buffer_pointer StorageBuffer", + "%capture_output = OpVariable %capture_buffer_pointer StorageBuffer", + "%capture_uvec2 = OpTypeVector %uint 2", + "%capture_ids_array = OpTypeRuntimeArray %capture_uvec2", + "%capture_ids_block = OpTypeStruct %capture_ids_array", + "%capture_ids_pointer = OpTypePointer StorageBuffer %capture_ids_block", + "%capture_ids = OpVariable %capture_ids_pointer StorageBuffer", + "%capture_ids_element_pointer = OpTypePointer StorageBuffer %capture_uvec2", + "%capture_element_pointer = OpTypePointer StorageBuffer %v4float", + "%capture_private_element_pointer = OpTypePointer Private %v4float"}; + + int max_const = std::max({6u, num_attrs, output_stride + 1u}); + for (int k = 0; k <= max_const; ++k) { + declarations.push_back(get_const(k) + " = OpConstant %uint " + std::to_string(k)); + } + + std::string clip_pointer = "%capture_clip_pointer"; + if (has_clip) { + std::regex ptr_priv(R"(^\s*(%\S+)\s*=\s*OpTypePointer\s+Private\s+%float\s*$)", + kMultilineRegex); + std::smatch m_priv; + if (std::regex_search(modified, m_priv, ptr_priv)) { + clip_pointer = m_priv[1]; + } else { + declarations.push_back(clip_pointer + " = OpTypePointer Private %float"); + } + } + declarations.push_back("%capture_zero_float = OpConstant %float 0"); + + std::vector<std::string> start = { + "%capture_id = OpLoad %capture_uvec3 %capture_global_id", + "%capture_invocation = OpCompositeExtract %uint %capture_id 0", + "%capture_original_ids_pointer = OpAccessChain %capture_ids_element_pointer %capture_ids " + "%capture_zero %capture_invocation", + "%capture_original_ids = OpLoad %capture_uvec2 %capture_original_ids_pointer", + "%capture_vertex = OpCompositeExtract %uint %capture_original_ids 0", + "%capture_instance = OpCompositeExtract %uint %capture_original_ids 1", + "%capture_vertex_signed = OpBitcast %int %capture_vertex", + "%capture_instance_signed = OpBitcast %int %capture_instance", + "OpStore %gl_VertexIndex %capture_vertex_signed", + "OpStore %gl_InstanceIndex %capture_instance_signed", + "%capture_input_base = OpIMul %uint %capture_invocation " + get_const(num_attrs), + "%capture_output_base = OpIMul %uint %capture_invocation " + get_const(output_stride)}; + + for (uint32_t i = 0; i < num_attrs; ++i) { + start.push_back("%capture_input_index_" + std::to_string(i) + + " = OpIAdd %uint %capture_input_base " + get_const(i)); + start.push_back("%capture_input_ptr_" + std::to_string(i) + + " = OpAccessChain %capture_element_pointer %capture_input %capture_zero " + "%capture_input_index_" + + std::to_string(i)); + start.push_back("%capture_attribute_" + std::to_string(i) + + " = OpLoad %v4float %capture_input_ptr_" + std::to_string(i)); + uint32_t w = attr_widths[i]; + if (w == 1) { + start.push_back("%capture_decoded_" + std::to_string(i) + + " = OpCompositeExtract %float %capture_attribute_" + std::to_string(i) + + " 0"); + start.push_back("OpStore %in_attr_" + std::to_string(i) + " %capture_decoded_" + + std::to_string(i)); + } else if (w < 4) { + std::string comps; + for (uint32_t c = 0; c < w; ++c) + comps += " " + std::to_string(c); + start.push_back("%capture_decoded_" + std::to_string(i) + " = OpVectorShuffle %v" + + std::to_string(w) + "float %capture_attribute_" + std::to_string(i) + + " %capture_attribute_" + std::to_string(i) + comps); ``` _🎯 Functional Correctness_ | _🟠 Major_ | _🏗️ Heavy lift_ **Declare the narrow vector result type instead of assuming `%v2float`/`%v3float` exists.** `OpVectorShuffle` needs a result type id. Line 421 builds that id as `"%v" + width + "float"`, which relies on the disassembly friendly name of an `OpTypeVector %float 2` or `%float 3` declaration in the source module. A vertex shader with only `vec4` and scalar attributes declares no 2- or 3-component float vector, so the id is undefined and `tools.Assemble` fails. In `KYTY_FINAL` builds the `EXIT_IF(!tools.Assemble(...))` guard in `perVertexPrototype.cpp` is compiled out, so the path continues with empty bytecode. Emit the needed vector types under `%capture_` names, and deduplicate them against the source the same way `%capture_uvec2`/`%capture_uvec3` are handled at lines 502-516. <details> <summary>🐛 Sketch of the fix</summary> ```diff + std::set<uint32_t> needed_widths; + for (uint32_t i = 0; i < num_attrs; ++i) { + if (attr_widths[i] == 2 || attr_widths[i] == 3) needed_widths.insert(attr_widths[i]); + } + for (uint32_t w: needed_widths) { + declarations.push_back("%capture_vec" + std::to_string(w) + + " = OpTypeVector %float " + std::to_string(w)); + } ``` Then reference `%capture_vec<w>` in the `OpVectorShuffle`, and reuse the existing replacement loop pattern to drop the declaration when the source already declares that type. </details> <!-- fingerprinting:phantom:medusa:komodo --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:e5b5ce4d0b3c810d92422650 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠Cosmo on GitHub · 2026-09-25 17:46 UTC · original

Wouldn't it be better to implement this as a MoltenVK PR?

**@⁠Cosmo** on GitHub · 2026-09-25 17:46 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/715#issuecomment-5836872822) Wouldn't it be better to implement this as a MoltenVK PR?
Author
Owner

@⁠carbonimax on GitHub · 2026-09-26 11:57 UTC · original

I agree that generic PerVertexKHR support would be better implemented in MoltenVK/SPIRV-Cross. The current PR is an opt-in application-side prototype with a restricted draw contract, so it would need to be generalized rather than moved unchanged.
MoltenVK already has vertex-output capture machinery for tessellation, which looks like a useful starting point to investigate. A sensible next step would be to extract a standalone Vulkan reproducer and assess an upstream implementation. Kyty-specific input handling and application-side caching could remain separate.
Would you prefer keeping this PR as a draft while that approach is investigated?

**@⁠carbonimax** on GitHub · 2026-09-26 11:57 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/715#issuecomment-5846066399) I agree that generic PerVertexKHR support would be better implemented in MoltenVK/SPIRV-Cross. The current PR is an opt-in application-side prototype with a restricted draw contract, so it would need to be generalized rather than moved unchanged. MoltenVK already has vertex-output capture machinery for tessellation, which looks like a useful starting point to investigate. A sensible next step would be to extract a standalone Vulkan reproducer and assess an upstream implementation. Kyty-specific input handling and application-side caching could remain separate. Would you prefer keeping this PR as a draft while that approach is investigated?
Author
Owner

@⁠carbonimax on GitHub · 2026-10-01 16:05 UTC · original

@⁠Cosmo Following up on the direction discussed above: this PR is now a draft. The active work has moved to generic PerVertexKHR support in MoltenVK/SPIRV-Cross; the application-side prototype is disabled in the current Kyty integration. That implementation remains experimental, with the public extension closed and no claim of complete Vulkan conformance.

The branch and its historical tests remain available. The PR description now separates that prototype evidence from the current integration, so it should not be treated as ready to merge.

**@⁠carbonimax** on GitHub · 2026-10-01 16:05 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/715#issuecomment-5935373147) @⁠Cosmo Following up on the direction discussed above: this PR is now a draft. The active work has moved to generic PerVertexKHR support in MoltenVK/SPIRV-Cross; the application-side prototype is disabled in the current Kyty integration. That implementation remains experimental, with the public extension closed and no claim of complete Vulkan conformance. The branch and its historical tests remain available. The PR description now separates that prototype evidence from the current integration, so it should not be treated as ready to merge.
Author
Owner

@⁠wuboo on GitHub · 2026-10-02 19:28 UTC · original · edited 2026-10-02 19:43 UTC

Thanks for this stack. I have been running Astro Bot (PPSA21564) on it on an M3 Max (macOS 26, Rosetta 2, MoltenVK) and profiling the first minutes of a new game. Some notes that may save you time.

Fix you may want: 16 vertex attributes in the prototype unpack. The unpack push constants are sized for Vulkan's 128-byte minimum (12 attribute descriptors), so a VS with 15 attributes exits. Astro Bot hits this right after the intro. MoltenVK allows 4096 bytes. The patch widens the descriptor array to 16, grows the packed count from 4 to 5 bits so 16 does not wrap to 0, and skips a draw past 16 (logged once per hash) instead of exiting. One commit on top of this PR's head (33a30b4c), with tests updated: github.com/wuboo/KytyPS5@575d3b9a (branch wuboo:pv-prototype-16-attributes). per_vertex_transform_tests pass on that branch; the GPU execution test passed on my integration stack.

Where the GPU time goes (first level, after fixing the SSE4a traps, see #839):

  • The prototype path (pv-unpack → pv-capture → replay pass per draw) carries about 75–85% of GPU time per frame: ~290 prototype draws and ~9.5 M "vertices" per flip in the heavy part of the level. Per-command-buffer timestamps put it at roughly replay 120 / capture 72 / unpack 64 ms per flip. MoltenVK only samples timestamps at encoder boundaries, so this is per-stage, not per-shader.
  • The PS that trigger it read v_interp_mov P10/P20. Most of these are manual interpolation of packed f16/snorm16 halves, mixed with ordinary GetAttribute. MoltenVK's SPIRV-Cross rejects PerVertexKHR in MSL, so a native path is not available.

Things that did not help, measured A/B on the same binary:

  • Merging consecutive replay passes. Prototype batches close almost every draw: 99.6% have one draw, mostly on capture-cache slot reuse and SET_UCONFIG_REG_INDIRECT/INDEX. Keeping them open halved the passes for +3%. Skipping the flush on UCONFIG writes also broke rendering.
  • Device-local scratch buffers: +10% / −4% depending on the window, so not stable.
  • Capturing once per unique vertex instead of per index element. Unique slots are only 18–42% of the index stream in the level, but the extra compaction pass made it 12–14% slower. It also needs care with ballots: a VS whose ballot only feeds an any/none branch still produced a triangle grid on the menu sky.
  • Rewriting the packed-half interpolation into native interpolants. Values matched to 0 ulp in isolation, but in-game lighting broke and there was no speedup.

What did correlate with frame rate was the number of prototype draws itself (dropping two VS hashes worth of draws gave +55%). My current guess is the dependent compute → compute → render transitions per draw, roughly 870 per frame, rather than shader cost. I'm measuring barrier counts next and will report back if grouping the compute stages of consecutive draws helps.

**@⁠wuboo** on GitHub · 2026-10-02 19:28 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/715#issuecomment-5959881524) · edited 2026-10-02 19:43 UTC Thanks for this stack. I have been running Astro Bot (PPSA21564) on it on an M3 Max (macOS 26, Rosetta 2, MoltenVK) and profiling the first minutes of a new game. Some notes that may save you time. **Fix you may want: 16 vertex attributes in the prototype unpack.** The unpack push constants are sized for Vulkan's 128-byte minimum (12 attribute descriptors), so a VS with 15 attributes exits. Astro Bot hits this right after the intro. MoltenVK allows 4096 bytes. The patch widens the descriptor array to 16, grows the packed count from 4 to 5 bits so 16 does not wrap to 0, and skips a draw past 16 (logged once per hash) instead of exiting. One commit on top of this PR's head (33a30b4c), with tests updated: https://github.com/wuboo/KytyPS5/commit/575d3b9a (branch `wuboo:pv-prototype-16-attributes`). `per_vertex_transform_tests` pass on that branch; the GPU execution test passed on my integration stack. **Where the GPU time goes (first level, after fixing the SSE4a traps, see #839):** - The prototype path (`pv-unpack` → `pv-capture` → replay pass per draw) carries about 75–85% of GPU time per frame: ~290 prototype draws and ~9.5 M "vertices" per flip in the heavy part of the level. Per-command-buffer timestamps put it at roughly replay 120 / capture 72 / unpack 64 ms per flip. MoltenVK only samples timestamps at encoder boundaries, so this is per-stage, not per-shader. - The PS that trigger it read `v_interp_mov` P10/P20. Most of these are manual interpolation of packed f16/snorm16 halves, mixed with ordinary `GetAttribute`. MoltenVK's SPIRV-Cross rejects `PerVertexKHR` in MSL, so a native path is not available. **Things that did not help, measured A/B on the same binary:** - Merging consecutive replay passes. Prototype batches close almost every draw: 99.6% have one draw, mostly on capture-cache slot reuse and `SET_UCONFIG_REG_INDIRECT`/`INDEX`. Keeping them open halved the passes for +3%. Skipping the flush on UCONFIG writes also broke rendering. - Device-local scratch buffers: +10% / −4% depending on the window, so not stable. - Capturing once per unique vertex instead of per index element. Unique slots are only 18–42% of the index stream in the level, but the extra compaction pass made it 12–14% slower. It also needs care with ballots: a VS whose ballot only feeds an any/none branch still produced a triangle grid on the menu sky. - Rewriting the packed-half interpolation into native interpolants. Values matched to 0 ulp in isolation, but in-game lighting broke and there was no speedup. What did correlate with frame rate was the number of prototype draws itself (dropping two VS hashes worth of draws gave +55%). My current guess is the dependent compute → compute → render transitions per draw, roughly 870 per frame, rather than shader cost. I'm measuring barrier counts next and will report back if grouping the compute stages of consecutive draws helps.
Author
Owner

@⁠wuboo on GitHub · 2026-10-06 04:34 UTC · original

Follow-up from macOS (M3 Max, Rosetta 2, MoltenVK), Astro Bot: a change on top of the prototype path that measurably helps here, in case it's useful for this PR.

Fused unpack into capture. Today every prototype draw runs an unpack dispatch that decodes the VS vertex attributes into an attribute_buffer (plus an id_buffer), a barrier, then the capture dispatch that reads them back. With the change, the capture shader decodes the V#/format and the index itself from the raw guest buffers. That removes per draw one dispatch, one barrier, one descriptor set and two transient buffer allocations. VertexIndex/InstanceIndex are computed in the shader.

Commits (two, on our macOS stack, behind KYTY_OPT_ON=pv_fused_unpack, default off): wuboo:pv-fused-unpack

  • 623ff3aa per-vertex prototype: fused unpack into capture
  • b56f0e8a GPU equivalence test for the fused capture

Correctness: a GPU test compares the capture records of the old and new paths bit for bit for 7 draw shapes (linear, indexed 16-bit, instancing, first_vertex, negative and positive vertex_offset, out-of-range vertices) × 4 formats (float32x3, unorm8x4, unorm16x2, half4). Frame diffs in the game show no regression; scene-to-scene differences we saw were timing, not image changes.

Performance (two off/on pairs per scene, same power conditions):

scene off on change
menu 28.98 30.28 fps +4.5%
ship 4.21 4.56 +8.3%
chase 20.95 27.57 +32%
first level (same geometry range) 9.47 11.18 +18%

On this host the gain comes mostly from the CP thread (fewer allocations/dispatches per draw under Rosetta), not from GPU time. It may matter less on native x86, but the per-draw work it removes is the same.

**@⁠wuboo** on GitHub · 2026-10-06 04:34 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/715#issuecomment-6009407100) Follow-up from macOS (M3 Max, Rosetta 2, MoltenVK), Astro Bot: a change on top of the prototype path that measurably helps here, in case it's useful for this PR. **Fused unpack into capture.** Today every prototype draw runs an unpack dispatch that decodes the VS vertex attributes into an `attribute_buffer` (plus an `id_buffer`), a barrier, then the capture dispatch that reads them back. With the change, the capture shader decodes the V#/format and the index itself from the raw guest buffers. That removes per draw one dispatch, one barrier, one descriptor set and two transient buffer allocations. VertexIndex/InstanceIndex are computed in the shader. Commits (two, on our macOS stack, behind `KYTY_OPT_ON=pv_fused_unpack`, default off): `wuboo:pv-fused-unpack` - 623ff3aa per-vertex prototype: fused unpack into capture - b56f0e8a GPU equivalence test for the fused capture **Correctness:** a GPU test compares the capture records of the old and new paths bit for bit for 7 draw shapes (linear, indexed 16-bit, instancing, first_vertex, negative and positive vertex_offset, out-of-range vertices) × 4 formats (float32x3, unorm8x4, unorm16x2, half4). Frame diffs in the game show no regression; scene-to-scene differences we saw were timing, not image changes. **Performance** (two off/on pairs per scene, same power conditions): | scene | off | on | change | |---|---|---|---| | menu | 28.98 | 30.28 fps | +4.5% | | ship | 4.21 | 4.56 | +8.3% | | chase | 20.95 | 27.57 | +32% | | first level (same geometry range) | 9.47 | 11.18 | +18% | On this host the gain comes mostly from the CP thread (fewer allocations/dispatches per draw under Rosetta), not from GPU time. It may matter less on native x86, but the per-draw work it removes is the same.
Author
Owner

@⁠carbonimax on GitHub · 2026-10-10 22:57 UTC · original

Closing: superseded by the MoltenVK/SPIRV-Cross PerVertexKHR work (KhronosGroup/MoltenVK#2858, KhronosGroup/SPIRV-Cross#2699). The branch stays available for reference.

**@⁠carbonimax** on GitHub · 2026-10-10 22:57 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/715#issuecomment-6103080759) Closing: superseded by the MoltenVK/SPIRV-Cross PerVertexKHR work (KhronosGroup/MoltenVK#2858, KhronosGroup/SPIRV-Cross#2699). The branch stays available for reference.

Pull request closed

This discussion has been locked. Commenting is limited to contributors.
No description provided.